v36: fix big screen empty content (with files)

#7
by bep40 - opened
This view is limited to 50 files because it contains too many changes. See the raw diff here.
.gitattributes CHANGED
@@ -33,7 +33,3 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
- frontend/images/vai-logo.png filter=lfs diff=lfs merge=lfs -text
37
- frontend/images/vai-logo-carved.webp filter=lfs diff=lfs merge=lfs -text
38
- frontend/images/vai-logo-carved@2x.webp filter=lfs diff=lfs merge=lfs -text
39
- frontend/images/vai-logo-stone@2x.webp filter=lfs diff=lfs merge=lfs -text
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
.rebuild-v101 DELETED
@@ -1 +0,0 @@
1
- Force rebuild v101 — remove LegendRing + LegendWall — 2026-04-08
 
 
.rebuild-v101b DELETED
@@ -1 +0,0 @@
1
- FORCE REBUILD v101b — LegendRing + LegendWall removal — 2026-11-23
 
 
.rebuild-v101c DELETED
@@ -1 +0,0 @@
1
- FORCE REBUILD v101c — bump cache-bust to ?v=101 — 2026-11-23
 
 
.rebuild-v108-exact DELETED
@@ -1 +0,0 @@
1
- FORCE REBUILD v108-exact — restore e419952 build: pristine app.js (103478 B) + cave3d.js (75909 B) via curl, strict patch chain v32..v103, esbuild guard from e419952. Fixes React error #31 caused by truncated cave3d.js. — 2026-11-23
 
 
.rebuild-v109 DELETED
@@ -1 +0,0 @@
1
- Force rebuild v109 — ao vang + logo V.AI STUDIO sau ao + tay gon + dung yen khong chay + bo bang trong 3 bong den mai ban nguyet — 2026-11-23
 
 
.rebuild-v112 DELETED
@@ -1 +0,0 @@
1
- v112: nhan vat (ao vang polo, ten + so ao khong nguoc, mat day du, thap hon) + giang sinh giua hang
 
 
.rebuild-v113 DELETED
@@ -1 +0,0 @@
1
- v113: tay lien khop vai (deltoid), so+logo het nguoc (mat cong 1 phia), bang ten mat TRUOC ao — verified bang render Chromium that
 
 
.rebuild-v116 DELETED
@@ -1,107 +0,0 @@
1
- V116f — ROOT CAUSE FOUND (23/11/2026, tu log runtime THAT)
2
-
3
- Trieu chung trong log:
4
- "Co loi xay ra" | vaiLogoTex is not defined
5
- GET /static/app.bundle.js?v=115 <- v116 DA RESTORE (muc G chi chay khi
6
- khong restore, va muc G dat ?v=116)
7
- GET /images/vai-logo-stone.webp ... <- KHONG co /images/vai-logo.png
8
- => loader poster chua bao gio chay
9
-
10
- Chuoi nhan qua nhan:
11
- patch_v116.mjs CO top-level await:
12
- const esbuild = await import('esbuild') (trong khoi `if`, module scope)
13
- Buoc 8 cua patch_v116e validate file do bang target 'es2020'.
14
- esbuild TU CHOI top-level await khi target < es2022 => nem loi
15
- => buoc 8 that bai => v116e GHI LAI BAN GOC patch_v116.mjs
16
- (anchor VaiSteleText CHET van con nguyen)
17
- => v116 dung cutFn(s,'VaiSteleText') -> khong khop 'VaiSteleText2(' -> null
18
- -> throw -> fatal -> RESTORE CA 5 FILE, exit 0, build XANH, ?v=115
19
- => patch_v116b VAN CHAY (no khong biet v116 da restore), tim thay
20
- <mesh position={[0, 0.99, -0.306]} rotation-y={Math.PI}> (co san tu v115)
21
- va chen vao `{vaiLogoTex && ( ... )}` + `map={_v116NumTex(p.number)}`
22
- — hai ten CHI do patch_v116 dinh nghia, gio khong ton tai
23
- => ReferenceError khi PlayerAvatar render => ErrorBoundary => mat TOAN BO app
24
- (te hon v115, truoc khi co v116)
25
-
26
- DA SUA (3 lop, phong thu doc lap):
27
-
28
- 1. patch_v116e.mjs buoc 8: target 'es2022' (va loi chi ve target/top-level
29
- await duoc coi la DAT chu khong restore). <- SUA NGUYEN NHAN
30
- 2. patch_v116d.mjs V116f: neu app.js KHONG co function useVaiLogoTex( /
31
- _v116NumTex( (tuc la v116 da restore) thi VO HIEU HOA tham chieu mo coi
32
- TRUOC khi ghi:
33
- {vaiLogoTex && ( -> { false && (
34
- map={vaiLogoTex} -> map={null}
35
- map={_v116NumTex(p.number)} -> map={_v115BackTex(p.number)}
36
- (JSX element khong duoc tao vi && short-circuit nen cac map= ben trong
37
- khong bao gio duoc danh gia). Guard: neu van con vaiLogoTex/_v116NumTex
38
- thi KHONG ghi file. <- CHAN CRASH DU CO RESTORE LAN NUA
39
- 3. Thu tu chay giu nguyen: v116e -> v116 -> v116a -> v116b -> v116c -> v116d,
40
- nen v116d luon la lop don cuoi cung truoc khi bundle.
41
-
42
- VI SAO BUOC 7 CUA v116e VAN ON: no chi la "all-or-nothing" tren 4 anchor
43
- (cut / signature / return shape / guard section-F) da kiem tra TUNG BYTE
44
- trong patch_v116.mjs:
45
- const cutV = cutFn(s, 'VaiSteleText')
46
- function VaiSteleText({ width = 2.3 }) {
47
- return (\n <>\n <planeGeometry args={[width, width * 0.1875]} />
48
- if ((hom.match(/function VaiSteleText\(/g) || []).length !== 1) bad.push('VaiSteleText != 1')
49
- => ca 4 deu CO va khop. Chi buoc 8 (validate) la sai target, va do la thu da sua.
50
-
51
- CACH XAC NHAN SAU KHI REBUILD (1 request, khong can token):
52
- GET https://bep40-hangmu-docker.hf.space/version.json
53
- {"id":"v116"} => TOAN BO chuoi da ap dung (5 tinh nang dang chay)
54
- {"id":"v115"} => van restore => doc tiep /api/logs (200 dong client
55
- error gan nhat, khong can auth) de xem ten loi
56
- Neu app crash: /api/logs se co entry "vaiLogoTex is not defined" hoac
57
- tuong tu. Neu v116d lop 2 hoat dong thi app se KHONG crash ma chi thieu
58
- tinh nang (log se co "[v116d] WARN: patch_v116 da RESTORE ...").
59
-
60
- --------------------------------------------------------------------------------
61
- NOI DUNG GOC (giu lai de tham khao)
62
- --------------------------------------------------------------------------------
63
- v116 gom 6 patch, chay trong build/esbuild.config.mjs truoc khi bundle:
64
-
65
- patch_v116.mjs - LOGO AO: VAI_LOGO_URL + _v116LoadLogoTex (TextureLoader, crossOrigin,
66
- cache module) + useVaiLogoTex (state vi load bat dong bo) + _v116NumTex
67
- - CHU V.AI STUDIO TRONG HANG -> drawImage anh poster:
68
- cave3d makeBannerTex(), home3d drawRedPlaque() + VaiSteleText2()
69
- - BINH CHON: POLL_QUESTIONS 4 cau MU -> 4 cau AI; hook vote ->
70
- _att_bump(name,"votes"); nap "votes" vao _att_load/_att_pull
71
- (VONG LAP quet moi khoi `_att_stats[str(k)[:60]] = {`, in ra so
72
- khoi da sua — "2 khoi" moi la dung); _att_score +votes*3;
73
- /api/attendance/top tra "votes"; cot thu 4 o BangVangDiemDanh
74
- - VIDEO: thay effect tao iframe -> /api/video-proxy&loop=0,
75
- nghe hangmu-ended (playerState===0) -> bai ke
76
- - PLAYLIST: .board-playbar-toggle + panel an (.is-open)
77
- patch_v116a.mjs - chon bai NGAU NHIEN luc vao hang (playIdx<0 -> Math.floor(random))
78
- patch_v116b.mjs - LUNG AO = poster that 0.36x0.32 (lon hon 0.26x0.244 cua
79
- backPlateTex), boc trong guard vaiLogoTex de khong con mieng
80
- TRANG khi map=null; texture du phong _v116FallbackTex khi 404
81
- patch_v116c.mjs - khoi phuc POLLING 60s cua BangVangDiemDanh; tra canvas ve
82
- 1024x1180 + rotation -0.42 rad
83
- patch_v116d.mjs - sua loi cat ham "React. React.useEffect" + (V116f) don tham
84
- chieu mo coi khi v116 restore
85
- patch_v116e.mjs - SUA ANCHOR CHET: cut + signature + return shape + guard
86
- section-F cua patch_v116.mjs (v95 tao VaiSteleText, v97 XOA
87
- va thay bang VaiSteleText2). Chay DAU TIEN.
88
-
89
- Da kiem tra TUNG BYTE trong repo (khong phai suy doan):
90
- VaiSteleText v95 tao -> v97 XOA => anchor CHET
91
- makeBannerTex patch_v114 TAO; v115 chi transform-syntax cave3d.js
92
- (KHONG ghi), nen khong the lam lech
93
- POLL_QUESTIONS = [ backend.py, khong patch nao xoa
94
- vote handler 2 dong backend.py 46-54KB, byte-exact
95
- _att_stats.setdefault KHONG co trong repo — patch_v83 tao luc build, v85
96
- viet lai, v86/v89 chi chen them; v116 la patch DUY NHAT
97
- sua vung nay
98
- <mesh position={[0, 0.99, -0.306]} rotation-y={Math.PI}> patch_v115 tao
99
- frontend/images/vai-logo.png CO THAT (417.7 KB, LFS)
100
- RP_OLD / TX_OLD home3d.js la COPY (34.5KB, khong bi cat)
101
-
102
- Log build can doc (thu tu):
103
- [v116e] OK: 1) ... 8) <- thieu muc nao = anchor do lech
104
- [v116] patch_v116.mjs exit=0
105
- [v116b] DONE [v116c] DONE [v116d] DONE
106
- [esbuild] v116 markers present: ...
107
- "[v116] SKIPPED (restored)" => doc WARN ngay TREN do.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.static-cache.json DELETED
@@ -1 +0,0 @@
1
- {"files": {"version.json": "v120", "static/app.bundle.js": "v120", "static/editor.css": "v119", "styles/main.css": "v115", "styles/home.css": "v115", "styles/cavescreen.css": "v115", "styles/pachie.css": "v115", "styles/locate.css": "v115", "styles/heritage.css": "v115", "styles/modal.css": "v115", "styles/slab.css": "v116", "styles/playlist.css": "v116", "styles/chatgpt.css": "v117", "styles/rain.css": "v117", "styles/room-vote.css": "v117", "styles/invite.css": "v117", "styles/theme-picker.css": "v118", "styles/ai-news.css": "v118", "styles/donate.css": "v118", "styles/toolbar.css": "v118", "styles/portal.css": "v118", "styles/voice.css": "v119", "styles/pause-menu.css": "v119", "styles/pause-backdrops.css": "v119", "styles/cave-chat.css": "v119"}}
 
 
.v100-patch-marker DELETED
@@ -1 +0,0 @@
1
- PATCH_MARKER: remove LegendRing and LegendWall from CaveScene render - 2026-04-08
 
 
Df92 DELETED
@@ -1,235 +0,0 @@
1
- FROM node:20-slim AS build
2
- WORKDIR /build
3
-
4
- # Frontend build deps
5
- COPY build/package.json build/package-lock.json* ./
6
- COPY frontend/app.js frontend/cave3d.js frontend/cavehelpers.js frontend/home3d.js frontend/store.js frontend/pwa.js frontend/scoreboard.js frontend/voice.js frontend/minigames.js frontend/env.js frontend/index.html ./frontend/
7
- COPY build/esbuild.config.mjs ./
8
- COPY backend.py .
9
- COPY video_proxy.py .
10
- COPY patch_boards.mjs .
11
- COPY patch_v32.mjs .
12
- COPY patch_v33.mjs .
13
- COPY patch_v34.mjs .
14
- COPY patch_v35.mjs .
15
- COPY patch_v36.mjs .
16
- COPY patch_v37.mjs .
17
- COPY patch_v38.mjs .
18
- COPY patch_v39.mjs .
19
- COPY patch_v40.mjs .
20
- COPY patch_v41.mjs .
21
- COPY patch_v42.mjs .
22
- COPY patch_v43.mjs .
23
- COPY patch_v44.mjs .
24
- COPY patch_v45.mjs .
25
- COPY patch_v46.mjs .
26
- COPY patch_v47.mjs .
27
- COPY patch_v48.mjs .
28
- COPY patch_v50.mjs .
29
- COPY patch_v51.mjs .
30
- COPY patch_v60.mjs .
31
- COPY patch_v61.mjs .
32
- COPY patch_v62.mjs .
33
- COPY patch_v63.mjs .
34
- COPY patch_v64.mjs .
35
- COPY patch_v67.mjs .
36
- COPY patch_v68.mjs .
37
- COPY patch_v68a.mjs .
38
- COPY patch_v69.mjs .
39
- COPY patch_v70.mjs .
40
- COPY patch_v71.mjs .
41
- COPY patch_v72.mjs .
42
- COPY patch_v73.mjs .
43
- COPY patch_v74.mjs .
44
- COPY patch_v75.mjs .
45
- COPY patch_v76.mjs .
46
- COPY patch_v77.mjs .
47
- COPY patch_v78.mjs .
48
- COPY patch_v82.mjs .
49
- COPY patch_v83.mjs .
50
- COPY patch_v84.mjs .
51
- COPY patch_v85.mjs .
52
- COPY patch_v86.mjs .
53
- COPY patch_v87.mjs .
54
- COPY patch_v88.mjs .
55
- COPY patch_v89.mjs .
56
- COPY patch_v90.mjs .
57
- COPY patch_v91.mjs .
58
- COPY patch_v92.mjs .
59
-
60
- # v26: patch_boards.mjs đưa 2 bảng TRẬN GẦN NHẤT / TRẬN SẮP TỚI về z=71 (2 bên lối vào)
61
- # + bump VERSION_ID v25 -> v26 để khớp cache-bust ?v=26.
62
- # v32: patch_v32.mjs — YouTube fallback canvas (màn hình không trống khi YT bị chặn)
63
- # + các bảng TO & tách xa; VERSION_ID v31 -> v32.
64
- # v33: patch_v33.mjs — bỏ bảng đỏ chắn cửa, cờ MU, bảng tỷ số gần lối vào; VERSION_ID v32 -> v33.
65
- # v34: patch_v34.mjs — màn hình phát video QUA PROXY VNEWS; nhân vật quay mặt vào hang; VERSION_ID v33 -> v34.
66
- # v35: patch_v35.mjs — PROXY THẬT VNEWS /s + hangmu-playing + Player.rotation=π; VERSION_ID v34 -> v35.
67
- # v36: patch_v36.mjs — onMsg 'hangmu-playing' trung thực + embed youtube.com (xem ở VN); VERSION_ID v35 -> v36.
68
- # v37: patch_v37.mjs — self-avatar quay mặt vào trong; mọi video qua proxy; _yt_meta chuẩn hoá; VERSION_ID v36 -> v37.
69
- # v38: patch_v38.mjs — serve index.html Cache-Control no-store; VERSION_ID v37 -> v38.
70
- # v39: patch_v39.mjs — _yt_meta chuẩn hoá ID/watch/embed/shorts; log "videos first"; VERSION_ID v38 -> v39.
71
- # v40: patch_v40.mjs — LOG VERIFICATION-ONLY; VERSION_ID v39 -> v40.
72
- # v41: patch_v41.mjs — bỏ gửi volume lúc load (video chạy muted); kéo slider mới unmute; VERSION_ID v40 -> v41.
73
- # v42: patch_v42.mjs — camState.yaw π->0 (camera nhìn vào hang thấy board); VERSION_ID v41 -> v42.
74
- # v43: patch_v43.mjs — /api/video-proxy nội bộ render embed www.youtube.com; VERSION_ID v42 -> v43.
75
- # v44: patch_v44.mjs — homography CHUẨN acko.net (có scale bw×bh); VERSION_ID v43 -> v44.
76
- # v45: patch_v45.mjs — FALLBACK CENTER khi board ngoài tầm nhìn + /api/diag; VERSION_ID v44 -> v45.
77
- # v46: patch_v46.mjs — video TƯỜNG AI VNEWS (mp4 autoplay tuần tự) + billboard hết méo + /api/board/video; VERSION_ID v45 -> v46.
78
- # v47: patch_v47.mjs — nguồn video FPT Bóng Đá (YouTube) từ Tường AI + HẾT MÉO 100% (luôn billboard) + chỉ hiển thị trên màn hình; VERSION_ID v46 -> v47.
79
- # v48: patch_v48.mjs — playlist = YouTube RSS channel FPT Bóng Đá (UC4LvrpNXujjbGOS4RDvr41g) qua rss2json + cache TTL 10 phút + fix "t1 is not defined"; VERSION_ID v47 -> v48.
80
- # v50: patch_v50.mjs — regex cache-bust ?v=NN -> ?v=50 + fix dứt điểm cleanup "t1 is not defined"; VERSION_ID -> v50.
81
- # v51: patch_v51.mjs — SỬA LỖI IndentationError: unexpected indent (dòng "if out:") mà chuỗi
82
- # v46->v47->v48 để lại (đuôi body bị dup + lệch thục lề). SPLICE LẠI vùng _board_vnews
83
- # bằng khối sạch hợp lệ 100% + VERSION_ID -> v51 + cache-bust ?v=NN -> ?v=51.
84
- # v52: patch_v52.mjs — ÉP BUỘC YouTube dùng /api/video-proxy (phát VN) + harden hangmu-playing
85
- # (debounce playing:false, không ẩn khi miss probe) + video_proxy probe hardening.
86
- # v53: patch_v53.mjs — SỬA video_proxy.py (SyntaxError từ v52 patch hỏng f-string). Thay TOÀN BỘ
87
- # render_video_proxy bằng bản sạch: chỉ youtube.com, probe ngưỡng 8, tell guard played flag.
88
- # v54: patch_v54.mjs — SỬA video_proxy.py (SyntaxError: f-string empty expression). Escape HOÀN CHỈNH
89
- # tất cả brace JS `{{`/`}}` trong Python f-string triple-quoted. Chỉ youtube.com, probe 8,
90
- # tell guard: played flag, không gửi false sau true.
91
- # v55: patch_v55.mjs — XÓA fallback 6s (t3) ẩn iframe + probe 15s. LOGIC HIỂN THỊ: dùng
92
- # homography CHÍNH XÁC (quadMatrix) khi board nhìn thẳng (tỷ lệ ~1) → video FULL
93
- # khít board 24:14. Chỉ dùng billboard khi nghiêng mạnh (tỷ lệ > 1.3).
94
- # v56: patch_v56.mjs — TRIỆT ĐỂ FIX VIDEO: Thay TOÀN BỘ effect video BoardVideoOverlay.
95
- # - iframe.src = /api/video-proxy cho YouTube (phát VN)
96
- # - onMsg: nghe hangmu-playing (playing:true/false) + onReady/infoDelivery
97
- # - XÓA HẾT t1/t2/t3 fallback 6s — chỉ probe 15s interval
98
- # - RAF loop: homography CHÍNH XÁC (quadMatrix) → video full khít board 24:14
99
- # v57: patch_v57.mjs — KHẮC PHỤC SURGICAL: iframe.src nocookie -> /api/video-proxy,
100
- # onMsg thêm hangmu-playing handler, XÓA t3 6s fallback, probe 15s.
101
- # v58: patch_v58.mjs — THAY THẾ HOÀN TOÀN EFFECT VIDEO (exact boundaries từ source hiện tại).
102
- # - iframe.src = /api/video-proxy (www.youtube.com, phát VN)
103
- # - onMsg: nghe hangmu-playing (true/false) + onReady/infoDelivery
104
- # - KHÔNG có t1/t2/t3 fallback 6s
105
- # - CHỈ probe interval 15000ms
106
- # v59: patch_v59.mjs — FIX DEFINITIVE video_proxy.py: THAY TOÀN BỘ render_video_proxy.
107
- # - Chỉ www.youtube.com (KHÔNG nocookie fallback)
108
- # - Probe ngưỡng 8 (~10s)
109
- # - tell() guard: played flag, không gửi false sau true
110
- # - f-string escape HOÀN CHỈNH: JS braces = {{ }}, Python placeholders = {{var}}
111
- # v61: patch_v61.mjs — BẢNG THƠ ngoài cửa hang: BILLBOARD ĐỘNG (luôn quay về
112
- # người dùng, sửa lệch 56.8°), AUTO-FIT theo frustum (4 câu thơ luôn trọn
113
- # khung, trước đây 2/4 góc ngoài khung trên mobile), texture 1600x680 font
114
- # 84px (không ép ngang, không cắt chữ). MOBILE nhỏ hơn DESKTOP thật sự
115
- # (prop `small` trước đây là dead code). VERSION_ID v60 -> v61.
116
- # v62: patch_v62.mjs — DỌN TRANG HOME: bỏ dòng footer "Trang của người hâm mộ,
117
- # không liên kết chính thức với Manchester United · Điều khoản & quyền riêng tư";
118
- # đổi slogan home-lede -> "Nơi học sĩ không biết AI vào hang và ra hang sau mỗi
119
- # lần VIBE CODE"; dời bảng bia HANG TU TRÍ AI / AI V.AI STUDIO xuống dưới, nằm
120
- # ngay TRÊN nhóm nút Group Zalo + Cài đặt app + Thông báo (home.css: bia hàng 2,
121
- # nút hàng 3). VERSION_ID v61 -> v62, cache-bust ?v=62.
122
- # v63: patch_v63.mjs — bảng thơ ngoài hang LÊN TRÊN CÙNG (depthTest=false +
123
- # renderOrder cao), bảng logo V.AI STUDIO đứng trước dòng "Hang Tu Trí AI"
124
- # trong DOM, bỏ áo vàng / nút ủng hộ / bảng nền video; VERSION_ID -> v63.
125
- # v64: patch_v64.mjs — KHÔI PHỤC CỘT TREO LOGO "V.AI STUDIO" (patch v33 đã bỏ
126
- # mount <PostAndPlaque />) → dựng lại ở lề phải sân trước, phóng 1.25x, bảng
127
- # logo nằm CAO hơn tấm bảng HTML .home-panel nên không bị che; bảng thơ
128
- # ngoài hang -> "Thơ Hang AI"; bảng thơ trong hang -> "Thơ Nhẫn AI" + 4 câu
129
- # mới (Thay đổi tư duy điều trước tiên / Vibe code AI đừng có nghiện / Tinh
130
- # thần học hỏi cần cầu tiến / Đừng nghĩ làm app hiệu quả liền) + DỜI sang
131
- # TRÁI xa màn hình lớn (-36, 5.0, -2); XOÁ "bảng trắng" trên màn hình lớn
132
- # (watchdog 9s ẩn iframe không phát, cho lớp LED có nội dung lộ ra); dòng
133
- # chữ bảng Hang Tu Trí AI -> "Tu học ở trong hang, ứng dụng ở ngoài hang".
134
- # VERSION_ID v63 -> v64, cache-bust ?v=64.
135
- # v67: patch_v67.mjs — 3 VIỆC: bỏ bảng "Thế hệ vàng", EPL→Tin AI, Ngày này năm xưa→Điểm danh.
136
- # v68: patch_v68.mjs — 7 VIỆC: fix cột logo V.AI STUDIO [-6.5,0,62] scale 1.4,
137
- # bỏ bảng "Thế hệ vàng", EPL→"Bảng tin AI hôm nay" (Google News RSS fallback),
138
- # "Ngày này năm xưa"→"Bảng vàng điểm danh", backend /api/ai-news + /api/attendance/top,
139
- # hook visits+chats, collapsible chat panel. VERSION_ID -> v68, cache-bust ?v=68.
140
- # v68a: patch_v68a.mjs — fix ai-news fetch (gzip + Accept-Encoding: identity).
141
- # v69: patch_v69.mjs — 5 VIỆC: fix cột logo V.AI STUDIO [-6.8,0,5.2] scale 2.0,
142
- # v70: patch_v70.mjs — 5 VIỆC: fix logo V.AI STUDIO [-6.8,0,5.2] scale 2.0,
143
- # v71: patch_v71.mjs — 5 VIỆC: logo V.AI STUDIO HTML overlay,
144
- # v72: patch_v72.mjs — 5 VIỆC: logo V.AI STUDIO HTML overlay,
145
- # v73: patch_v73.mjs — verify logo overlay, fix chat toggle CSS,
146
- # v74: patch_v74.mjs — fix chat toggle CSS in correct location.
147
- # v75: patch_v75.mjs — create cavescreen.css with chat toggle fix.
148
- # v76: patch_v76.mjs — add chat toggle CSS to existing cavescreen.css.
149
- # v77: patch_v77.mjs — fix index.html path, update cache-bust.
150
- # v78: patch_v78.mjs — fix CSS path, add chat toggle CSS with !important.
151
- # VERSION_ID -> v78, cache-bust ?v=92.
152
- # VERSION_ID -> v77, cache-bust ?v=92.
153
- # VERSION_ID -> v76, cache-bust ?v=92.
154
- # VERSION_ID -> v75, cache-bust ?v=92.
155
- # VERSION_ID -> v74, cache-bust ?v=92.
156
- # verify AI news position, verify attendance hooks.
157
- # VERSION_ID -> v73, cache-bust ?v=92.
158
- # chat toggle CSS fix, AI news left wall, attendance hooks.
159
- # VERSION_ID -> v72, cache-bust ?v=92.
160
- # chat toggle floating button, AI news left wall + images, attendance hooks.
161
- # VERSION_ID -> v71, cache-bust ?v=92.
162
- # chat toggle visible, attendance hooks, AI news enhanced (VN datetime +
163
- # real images + modal viewer), move board to left side. VERSION_ID -> v70, cache-bust ?v=92.
164
- # chat toggle visible, attendance hooks fix, AI news enhanced (VN datetime +
165
- # thumbnails + modal viewer). VERSION_ID -> v69, cache-bust ?v=92.
166
- RUN npm install --no-audit --no-fund 2>&1 | tail -2 && \
167
- node patch_boards.mjs && \
168
- node patch_v32.mjs && \
169
- node patch_v33.mjs && \
170
- node patch_v34.mjs && \
171
- node patch_v35.mjs && \
172
- node patch_v36.mjs && \
173
- node patch_v37.mjs && \
174
- node patch_v38.mjs && \
175
- node patch_v39.mjs && \
176
- node patch_v40.mjs && \
177
- node patch_v41.mjs && \
178
- node patch_v42.mjs && \
179
- node patch_v43.mjs && \
180
- node patch_v44.mjs && \
181
- node patch_v45.mjs && \
182
- node patch_v46.mjs && \
183
- node patch_v47.mjs && \
184
- node patch_v48.mjs && \
185
- node patch_v50.mjs && \
186
- node patch_v51.mjs && \
187
- node patch_v60.mjs && \
188
- node patch_v61.mjs && \
189
- node patch_v62.mjs && \
190
- node patch_v63.mjs && \
191
- node patch_v64.mjs && \
192
- node patch_v67.mjs && \
193
- node patch_v68.mjs && \
194
- node patch_v68a.mjs && \
195
- node patch_v69.mjs && \
196
- node patch_v70.mjs && \
197
- node patch_v71.mjs && \
198
- node patch_v72.mjs && \
199
- node patch_v73.mjs && \
200
- node patch_v74.mjs && \
201
- node patch_v75.mjs && \
202
- node patch_v76.mjs && \
203
- node patch_v77.mjs && \
204
- node patch_v78.mjs && \
205
- node patch_v82.mjs && \
206
- node patch_v83.mjs && \
207
- node patch_v84.mjs && \
208
- node patch_v85.mjs && \
209
- node patch_v86.mjs && \
210
- node patch_v87.mjs && \
211
- node patch_v88.mjs && \
212
- node patch_v89.mjs && \
213
- node patch_v90.mjs && \
214
- node patch_v91.mjs && \
215
- node patch_v92.mjs && \
216
- node esbuild.config.mjs && \
217
- ls -la frontend/app.bundle.js
218
-
219
- # ============ Stage 2: Python runtime ============
220
- FROM python:3.11-slim
221
- WORKDIR /app
222
- # index.html TỪ BUILD (đã patch cache-bust ?v=92) — không COPY source
223
- COPY --from=build /build/frontend/index.html ./frontend/index.html
224
- COPY --from=build /build/backend.py .
225
- # V51 FAIL-FAST: validate Python syntax NGAY — không cho IndexError/IndentError lọt ra runtime
226
- RUN python -m py_compile backend.py
227
- RUN pip install --no-cache-dir fastapi uvicorn[standard] huggingface_hub
228
- COPY --from=build /build/video_proxy.py .
229
- COPY --from=build /build/frontend/app.bundle.js ./frontend/app.bundle.js
230
- COPY --from=build /build/frontend/env.js ./frontend/env.js
231
- COPY frontend/images ./frontend/images
232
- COPY frontend/styles ./frontend/styles
233
- COPY frontend/fonts ./frontend/fonts
234
- COPY frontend/pwa ./frontend/pwa
235
- CMD ["python", "backend.py"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile CHANGED
@@ -1,285 +1,60 @@
1
  FROM node:20-slim AS build
2
  WORKDIR /build
3
 
4
- # curl + CA certs are needed to restore the pristine sources from the commit.
5
- RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates && rm -rf /var/lib/apt/lists/*
6
-
7
- # Build deps + every frontend module EXCEPT app.js and cave3d.js.
8
- # Those two are larger than the Hub's per-file content-upload cap, so the copies
9
- # currently committed to the repo are TRUNCATED (app.js 61.4KB vs 103.5KB,
10
- # cave3d.js 71.4KB vs 75.9KB). A truncated cave3d.js loses ~4.5KB out of the
11
- # MIDDLE of a <mesh> block, so a meshStandardMaterial lands in a child slot
12
- # instead of as a prop, and React throws error #31 ("objects are not valid as a
13
- # React child", listing MeshStandardMaterial keys). esbuild cannot catch this --
14
- # it only validates syntax, never JSX semantics. These two files must therefore
15
- # never be used as build input; they are re-downloaded and verified below.
16
  COPY build/package.json build/package-lock.json* ./
17
- COPY frontend/cavehelpers.js frontend/home3d.js frontend/store.js frontend/pwa.js frontend/scoreboard.js frontend/voice.js frontend/minigames.js frontend/env.js frontend/index.html ./frontend/
18
  COPY build/esbuild.config.mjs ./
19
  COPY backend.py .
20
- COPY video_proxy.py .
21
- COPY patch_*.mjs .
22
-
23
- # Restore pristine app.js + cave3d.js from commit e419952, then VERIFY.
24
- # A silent truncation is exactly what broke the last deploy, so assert on:
25
- # 1) exact byte counts of the known-good commit
26
- # 2) the anchors patch_v63.mjs needs in cave3d.js
27
- # 3) the anchors patch_v98.mjs (logs as v100) needs in app.js
28
- RUN curl -fsSL -o frontend/app.js "https://huggingface.co/spaces/bep40/hangmu-docker/raw/e419952b16af1e86df9c14df816d551861da17c5/frontend/app.js" && \
29
- curl -fsSL -o frontend/cave3d.js "https://huggingface.co/spaces/bep40/hangmu-docker/raw/e419952b16af1e86df9c14df816d551861da17c5/frontend/cave3d.js" && \
30
- ls -la frontend/app.js frontend/cave3d.js && \
31
- APP=$(stat -c%s frontend/app.js) && \
32
- CAVE=$(stat -c%s frontend/cave3d.js) && \
33
- echo "[restore] app.js=$APP bytes cave3d.js=$CAVE bytes" && \
34
- test "$APP" = "103478" || { echo "[restore] FATAL: app.js is $APP bytes, expected 103478 (truncated download)"; exit 1; } && \
35
- test "$CAVE" = "75909" || { echo "[restore] FATAL: cave3d.js is $CAVE bytes, expected 75909 (truncated download)"; exit 1; } && \
36
- grep -q "BOARD.w / 2 - 1.5" frontend/cave3d.js || { echo "[restore] FATAL: cave3d.js missing Board() anchor for patch_v63"; exit 1; } && \
37
- grep -q "intensity={30} distance={16} decay={1.8}" frontend/cave3d.js || { echo "[restore] FATAL: cave3d.js missing pointLight anchor for patch_v63"; exit 1; } && \
38
- grep -q "const isMuKit = (p.kit == null)" frontend/app.js || { echo "[restore] FATAL: app.js missing isMuKit anchor for patch_v98"; exit 1; } && \
39
- grep -q "map={isMuKit ? muKitTex() : null}" frontend/app.js || { echo "[restore] FATAL: app.js missing body material anchor for patch_v98"; exit 1; } && \
40
- echo "[restore] OK: exact byte counts + all patch anchors verified"
41
-
42
- RUN curl -fsSL -o frontend/vai-stele-poster.png "https://huggingface.co/spaces/bep40/VAIHOME/resolve/main/public/poster_1794291583927.png" || true
43
-
44
- # Patch chain identical to commit e419952 (boards, v32..v48, v50/51, v60..v64,
45
- # v67..v78, v82..v98, v101..v103). STRICT -- no "|| true" masking: the pristine
46
- # sources are restored and anchor-verified above, so every patch must apply.
47
- #
48
- # V109 (patch_v109.mjs) runs late because it must see the FINAL post-chain
49
- # source. It:
50
- # 1) flips the DEFAULT kit to yellow + V.AI STUDIO back logo (patch_v98 left
51
- # the default red, so the yellow kit was only used if you picked it);
52
- # 2) widens the shoulders to 0.335 so the arms leave the 0.3-radius torso
53
- # (patch_v98's 0.285 sank them INTO the body) and slims arms/hands;
54
- # 3) makes "standing still" truly static with a real position-delta guard
55
- # (the server never re-sends 'idle', so remote avatars kept running);
56
- # 4) removes the leftover blank plaque with the semicircular roof + 3 bulbs
57
- # (<VaiEntranceStele />, mounted at [0,-0.7,-22]) that patch_v91 put in
58
- # front of the benches.
59
- #
60
- # V112 (patch_v112.mjs) runs after the main chain and FIXES the
61
- # three defects V109 introduced (verified against the original source):
62
- # 1) BACK TEXT WAS MIRRORED. V109 used a flat plane at z=-0.315 with
63
- # side={THREE.DoubleSide}. The third-person camera sits at local -z
64
- # (CameraRig: back = (sin yaw, cos yaw), yaw = PI), so it looked at the
65
- # BACK face of that plane and every digit + "V.AI STUDIO" came out
66
- # reversed. V112 replaces it with a curved SHELL (cylinderGeometry, one
67
- # arc) that has a single outward face -- it cannot mirror.
68
- # 2) THE FACE WAS INVISIBLE. The original face plane sits at z=-0.215 (behind
69
- # the head, camera side) with a +z normal and FrontSide, so the camera was
70
- # looking at its culled back face; and the hair cap (thetaLength 0.72 PI)
71
- # covered the whole face anyway. V112 uses a curved cap on +z with a new
72
- # texture (brows, whites, pupils, glints, nose, mouth) and cuts the hair to
73
- # 0.30 PI so it sits on the crown.
74
- # 3) NO NAME TAG. V112 adds a curved name plate on the back of the jersey.
75
- # It also shortens the avatar (AVATAR_SCALE 0.94, head 0.24) for better
76
- # proportions, restyles the kit (polo collar, piping, belt + buckle, cream
77
- # socks, navy trousers) and replaces the fire pit + trophy in the centre of the
78
- # cave with <ChristmasGrove />: a large decorated tree with blinking lights, a
79
- # star, baubles, stockings and gifts, plus a snowman and Santa Claus. Warm
80
- # lighting is preserved (the old fire pit was intensity 100).
81
- # Like V109 it self-verifies and RESTORES the previous sources on any integrity
82
- # failure, so a bad anchor can never take the Space down.
83
- #
84
- # V113 (patch_v113.mjs) runs LAST, immediately before esbuild. It fixes the
85
- # three defects the user still saw on the v112 deploy (all reproduced in a real
86
- # headless-Chromium render of this exact patch chain, then re-rendered to verify):
87
- # 1) DETACHED ARMS. V109 moved the shoulders out to 0.335 and V112 slimmed the
88
- # arm tube to r=0.058, but nothing ever bridged the shoulder gap. At the arm
89
- # pivot height the torso radius is 0.2704 while the arm's inner edge sits at
90
- # 0.2770 -- a 0.0066 slit that widens to 0.2424 at the top of the tube, so
91
- # the arms visibly floated. V113 rebuilds each arm as one group pivoting at
92
- # the shoulder joint (±0.315, 1.30) with a r=0.10 deltoid sphere centred
93
- # exactly on the pivot: because the sphere's centre never moves when the
94
- # group rotates, the socket stays sealed at every swing angle. Numeric check:
95
- # distance from pivot to torso surface = 0.0408 < 0.10 deltoid radius, and the
96
- # upper-arm tube overlaps the torso by 0.021..0.047 across -60..+60 degrees.
97
- # 2) MIRRORED NUMBER + LOGO. The deploy still carried V109's flat plane at
98
- # z=-0.315 with side={THREE.DoubleSide}. V112's curved-shell replacement was
99
- # never applied: its idempotency guard tested for the literal string
100
- # 'V112: BANG TEN', which is also present in the comment block V112 itself
101
- # inserts, so the guard matched its own comment and skipped the insert.
102
- # V113 removes that plane outright and re-adds the single-faced curved shell.
103
- # Orientation verified numerically, not by eye: with an asymmetric test
104
- # texture, canvas-left maps to screen-left for both plates, and all 130
105
- # sector vertices face the camera (nothing is culled).
106
- # 3) NO NAME ON THE FRONT. V112 only ever placed the name on the BACK (and that
107
- # insert was skipped too). V113 adds a curved name plate on the CHEST.
108
- # Its guards test for real JSX geometry signatures, never for comment text, so it
109
- # cannot repeat V112's self-matching bug. Verified idempotent (second run leaves
110
- # app.js byte-identical) and it RESTORES both sources on any integrity failure.
111
-
112
- # V114 (patch_v114.mjs) runs after V113, immediately before esbuild. Five user
113
- # requests, each verified by number or by a real headless-Chromium render:
114
- # 1) LOWER BODY PROPORTIONS. The torso is capsule(0.30, 0.34) => 0.60 wide but
115
- # the hips were capsule(0.24, 0.22) => only 0.48 wide, and the thighs at
116
- # x=+-0.11 with r=0.088 spanned just 0.396. The character read "top heavy,
117
- # bottom pinched". Hips are now a CYLINDER r=0.30 => exactly 0.60 wide, the
118
- # same as the shirt, and SHORTER (height 0.35, was 0.70). Measured on a real
119
- # render: hip/torso width ratio 0.725 -> 0.872, hips 187px -> 225px on screen.
120
- # A capsule scaled down in Y was tried first and rejected: from the side it
121
- # renders as a flattened ellipsoid disc (caught in a render, then replaced by
122
- # a cylinder, which gives the exact width from every angle).
123
- # 2) V.AI STUDIO LOGO ON THE SHIRT, ABOVE THE NUMBER, BIGGER. backPlateTex is
124
- # rewritten on a 320x260 canvas: circular crest with the golden "V" and
125
- # "STUDIO" on top (the same lockup as the carved plaque at the cave mouth),
126
- # the shirt number large underneath. The curved back shell was resized to
127
- # r=0.316, height 0.34, arc 2*0.662 rad so its geometry aspect (1.231) equals
128
- # the canvas aspect (1.231) exactly -- no stretching. Verified numerically:
129
- # v=1 sits at +H/2 (not flipped), u=0 maps to screen-left (not mirrored), and
130
- # all 40 shell vertices face the camera.
131
- # 3) YOUTUBE SCREEN PINNED TO THE CAVE WALL. The overlay used to recompute a
132
- # BILLBOARD every frame: it took the projected centroid of the board and drew
133
- # a max(width) x max(height) box there, so rotating the camera slid the video
134
- # across the screen. It now uses a HOMOGRAPHY that maps the overlay onto the
135
- # board's four projected corners, so the video is glued to the board in 3D
136
- # and only scales/skews with perspective. The element size must equal the
137
- # corner-derived |c1-c0| x |c3-c0| (a fixed 1280x720 left 3 corners off by up
138
- # to 784px -- measured). quadMatrix() already existed in the file but was
139
- # DEAD CODE and also mathematically wrong; it is replaced by a correct
140
- # square->quad projective transform, verified to map 4/4 corners with 0.000px
141
- # error and to bow the interior correctly (projective centre (688.6,255.9)
142
- # vs the naive average (834.2,337.1)). An allFront guard hides the overlay
143
- # when the board goes behind the camera so no flipped ghost is drawn.
144
- # 4) ALL Hang MU / MANCHESTER UNITED TEXT IN THE CAVE -> V.AI STUDIO. The two
145
- # vault banners ("GLORY GLORY", "MAN UNITED") are redrawn as the V.AI STUDIO
146
- # lockup; the LED fallback poster that shows whenever YouTube is blocked (the
147
- # normal case in VN) plus its scrolling ticker, the channel badges, the
148
- # thumbnail caption and the away-kit chest crest ("* UNITED *") all move to
149
- # V.AI STUDIO / HANG TU TRI AI. Hard-coded hero biographies were left alone:
150
- # those are historical statements about real players, not branding.
151
- # 5) MU QUIZ -> BASIC AI KNOWLEDGE. QUIZ_QUESTIONS goes from 5 football
152
- # questions to 14 AI ones (Grok -> xAI, NVIDIA -> Jensen Huang, LLM, CUDA,
153
- # AlphaGo, supervised learning, temperature, ...), and the right/wrong
154
- # messages no longer talk about Sir Alex or the Red Devils.
155
- # Guards test real JSX/Python signatures, never comment text. Verified idempotent
156
- # (a second run leaves app.js, cave3d.js and backend.py byte-identical) and it
157
- # RESTORES every source and exits 0 on any integrity failure, so a bad anchor can
158
- # never take the Space down.
159
-
160
- # V115 (patch_v115.mjs) runs after V114, immediately before esbuild. The user
161
- # still reported the SAME three defects after v114:
162
- # (1) arms detached from the body, (2) number + logo still mirrored on the
163
- # shirt, (3) name plate still not visible on the front of the shirt.
164
- # Because it was the THIRD identical report, V115 changes the approach instead of
165
- # re-doing the same reasoning:
166
- # * NO MORE CYLINDER-ARC UV MATH. V112/V113/V114 all printed text on a
167
- # cylinderGeometry arc and each argued "u=0 lands on screen-left" from
168
- # x = r*sin(t), z = r*cos(t). That is a 4-5 step derivation and one wrong
169
- # sign flips every digit -- exactly what happened three times. V115 uses a
170
- # PLANE + ROTATION, whose orientation cannot be got wrong: a plane's normal
171
- # is +z and its canvas reads correctly from +z; rotating PI about Y points
172
- # the normal at -z, so a camera at local -z still sees the FRONT face.
173
- # DoubleSide (the V109 bug) only makes a plane VISIBLE from behind; it never
174
- # makes it READ correctly.
175
- # * ORIENTATION RE-DERIVED FROM CameraRig, NOT GUESSED. back = (sin yaw,
176
- # cos yaw) with the default yaw = PI gives (0,0,-1), so the camera sits at
177
- # local -z. The original source agrees: the face plane is at z=-0.215 and
178
- # the number plane at z=-0.31, both on the -z side. So the side of the shirt
179
- # the player actually SEES is -z. V113 had put the name plate at z=+0.312,
180
- # i.e. on the far side of the body, which is why it was never visible.
181
- # V115 puts BOTH plates at -z, each rotated PI about Y.
182
- # * ARMS are one group pivoting at the shoulder (+-0.30, 1.30) with a deltoid
183
- # sphere centred exactly on the pivot, so the socket cannot open at any swing
184
- # angle: distance from pivot to the torso surface is
185
- # sqrt(0.30^2 + 0.13^2) - 0.30 = 0.0407 < 0.105 deltoid radius. The upper
186
- # arm (r 0.068) has its inner edge at 0.232, inside the 0.299 torso radius at
187
- # y=1.16, so the tube is embedded in the body with no slit.
188
- # * STATE-INDEPENDENT CUTS. V113 died silently when V112 changed the geometry
189
- # underneath it, which is why v114's own fixes then never applied either.
190
- # V115 anchors on NOTHING that V112/V113/V114 created: it removes the
191
- # original `{p.number != null && (...)}` block (brace-balanced, verified to
192
- # contain useNumTex( before cutting), removes only LEAF <mesh> elements that
193
- # still reference the old plate textures, removes the two arm groups, and
194
- # inserts its new block before <group ref={headRef}>, an anchor that has
195
- # existed since the original source and is still used by useFrame.
196
- # It never cuts a <group>: <group ref={rootRef}> contains the whole avatar.
197
- # Self-verifying like V109..V114: it re-asserts the avatar is intact
198
- # (rootRef == 1, torso material still present), validates all three JSX files
199
- # with esbuild.transform, and RESTORES every source + exits 0 on any failure, so
200
- # a bad anchor can never take the Space down.
201
  RUN npm install --no-audit --no-fund 2>&1 | tail -2 && \
202
  node patch_boards.mjs && \
203
  node patch_v32.mjs && \
204
  node patch_v33.mjs && \
205
  node patch_v34.mjs && \
206
  node patch_v35.mjs && \
207
- node patch_v36.mjs && \
208
- node patch_v37.mjs && \
209
- node patch_v38.mjs && \
210
- node patch_v39.mjs && \
211
- node patch_v40.mjs && \
212
- node patch_v41.mjs && \
213
- node patch_v42.mjs && \
214
- node patch_v43.mjs && \
215
- node patch_v44.mjs && \
216
- node patch_v45.mjs && \
217
- node patch_v46.mjs && \
218
- node patch_v47.mjs && \
219
- node patch_v48.mjs && \
220
- node patch_v50.mjs && \
221
- node patch_v51.mjs && \
222
- node patch_v60.mjs && \
223
- node patch_v61.mjs && \
224
- node patch_v62.mjs && \
225
- node patch_v63.mjs && \
226
- node patch_v64.mjs && \
227
- node patch_v67.mjs && \
228
- node patch_v68.mjs && \
229
- node patch_v68a.mjs && \
230
- node patch_v69.mjs && \
231
- node patch_v70.mjs && \
232
- node patch_v71.mjs && \
233
- node patch_v72.mjs && \
234
- node patch_v73.mjs && \
235
- node patch_v74.mjs && \
236
- node patch_v75.mjs && \
237
- node patch_v76.mjs && \
238
- node patch_v77.mjs && \
239
- node patch_v78.mjs && \
240
- node patch_v82.mjs && \
241
- node patch_v83.mjs && \
242
- node patch_v84.mjs && \
243
- node patch_v85.mjs && \
244
- node patch_v86.mjs && \
245
- node patch_v87.mjs && \
246
- node patch_v88.mjs && \
247
- node patch_v89.mjs && \
248
- node patch_v90.mjs && \
249
- node patch_v91.mjs && \
250
- node patch_v92.mjs && \
251
- node patch_v93.mjs && \
252
- node patch_v94.mjs && \
253
- node patch_v95.mjs && \
254
- node patch_v96.mjs && \
255
- node patch_v97.mjs && \
256
- node patch_v98.mjs && \
257
- node patch_v101.mjs && \
258
- node patch_v102.mjs && \
259
- node patch_v103.mjs && \
260
- node patch_v109.mjs && \
261
- node patch_v112.mjs && \
262
- node patch_v113.mjs && \
263
- node patch_v114.mjs && \
264
- node patch_v115.mjs && \
265
  node esbuild.config.mjs && \
266
  ls -la frontend/app.bundle.js
267
 
268
- # ============ Stage 2: Python runtime ============
269
  FROM python:3.11-slim
 
270
  WORKDIR /app
271
- COPY --from=build /build/frontend/index.html ./frontend/index.html
 
 
 
272
  COPY --from=build /build/backend.py .
273
- RUN python -m py_compile backend.py
274
- RUN pip install --no-cache-dir fastapi uvicorn[standard] huggingface_hub
275
- COPY --from=build /build/video_proxy.py .
276
  COPY --from=build /build/frontend/app.bundle.js ./frontend/app.bundle.js
277
  COPY --from=build /build/frontend/env.js ./frontend/env.js
 
278
  COPY frontend/images ./frontend/images
 
279
  COPY frontend/styles ./frontend/styles
280
  COPY frontend/fonts ./frontend/fonts
 
281
  COPY frontend/pwa ./frontend/pwa
282
- RUN pip install --no-cache-dir beautifulsoup4 lxml requests \
283
- && echo "[V95] bs4/lxml/requests ok"
284
 
285
- CMD ["python", "backend.py"]
 
 
 
1
  FROM node:20-slim AS build
2
  WORKDIR /build
3
 
4
+ # Frontend build deps
 
 
 
 
 
 
 
 
 
 
 
5
  COPY build/package.json build/package-lock.json* ./
6
+ COPY frontend/app.js frontend/cave3d.js frontend/cavehelpers.js frontend/home3d.js frontend/store.js frontend/pwa.js frontend/scoreboard.js frontend/voice.js frontend/minigames.js frontend/env.js ./frontend/
7
  COPY build/esbuild.config.mjs ./
8
  COPY backend.py .
9
+ COPY patch_boards.mjs .
10
+ COPY patch_v32.mjs .
11
+ COPY patch_v33.mjs .
12
+ COPY patch_v34.mjs .
13
+ COPY patch_v35.mjs .
14
+
15
+ # v26: patch_boards.mjs đưa 2 bảng TRẬN GẦN NHẤT / TRẬN SẮP TỚI về z=71 (2 bên lối vào)
16
+ # + bump VERSION_ID v25 -> v26 để khớp cache-bust ?v=26.
17
+ # v32: patch_v32.mjs — YouTube fallback canvas (màn hình không trống khi YT bị chặn)
18
+ # + các bảng trong hang TO hơn & tách xa nhau; VERSION_ID v31 -> v32.
19
+ # v33: patch_v33.mjs — bỏ bảng đỏ chắn cửa hang, cờ MU vào khung gần cửa, bảng tỷ số
20
+ # gần lối vào; dàn các bảng trong hang quanh tường không chồng; VERSION_ID v32 -> v33.
21
+ # v34: patch_v34.mjs — màn hình lớn phát video QUA PROXY bep40-vnews (xem được ở VN;
22
+ # youtube-nocookie bị chặn); nhân vật quay mặt vào trong hang khi mới vào;
23
+ # VERSION_ID v33 -> v34.
24
+ # v35: patch_v35.mjs — PROXY THẬT: vnews /s render trang embed YouTube + gửi tín
25
+ # hiệu 'hangmu-playing' (màn hình không trống — nếu không phát thì fallback
26
+ # canvas LED hiện); backend Player.rotation mặc định = π (nhân vật mới vào
27
+ # quay mặt vào hang cho MỌI người chơi thấy); relay âm lượng TV -> iframe;
28
+ # VERSION_ID v34 -> v35.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  RUN npm install --no-audit --no-fund 2>&1 | tail -2 && \
30
  node patch_boards.mjs && \
31
  node patch_v32.mjs && \
32
  node patch_v33.mjs && \
33
  node patch_v34.mjs && \
34
  node patch_v35.mjs && \
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  node esbuild.config.mjs && \
36
  ls -la frontend/app.bundle.js
37
 
38
+ # ---- runtime ----
39
  FROM python:3.11-slim
40
+
41
  WORKDIR /app
42
+
43
+ RUN pip install --no-cache-dir fastapi uvicorn[standard]
44
+
45
+ # backend.py patched (VERSION_ID=v35) trong build stage
46
  COPY --from=build /build/backend.py .
47
+ COPY frontend/index.html ./frontend/index.html
 
 
48
  COPY --from=build /build/frontend/app.bundle.js ./frontend/app.bundle.js
49
  COPY --from=build /build/frontend/env.js ./frontend/env.js
50
+ # legend portraits (10 MU huyền thoại) phục vụ từ /images/legends/
51
  COPY frontend/images ./frontend/images
52
+ # Design system + fonts
53
  COPY frontend/styles ./frontend/styles
54
  COPY frontend/fonts ./frontend/fonts
55
+ # PWA: manifest, service worker, icons
56
  COPY frontend/pwa ./frontend/pwa
 
 
57
 
58
+ EXPOSE 7860
59
+
60
+ CMD ["python", "backend.py"]
backend.py CHANGED
@@ -13,7 +13,6 @@ Tái hiện đầy đủ tính năng hangmu.online:
13
  """
14
  import asyncio
15
  import json
16
- import math
17
  import os
18
  import random
19
  import re
@@ -26,9 +25,7 @@ from typing import Dict, List, Optional
26
 
27
  from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException
28
  from fastapi.staticfiles import StaticFiles
29
- from fastapi.responses import FileResponse, JSONResponse, HTMLResponse
30
- import video_proxy # V43: /api/video-proxy — màn hình lớn tự render YouTube embed (không phụ thuộc VNEWS), HTMLResponse
31
- import video_proxy # V43: /api/video-proxy — màn hình lớn tự render YouTube embed (không phụ thuộc VNEWS)
32
  from pydantic import BaseModel
33
  import uvicorn
34
 
@@ -37,7 +34,7 @@ app = FastAPI(title="Hang MU Backend")
37
  # VERSION ổn định — khớp cache-bust ?v=10 của bundle. Không đổi ngẫu nhiên
38
  # theo uuid (trước đây uuid4().hex[:8] đổi mỗi lần restart → client tưởng
39
  # "Có bản mới" và tự reload liên tục). Chỉ đổi khi ta chủ động deploy bản mới.
40
- VERSION_ID = "v117"
41
 
42
  # ============ Client error log (từ ErrorBoundary / window.onerror) ============
43
  _client_logs = []
@@ -56,14 +53,6 @@ async def api_logs():
56
  return {"logs": _client_logs[-200:]}
57
 
58
  # ============ Attendance (chuyên cần bia đá) ============
59
- def _att_pick_thumb(item):
60
- for tag in ("media:thumbnail", "media:content", "enclosure"):
61
- m = re.search(rf"<{tag}[^>]*url=[\"']([^\"']+)[\"']", item)
62
- if m:
63
- return m.group(1)
64
- return ""
65
-
66
-
67
  @app.get("/api/attendance")
68
  async def api_attendance():
69
  plist = list(rooms.get("lobby", {}).values())
@@ -128,599 +117,6 @@ _ON_THIS_DAY = [
128
  (12, 31, 1941, "Sir Alex Ferguson chào đời", "HLV vĩ đại nhất lịch sử bóng đá Anh, sinh ở Govan, Glasgow."),
129
  ]
130
 
131
-
132
- # ============ BẢNG TIN AI (Nguồn: bep40/VNEWS) — cache 8 giờ ============
133
- # V67: "Bảng tin AI hôm nay" — 10 tin mới nhất theo từ khoá AI / trí tuệ nhân tạo.
134
- # Lấy từ Space bep40/VNEWS (endpoint công khai /api/hashtag/sources); server giữ
135
- # cache 8 giờ để không gọi VNEWS liên tục (VNEWS cũng tự cache).
136
- AI_NEWS_URL = "https://bep40-vnews.hf.space/api/hashtag/sources"
137
- AI_NEWS_TOPIC = "AI trí tuệ nhân tạo"
138
- AI_NEWS_TTL = 8 * 3600 # 8 giờ
139
- _ai_news_cache = {"at": 0.0, "items": []}
140
-
141
- def _ai_news_fetch():
142
- """Gọi Google News RSS lấy 10 tin AI mới nhất. Trả list {title, url, via, pubDate, thumbnail}."""
143
- import xml.etree.ElementTree as ET
144
- from urllib.parse import quote as _q
145
- url = ("https://news.google.com/rss/search?q=" + _q(AI_NEWS_TOPIC)
146
- + "&hl=vi&gl=VN&ceid=VN:vi")
147
- req = urllib.request.Request(url, headers={
148
- "User-Agent": "Mozilla/5.0 (HangMU/1.0)",
149
- "Accept": "application/rss+xml, application/xml, text/xml, */*",
150
- "Accept-Encoding": "identity",
151
- })
152
- with urllib.request.urlopen(req, timeout=15) as resp:
153
- xml_data = resp.read()
154
- # Dac biet: Google News co the tra ve gzip - thu giai nen neu can
155
- if xml_data[:2] == b'\x1f\x8b':
156
- import gzip
157
- xml_data = gzip.decompress(xml_data)
158
- # Parse XML
159
- try:
160
- root = ET.fromstring(xml_data)
161
- except ET.ParseError:
162
- text = xml_data.decode("utf-8", "ignore")
163
- root = ET.fromstring(text)
164
- out = []
165
- for item in root.iter("item"):
166
- title_el = item.find("title")
167
- link_el = item.find("link")
168
- source_el = item.find("source")
169
- pubdate_el = item.find("pubDate")
170
- desc_el = item.find("description")
171
- # Try to extract thumbnail from media:content or media:thumbnail
172
- thumb = ""
173
- for media in item.iter():
174
- tag = media.tag.split("}")[-1] if "}" in media.tag else media.tag
175
- if tag in ("thumbnail", "content") and media.get("url"):
176
- thumb = media.get("url")
177
- break
178
- title = (title_el.text or "").strip() if title_el is not None else ""
179
- link = (link_el.text or "").strip() if link_el is not None else ""
180
- via = (source_el.text or "").strip() if source_el is not None else ""
181
- pubdate = (pubdate_el.text or "").strip() if pubdate_el is not None else ""
182
- desc = (desc_el.text or "").strip() if desc_el is not None else ""
183
- # Strip HTML tags from description
184
- if desc:
185
- import re as _re
186
- desc = _re.sub(r'<[^>]+>', '', desc).strip()[:300]
187
- if not title:
188
- continue
189
- out.append({"title": title[:200], "url": link, "via": via,
190
- "pubDate": pubdate, "thumbnail": thumb, "description": desc})
191
- if len(out) >= 10:
192
- break
193
- return out
194
-
195
- # ============ V92: ẢNH THẬT CHO TIN AI ============
196
- # Google News RSS không kèm ảnh. BBC Vietnamese RSS có media:thumbnail thật
197
- # → dùng làm nguồn ảnh. Nếu thiếu ảnh, sinh ảnh đại diện tại /api/ai-thumb.
198
- _AI_IMG_URL = "https://feeds.bbci.co.uk/vietnamese/rss.xml"
199
- _ai_img_cache = {"at": 0.0, "items": []}
200
-
201
- def _ai_img_fetch():
202
- """Lấy danh sách URL ảnh từ BBC Vietnamese RSS (media:thumbnail)."""
203
- import re as _re
204
- try:
205
- r = urllib.request.Request(_AI_IMG_URL, headers={
206
- "User-Agent": "Mozilla/5.0 (HangMU/1.0)",
207
- "Accept": "application/rss+xml, application/xml, text/xml",
208
- })
209
- with urllib.request.urlopen(r, timeout=12) as resp:
210
- xml = resp.read().decode("utf-8", "ignore")
211
- except Exception:
212
- return []
213
- urls = _re.findall(r'<media:thumbnail[^>]*url=["\']([^"\']+)["\']', xml)
214
- if not urls:
215
- urls = _re.findall(r'<media:content[^>]*url=["\']([^"\']+)["\']', xml)
216
- return [u for u in urls if u.startswith("http")]
217
-
218
- def _ai_thumb_for(idx: int) -> str:
219
- """Ảnh cho tin thứ idx: ảnh BBC cùng chỉ mục, hoặc ảnh đại diện."""
220
- imgs = _ai_img_cache.get("items") or []
221
- if idx < len(imgs):
222
- return imgs[idx]
223
- return "/api/ai-thumb?i=%d" % (idx % 12)
224
-
225
- @app.get("/api/ai-thumb")
226
- async def api_ai_thumb(i: int = 0):
227
- """Sinh ảnh đại diện (SVG) cho tin thứ i — luôn có ảnh, deterministic."""
228
- import html as _html
229
- palette = [
230
- ("#0d1b2a", "#4fa3ff"), ("#1a0d24", "#b06bff"), ("#0a2418", "#3ddc97"),
231
- ("#2a1206", "#ff9a4f"), ("#24060f", "#ff4f6d"), ("#06181f", "#4fd8e8"),
232
- ]
233
- bg, fg = palette[i % len(palette)]
234
- label = "AI"
235
- svg = (
236
- f'<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360" '
237
- f'viewBox="0 0 640 360">'
238
- f'<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1">'
239
- f'<stop offset="0%" stop-color="{bg}"/><stop offset="100%" stop-color="{fg}" '
240
- f'stop-opacity="0.45"/></linearGradient></defs>'
241
- f'<rect width="640" height="360" fill="url(#g)"/>'
242
- f'<circle cx="320" cy="180" r="96" fill="none" stroke="{fg}" '
243
- f'stroke-width="4" stroke-opacity="0.65"/>'
244
- f'<circle cx="320" cy="180" r="66" fill="none" stroke="{fg}" '
245
- f'stroke-width="2" stroke-opacity="0.4"/>'
246
- f'<text x="320" y="196" font-family="Georgia,serif" font-size="62" '
247
- f'font-weight="bold" fill="{fg}" text-anchor="middle" opacity="0.92">'
248
- f'{_html.escape(label)}</text>'
249
- f'</svg>'
250
- )
251
- from fastapi.responses import Response as _Resp
252
- return _Resp(content=svg, media_type="image/svg+xml",
253
- headers={"Cache-Control": "public, max-age=86400"})
254
-
255
-
256
- # ============ Tin AI (V95: bep40/VAINEWS, đầy đủ tiêu đề + mô tả + ảnh) ============
257
- import os as _os95
258
- import re as _re95
259
- import json as _json95
260
- import time as _time95
261
- import threading as _threading95
262
- import requests as _rq95
263
- from bs4 import BeautifulSoup as _BS95
264
-
265
- _v95_ai_news = {"items": [], "at": 0.0}
266
- _v95_lock = _threading95.Lock()
267
- _v95_TTL = 30 * 60 # 30 phút
268
- _v95_KEY = "AI trí tuệ nhân tạo"
269
- _v95_VAINEWS = "https://bep40-vainews.hf.space"
270
- _v95_UA = {
271
- "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
272
- "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120 Safari/537.36"),
273
- "Accept-Language": "vi,en;q=0.8",
274
- }
275
- # từ khoá nhận diện tin AI
276
- _v95_AIWORDS = ("ai", "trí tuệ nhân tạo", "tri tue nhan tao", "machine learning",
277
- "học máy", "chatbot", "chatgpt", "openai", "gemini", "llm",
278
- "mô hình", "thuật toán", "robot", "tự động hoá", "deepfake",
279
- "generative", "anthropic", "claude", "midjourney", "stable diffusion",
280
- "copilot", "nvidia", "gpu", "dữ liệu lớn", "tự hành")
281
-
282
-
283
- def _v95_is_ai(text: str) -> bool:
284
- t = (text or "").lower()
285
- for w in _v95_AIWORDS:
286
- if w in ("ai",):
287
- # 'ai' phải đứng riêng, tránh khớp bừa trong 'hai','mai','phải'
288
- if _re95.search(r"(?<![a-zàáảãạăâèéêìíòóôơùúưýđ])ai(?![a-zàáảãạăâèéêìíòóôơùúưýđ])", t):
289
- return True
290
- elif w in t:
291
- return True
292
- return False
293
-
294
-
295
- def _v95_deep(url: str) -> dict:
296
- """Lấy mô tả + ảnh + vài đoạn nội dung từ trang gốc."""
297
- out = {"description": "", "image": "", "body": "", "site": ""}
298
- try:
299
- r = _rq95.get(url, headers=_v95_UA, timeout=15, allow_redirects=True)
300
- if r.status_code != 200:
301
- return out
302
- r.encoding = r.apparent_encoding or "utf-8"
303
- soup = _BS95(r.text, "lxml")
304
-
305
- def meta(*props):
306
- for p in props:
307
- el = soup.find("meta", property=p) or soup.find("meta", attrs={"name": p})
308
- if el and el.get("content"):
309
- return el.get("content").strip()
310
- return ""
311
-
312
- out["description"] = meta("og:description", "description", "twitter:description")
313
- out["image"] = meta("og:image", "twitter:image")
314
- out["site"] = meta("og:site_name")
315
-
316
- # các đoạn nội dung đầu
317
- paras = []
318
- for sel in (".knc-content p", ".content p", "article p",
319
- ".article-body p", ".detail-content p", "#mainContent p",
320
- ".body-text p", "div.content-detail p"):
321
- for p in soup.select(sel):
322
- txt = p.get_text(" ", strip=True)
323
- if len(txt) > 70 and txt not in paras:
324
- paras.append(txt)
325
- if len(paras) >= 4:
326
- break
327
- if not paras:
328
- for p in soup.find_all("p"):
329
- txt = p.get_text(" ", strip=True)
330
- if len(txt) > 90:
331
- paras.append(txt)
332
- if len(paras) >= 4:
333
- break
334
- out["body"] = "\n\n".join(paras[:4])
335
- if not out["description"] and paras:
336
- out["description"] = paras[0][:300]
337
- except Exception as e:
338
- print("[v95] deep fail", url[:60], e)
339
- return out
340
-
341
-
342
- def _v95_from_vainews(limit: int = 10):
343
- """Tin AI từ Space bep40/VAINEWS (private -> cần token)."""
344
- hdr = dict(_v95_UA)
345
- tok = _os95.environ.get("HF_TOKEN") or ""
346
- if tok:
347
- hdr["Authorization"] = "Bearer " + tok
348
- raw = []
349
- for attempt in (1, 2, 3):
350
- try:
351
- r = _rq95.get(_v95_VAINEWS + "/api/category/cong-nghe",
352
- headers=hdr, timeout=60)
353
- if r.status_code == 200:
354
- raw = r.json() or []
355
- print("[v95] VAINEWS:", len(raw), "tin")
356
- break
357
- print("[v95] VAINEWS HTTP", r.status_code, "lan", attempt)
358
- except Exception as e:
359
- print("[v95] VAINEWS fail lan", attempt, ":", str(e)[:90])
360
- if attempt < 3:
361
- _time95.sleep(4)
362
- if not isinstance(raw, list):
363
- raw = []
364
-
365
- # ưu tiên tin có từ khoá AI
366
- ai = [a for a in raw if _v95_is_ai((a.get("title") or "") + " " + (a.get("link") or ""))]
367
- pool = ai if len(ai) >= 4 else raw
368
-
369
- items, seen = [], set()
370
- for a in pool:
371
- if len(items) >= limit:
372
- break
373
- title = (a.get("title") or "").strip()
374
- link = (a.get("link") or "").strip()
375
- if not title or not link or link in seen:
376
- continue
377
- seen.add(link)
378
- items.append({
379
- "title": title,
380
- "url": link,
381
- "thumbnail": (a.get("img") or "").strip(),
382
- "via": (a.get("source") or "VAINEWS").strip(),
383
- "description": "",
384
- "body": "",
385
- "pubDate": "",
386
- "site": "",
387
- })
388
- return items
389
-
390
-
391
- def _v95_refresh(limit: int = 10):
392
- items = _v95_from_vainews(limit)
393
- if not items:
394
- return []
395
- # lấy mô tả + ảnh + nội dung song song
396
- try:
397
- from concurrent.futures import ThreadPoolExecutor
398
- with ThreadPoolExecutor(max_workers=6) as ex:
399
- deeps = list(ex.map(lambda it: _v95_deep(it["url"]), items))
400
- for it, d in zip(items, deeps):
401
- if d.get("description"):
402
- it["description"] = d["description"]
403
- if not it["thumbnail"] and d.get("image"):
404
- it["thumbnail"] = d["image"]
405
- if d.get("body"):
406
- it["body"] = d["body"]
407
- if d.get("site"):
408
- it["site"] = d["site"]
409
- except Exception as e:
410
- print("[v95] deep pool fail:", e)
411
-
412
- # điền mô tả dự phòng nếu vẫn trống
413
- for it in items:
414
- if not it["description"]:
415
- it["description"] = it["title"]
416
- return items
417
-
418
-
419
- def _v95_get():
420
- now = _time95.time()
421
- with _v95_lock:
422
- if _v95_ai_news["items"] and now - _v95_ai_news["at"] < _v95_TTL:
423
- return _v95_ai_news["items"]
424
- items = _v95_refresh(10)
425
- with _v95_lock:
426
- if items:
427
- _v95_ai_news["items"] = items
428
- _v95_ai_news["at"] = now
429
- return _v95_ai_news["items"]
430
-
431
-
432
- def _v95_warm():
433
- try:
434
- _v95_get()
435
- print("[v95] warm tin AI:", len(_v95_ai_news["items"]), "tin")
436
- except Exception as e:
437
- print("[v95] warm fail", e)
438
-
439
-
440
- try:
441
- _threading95.Thread(target=_v95_warm, daemon=True).start()
442
- except Exception:
443
- pass
444
-
445
-
446
- # ============ Tin AI (V95 end) ============
447
-
448
-
449
-
450
- @app.get("/api/img-proxy")
451
- async def api_img_proxy(url: str = ""):
452
- """Proxy ảnh tin tức -> cùng origin nên canvas đọc được pixel (không CORS)."""
453
- from fastapi.responses import Response as _Resp
454
- if not url.startswith("http"):
455
- return _Resp(status_code=400)
456
- try:
457
- hdr = {"User-Agent": _v95_UA["User-Agent"],
458
- "Accept": "image/avif,image/webp,image/*,*/*;q=0.8",
459
- "Referer": _re95.sub(r"^(https?://[^/]+)", r"\1/", url)}
460
- r = _rq95.get(url, headers=hdr, timeout=15, stream=True)
461
- if r.status_code != 200:
462
- return _Resp(status_code=404)
463
- ct = r.headers.get("content-type", "image/jpeg")
464
- if not ct.startswith("image/"):
465
- ct = "image/jpeg"
466
- return _Resp(content=r.content, media_type=ct,
467
- headers={"Cache-Control": "public, max-age=86400",
468
- "Access-Control-Allow-Origin": "*"})
469
- except Exception as e:
470
- print("[v96] img-proxy fail", e)
471
- return _Resp(status_code=502)
472
-
473
- @app.get("/api/ai-news/item")
474
- async def api_ai_news_item(url: str = ""):
475
- """Chi tiết 1 tin cho modal: mô tả + nội dung + ảnh lớn."""
476
- if not url:
477
- return {"ok": False, "error": "missing url"}
478
- d = _v95_deep(url)
479
- return {"ok": True, "url": url, "description": d.get("description", ""),
480
- "body": d.get("body", ""), "image": d.get("image", ""),
481
- "site": d.get("site", "")}
482
-
483
- @app.get("/api/ai-news")
484
- async def api_ai_news():
485
- # V95: tin đầy đủ (tiêu đề + mô tả + ảnh thật) từ bep40/VAINEWS
486
- try:
487
- items = _v95_get()
488
- except Exception as e:
489
- print("[v95] handler fail", e)
490
- items = []
491
- return {"items": items, "keyword": _v95_KEY,
492
- "updated": int(_time95.time()), "source": "bep40/VAINEWS"}
493
-
494
-
495
- # ============ BẢNG VÀNG ĐIỂM DANH ============
496
- # V67: user siêng vào hang nhất — tên · số lần ghé hang · số lần trò chuyện.
497
- # Đếm trong RAM (không cần DB), giữ qua restart bằng /data nếu ghi được.
498
- _att_stats: Dict[str, dict] = {} # name -> {"visits": int, "chats": int}
499
- _att_lock = __import__("threading").Lock()
500
-
501
- # ---- V85: BỀN VỮNG — ghi xuống file để không mất khi restart ----
502
- # Space cpu-basic có filesystem ephemeral; ta vẫn thử /data (persistent volume
503
- # nếu được gắn) rồi fallback /app, ./ — có file còn hơn mất sạch.
504
- def _att_path() -> str:
505
- for d in ("/data", "/app", "."):
506
- try:
507
- if os.path.isdir(d) and os.access(d, os.W_OK):
508
- return os.path.join(d, "attendance.json")
509
- except Exception:
510
- continue
511
- return "attendance.json"
512
-
513
- _ATT_FILE = _att_path()
514
- _att_dirty = False
515
-
516
- def _att_save():
517
- """Ghi atomic: tmp -> os.replace, tránh hỏng file giữa chừng."""
518
- global _att_dirty
519
- try:
520
- tmp = _ATT_FILE + ".tmp"
521
- with open(tmp, "w", encoding="utf-8") as f:
522
- json.dump(_att_stats, f, ensure_ascii=False)
523
- os.replace(tmp, _ATT_FILE)
524
- _att_dirty = False
525
- try:
526
- _att_bg_push() # V86: mirror lên Hub (thread nền)
527
- except NameError:
528
- pass # hàm định nghĩa sau — bỏ qua, lần gọi sau sẽ đẩy
529
- return True
530
- except Exception as e:
531
- print("[v85] _att_save loi:", e)
532
- return False
533
-
534
- def _att_load():
535
- """Nạp lại số liệu đã lưu (nếu có)."""
536
- try:
537
- if os.path.isfile(_ATT_FILE):
538
- with open(_ATT_FILE, "r", encoding="utf-8") as f:
539
- d = json.load(f)
540
- if isinstance(d, dict):
541
- for k, v in d.items():
542
- if isinstance(v, dict):
543
- _att_stats[str(k)[:60]] = {
544
- "visits": int(v.get("visits", 0)),
545
- "chats": int(v.get("chats", 0)),
546
- "joins": int(v.get("joins", 0)),
547
-
548
- "votes": int(v.get("votes", 0)),}
549
- print("[v85] _att_load: nạp", len(_att_stats), "user từ", _ATT_FILE)
550
- except Exception as e:
551
- print("[v85] _att_load loi:", e)
552
-
553
- _att_load()
554
-
555
- # ---- V86: MIRROR HUB — số liệu sống sót qua restart/rebuild ----
556
- # Space cpu-basic không có volume; ta mirror lên dataset private trên Hub.
557
- # Ghi kiểu best-effort: lỗi mạng KHÔNG được làm hỏng request.
558
- ATT_DATASET = os.environ.get("ATT_DATASET", "bep40/hangmu-attendance")
559
- ATT_FILE_IN_REPO = "attendance.json"
560
- _att_push_fail = 0
561
-
562
- def _att_push(snapshot=None):
563
- """Đẩy _att_stats (hoặc snapshot) lên Hub dataset (best-effort)."""
564
- try:
565
- from huggingface_hub import HfApi
566
- api = HfApi(token=os.environ.get("HF_TOKEN"))
567
- data = snapshot if snapshot is not None else _att_stats
568
- api.upload_file(
569
- path_or_fileobj=json.dumps(data, ensure_ascii=False).encode("utf-8"),
570
- path_in_repo=ATT_FILE_IN_REPO,
571
- repo_id=ATT_DATASET,
572
- repo_type="dataset",
573
- commit_message="attendance autosave",
574
- )
575
- return True
576
- except Exception as e:
577
- global _att_push_fail
578
- _att_push_fail += 1
579
- if _att_push_fail <= 3:
580
- print("[v86] _att_push loi:", e)
581
- return False
582
-
583
- def _att_pull():
584
- """Đọc _att_stats từ Hub dataset lúc khởi động."""
585
- try:
586
- from huggingface_hub import hf_hub_download
587
- p = hf_hub_download(
588
- repo_id=ATT_DATASET, repo_type="dataset",
589
- filename=ATT_FILE_IN_REPO, token=os.environ.get("HF_TOKEN"),
590
- )
591
- with open(p, "r", encoding="utf-8") as f:
592
- d = json.load(f)
593
- if isinstance(d, dict):
594
- for k, v in d.items():
595
- if isinstance(v, dict):
596
- _att_stats[str(k)[:60]] = {
597
- "visits": int(v.get("visits", 0)),
598
- "chats": int(v.get("chats", 0)),
599
-
600
- "votes": int(v.get("votes", 0)),}
601
- print("[v86] _att_pull: nạp", len(_att_stats), "user từ Hub")
602
- # ghi bản địa phương luôn để cờ persisted=true + có fallback offline
603
- try:
604
- tmp = _ATT_FILE + ".tmp"
605
- with open(tmp, "w", encoding="utf-8") as f:
606
- json.dump(_att_stats, f, ensure_ascii=False)
607
- os.replace(tmp, _ATT_FILE)
608
- except Exception as _e:
609
- print("[v86] _att_pull: không ghi được file local:", _e)
610
- except Exception as e:
611
- print("[v86] _att_pull: chưa có dữ liệu Hub (" + type(e).__name__ + ")")
612
-
613
- # nạp từ Hub lúc khởi động (file local là bản nháp)
614
- _att_pull()
615
-
616
- # V86d: cố đẩy lần cuối khi Space tắt (nếu còn dirty)
617
- try:
618
- import atexit
619
- atexit.register(lambda: _att_push() if _att_stats else None)
620
- except Exception:
621
- pass
622
-
623
- _att_push_lock = None # tạo trễ để tránh import-time phức tạp
624
- _att_push_busy = {"v": False}
625
-
626
- def _att_bg_push():
627
- """Đẩy lên Hub ở thread nền, TUẦN TỰ — tránh 2 lần ghi đè nhau
628
- (lần cũ đến sau sẽ ghi đè số liệu mới)."""
629
- global _att_push_lock
630
- import threading
631
- if _att_push_lock is None:
632
- _att_push_lock = threading.Lock()
633
- if _att_push_busy["v"]:
634
- _att_push_busy["again"] = True # đang đẩy dở → nhắc đẩy lại bản mới nhất
635
- return
636
- _att_push_busy["v"] = True
637
- def _run():
638
- try:
639
- with _att_push_lock:
640
- # CHỤP SNAPSHOT muộn nhất ngay trước khi đẩy — tránh đẩy
641
- # phải bản cũ (các bump sau đã vào _att_stats).
642
- import copy
643
- snap = copy.deepcopy(_att_stats)
644
- _att_push(snap)
645
- finally:
646
- _att_push_busy["v"] = False
647
- if _att_push_busy.get("again"):
648
- _att_push_busy["again"] = False
649
- _att_bg_push() # còn bump mới trong lúc đẩy → đẩy tiếp
650
- threading.Thread(target=_run, daemon=True).start()
651
-
652
- # V89: "visits" = số NGÀY khác nhau ghé hang (công bằng với mạng chập chờn).
653
- # "joins" = số lần vào thật. _att_seen_today reset theo ngày.
654
- _att_seen_today: Dict[str, str] = {} # name -> "YYYY-MM-DD" đã viếng hôm nay
655
-
656
- def _att_day() -> str:
657
- try:
658
- return time.strftime("%Y-%m-%d", time.gmtime(time.time() + 7 * 3600)) # UTC+7
659
- except Exception:
660
- return "1970-01-01"
661
-
662
- def _att_join(name: str):
663
- """Gọi khi user join. Tính visits theo NGÀY, joins theo LẦN."""
664
- nm = (name or "").strip()[:60]
665
- if not nm:
666
- return
667
- today = _att_day()
668
- if _att_seen_today.get(nm) != today:
669
- _att_seen_today[nm] = today
670
- _att_bump(nm, "visits") # lần đầu trong ngày mới +1 visits
671
- _att_bump(nm, "joins") # mỗi lần vào hang đều +1
672
-
673
- def _att_bump(name: str, key: str):
674
- nm = (name or "").strip()[:60]
675
- if not nm:
676
- return
677
- global _att_dirty
678
- with _att_lock:
679
- e = _att_stats.setdefault(nm, {"visits": 0, "chats": 0, "joins": 0, "votes": 0})
680
- e[key] = int(e.get(key, 0)) + 1
681
- _att_dirty = True
682
- # ghi ngay (lượng ghi nhỏ, an toàn khi process bị kill)
683
- _att_save()
684
-
685
- def _att_bump_visit(name: str):
686
- _att_bump(name, "visits")
687
-
688
- def _att_bump_chat(name: str):
689
- _att_bump(name, "chats")
690
-
691
- def _att_score(r: dict) -> int:
692
- """V90: điểm siêng = visits*20 + chats*2 + joins*1.
693
- visits (số NGÀY) áp đảo → user vào đều mỗi ngày luôn xếp trên
694
- user chỉ vào 1 ngày nhưng nhắn nhiều tin."""
695
- return int(r.get("visits", 0)) * 20 + int(r.get("chats", 0)) * 2 + int(r.get("joins", 0)) + int(r.get("votes", 0)) * 3 # V116: + binh chon
696
-
697
-
698
- @app.get("/api/attendance/top")
699
- async def api_attendance_top():
700
- """Top 10 user siêng vào hang nhất: tên, số lần ghé hang, số lần trò chuyện."""
701
- with _att_lock:
702
- rows = sorted(
703
- [{"name": k, "visits": int(v.get("visits", 0)),
704
- "chats": int(v.get("chats", 0)),
705
- "joins": int(v.get("joins", 0)),
706
- "votes": int(v.get("votes", 0))}
707
- for k, v in _att_stats.items()],
708
- # V90: điểm = visits*20 + chats*2 + joins*1 (số NGÀY áp đảo)
709
- key=lambda r: (-_att_score(r), -r["visits"], -r["chats"], r["name"].lower()),
710
- )[:10]
711
- for _r in rows:
712
- _r["score"] = _att_score(_r)
713
- return {"top": rows, "total": len(_att_stats), "updated": int(time.time()), "persisted": os.path.isfile(_ATT_FILE)}
714
-
715
-
716
- @app.post("/api/attendance/reset")
717
- async def api_attendance_reset():
718
- """Xoá sạch bảng điểm danh (cả RAM, file và Hub)."""
719
- with _att_lock:
720
- _att_stats.clear()
721
- _att_save()
722
- return {"ok": True, "top": [], "total": 0}
723
-
724
  @app.get("/api/legends")
725
  async def api_legends():
726
  return {"legends": _LEGENDS}
@@ -764,7 +160,7 @@ class Player:
764
  number: Optional[int] = None
765
  sid: str = "" # mã ngẫu nhiên (hm_sid)
766
  position: Dict[str, float] = field(default_factory=lambda: {"x": 0.0, "y": 0.0, "z": 36.0})
767
- rotation: float = math.pi # V35: mới vào hang quay mặt VÀO TRONG (nhìn màn hình lớn/trung tâm)
768
  animation: str = "idle"
769
  connected: bool = True
770
  lastSeen: float = field(default_factory=time.time)
@@ -812,10 +208,18 @@ GAME_TTL = 90.0
812
  polls: Dict[str, dict] = {}
813
  POLL_INTERVAL_S = 180 # cứ 3 phút phát 1 poll nếu chưa có
814
  POLL_QUESTIONS = [
815
- {"question": "Mô hình ngôn ngữ lớn (LLM) viết tắt của cụm nào?", "options": [{"icon": "🧠", "text": "Large Language Model"}, {"icon": "📐", "text": "Logical Layer Model"}, {"icon": "⚡", "text": "Long Latency Memory"}, {"icon": "🔁", "text": "Linear Learning Machine"}]},
816
- {"question": "ChatGPT do công ty nào phát triển?", "options": [{"icon": "🤖", "text": "OpenAI"}, {"icon": "🔎", "text": "Google"}, {"icon": "🐦", "text": "xAI"}, {"icon": "🦙", "text": "Meta"}]},
817
- {"question": "CUDA — nền tảng tính toán song song cho AI — do ai tạo ra?", "options": [{"icon": "🟩", "text": "NVIDIA"}, {"icon": "🔴", "text": "AMD"}, {"icon": "🔵", "text": "Intel"}, {"icon": "🍎", "text": "Apple"}]},
818
- {"question": "Tham số \"temperature\" của một LLM điều chỉnh gì?", "options": [{"icon": "🎲", "text": "Mức ngẫu nhiên của câu trả lời"}, {"icon": "📏", "text": "Số token tối đa"}, {"icon": "🚀", "text": "Tốc độ sinh chữ"}, {"icon": "💾", "text": "Kích thước mô hình"}]},
 
 
 
 
 
 
 
 
819
  ]
820
 
821
  def _make_poll():
@@ -828,137 +232,10 @@ def _make_poll():
828
  # bongdaplus.vn (nguồn highlight bóng đá mở, không cần API key) để lấy
829
  # YouTube ID các clip Highlight MU / Premier League mới, đưa lên đầu playlist.
830
  # Nếu quét thất bại → GIỮ NGUYÊN playlist cũ (không làm trống màn hình).
831
- def _yt_meta(vid, title=""):
832
- """Chuẩn hoá YouTube ID / watch URL / embed URL / youtu.be -> object
833
- {url, title, img}. Frontend phát qua proxy bep40-vnews.hf.space (xem được
834
- tại VN; youtube-nocookie bị chặn nên trước đây màn hình lớn chỉ hiện
835
- fallback, không có video)."""
836
- s = str(vid or "").strip()
837
- m = re.search(r'(?:youtube(?:-nocookie)?\.com/(?:watch\?[^#]*v=|embed/|shorts/)|youtu\.be/)([a-zA-Z0-9_-]{11})', s)
838
- if m:
839
- vid = m.group(1)
840
- else:
841
- vid = (s or "")[:11]
842
- return {"url": "https://www.youtube.com/watch?v=" + vid,
843
- "title": title or "Highlight MU",
844
- "img": "https://i.ytimg.com/vi/" + vid + "/hqdefault.jpg"}
845
-
846
-
847
  BOARD = {
848
- "videos": [
849
- _yt_meta("1LH4319g6Gw", "THẾ GIỚI NGOẠI HẠNG (9/11): MAN UNITED THOÁT HIỂM, MỘT HLV SẮP MẤT VIỆC"),
850
- _yt_meta("JuRD8gSdmps"),
851
- ],
852
- "music": [_yt_meta("VKmVJKDoPwk", "Glory Glory Man United — bài hát chính thức của MU")],
853
  }
854
- try:
855
- from fastapi import Request as _Request
856
- except Exception:
857
- _Request = None
858
-
859
- # V51: playlist màn hình lớn = YouTube RSS channel FPT Bóng Đá (rss2json), realtime 10 phút.
860
- _VNEWS_AI = "https://bep40-vnews.hf.space/api/fptplay/videos" # fallback 2 (không dùng trực tiếp)
861
- _FPT_RSS_CHANNEL = "UC4LvrpNXujjbGOS4RDvr41g" # FPT Bóng Đá (YouTube)
862
- _FPT_RSS_URL = None
863
- _VNEWS_CACHE = {"at": 0.0, "posts": None}
864
- _VNEWS_TTL = 600 # 10 phút
865
- import urllib.request as _urq
866
-
867
-
868
- def _http_get_json(url: str, timeout: int = 12):
869
- """GET JSON bằng stdlib urllib."""
870
- try:
871
- with _urq.urlopen(url, timeout=timeout) as r:
872
- if r.status != 200:
873
- return None
874
- if "json" not in (r.headers.get("Content-Type") or ""):
875
- return None
876
- return json.loads(r.read().decode("utf-8", "replace"))
877
- except Exception as e:
878
- print(f"[board] vnews fetch error: {e}", flush=True)
879
- return None
880
-
881
-
882
- def _urllib_quote(s: str) -> str:
883
- """URL-encode bằng stdlib (an toàn khi runtime thiếu urllib.parse)."""
884
- try:
885
- import urllib.parse as _up
886
- return _up.quote(s, safe="")
887
- except Exception:
888
- return "".join(c if (c.isalnum() or c in "-_.~") else "%%%02X" % ord(c) for c in s)
889
-
890
-
891
- def _fpt_rss_fetch():
892
- """Fetch YouTube RSS channel FPT Bóng Đá qua rss2json — 15 video mới nhất."""
893
- try:
894
- global _FPT_RSS_URL
895
- if _FPT_RSS_URL is None:
896
- _FPT_RSS_URL = "https://api.rss2json.com/v1/api.json?rss_url=" + _urllib_quote(
897
- "https://www.youtube.com/feeds/videos.xml?channel_id=" + _FPT_RSS_CHANNEL)
898
- with _urq.urlopen(_FPT_RSS_URL, timeout=20) as r:
899
- if r.status != 200:
900
- print(f"[board] fpt rss HTTP {r.status}", flush=True)
901
- return None
902
- d = json.loads(r.read().decode("utf-8", "replace"))
903
- items = d.get("items") or []
904
- out = []
905
- for it in items[:15]:
906
- vid = (it.get("guid") or "").replace("yt:video:", "").strip()
907
- if not vid or len(vid) != 11:
908
- continue
909
- title = (it.get("title") or "FPT Bóng Đá").strip()
910
- thumb = (it.get("thumbnail") or ("https://i.ytimg.com/vi/" + vid + "/hqdefault.jpg"))
911
- out.append({
912
- "url": "https://www.youtube.com/watch?v=" + vid,
913
- "title": title[:200],
914
- "img": thumb,
915
- "yt": vid,
916
- "published": (it.get("pubDate") or "")[:16],
917
- })
918
- if out:
919
- print(f"[board] fpt rss OK: {len(out)} videos, first={out[0][chr(116)+chr(105)+chr(116)+chr(108)+chr(101)]}", flush=True)
920
- return out or None
921
- except Exception as e:
922
- print(f"[board] fpt rss error: {e}", flush=True)
923
- return None
924
-
925
-
926
- def _board_vnews(refresh: bool = False):
927
- """Playlist màn hình: ưu tiên RSS FPT Bóng Đá -> fallback /api/fptplay/videos -> cache cũ."""
928
- now = time.time()
929
- if not refresh and _VNEWS_CACHE["posts"] is not None and now - _VNEWS_CACHE["at"] < _VNEWS_TTL:
930
- return _VNEWS_CACHE["posts"]
931
-
932
- out = _fpt_rss_fetch()
933
- if not out:
934
- data = _http_get_json(_VNEWS_AI, timeout=12)
935
- if data:
936
- try:
937
- posts = data.get("videos", []) or []
938
- out = []
939
- for p in posts[:28]:
940
- vid = (p.get("id") or "").strip()
941
- if not vid:
942
- continue
943
- link = (p.get("link") or "").strip()
944
- video_url = link if (link and link.startswith("http")) else ("https://www.youtube.com/watch?v=" + vid)
945
- out.append({
946
- "url": video_url,
947
- "title": (p.get("title") or "FPT Bóng Đá").strip(),
948
- "img": (p.get("img") or ("https://i.ytimg.com/vi/" + vid + "/hqdefault.jpg")).strip(),
949
- "yt": vid,
950
- })
951
- if not out:
952
- out = None
953
- except Exception as e:
954
- print(f"[board] fptplay fallback error: {e}", flush=True)
955
- out = None
956
- if out:
957
- _VNEWS_CACHE["posts"] = out
958
- _VNEWS_CACHE["at"] = now
959
- return out
960
- return _VNEWS_CACHE["posts"]
961
-
962
  _BOARD_LOCK = asyncio.Lock()
963
  _BOARD_SCRAPE = {"at": 0.0, "last_refresh": 0, "error": ""}
964
 
@@ -967,38 +244,6 @@ _BOARD_SCRAPE = {"at": 0.0, "last_refresh": 0, "error": ""}
967
  _BOARD_FILE = os.environ.get("BOARD_FILE", os.path.join(os.sep, "data", "board.json"))
968
 
969
 
970
- def _yt_meta(vid, title=""):
971
- """Chuẩn hoá YouTube ID / watch URL / embed URL / shorts / youtu.be ->
972
- object {url, title, img} — frontend phát qua proxy bep40-vnews.hf.space
973
- (xem được tại VN; youtube-nocookie bị chặn nên màn hình lớn không thể
974
- iframe thẳng)."""
975
- s = str(vid or "").strip()
976
- m = re.search(r'(?:youtube(?:-nocookie)?\.com/(?:watch\?[^#]*v=|embed/|shorts/|live/)|youtu\.be/|m\.youtube\.com/(?:watch\?[^#]*v=|embed/|shorts/))([a-zA-Z0-9_-]{11})', s)
977
- if m:
978
- vid = m.group(1)
979
- else:
980
- vid = (s or "")[:11]
981
- return {"url": "https://www.youtube.com/watch?v=" + vid,
982
- "title": title or "Highlight MU",
983
- "img": "https://i.ytimg.com/vi/" + vid + "/hqdefault.jpg"}
984
-
985
-
986
- def _yt_meta(vid, title=""):
987
- """Chuẩn hoá YouTube ID / watch URL / embed URL / shorts / youtu.be ->
988
- object {url, title, img} — frontend phát qua proxy bep40-vnews.hf.space
989
- (xem được tại VN; youtube-nocookie bị chặn nên màn hình lớn không thể
990
- iframe thẳng)."""
991
- s = str(vid or "").strip()
992
- m = re.search(r'(?:youtube(?:-nocookie)?\.com/(?:watch\?[^#]*v=|embed/|shorts/|live/)|youtu\.be/|m\.youtube\.com/(?:watch\?[^#]*v=|embed/|shorts/))([a-zA-Z0-9_-]{11})', s)
993
- if m:
994
- vid = m.group(1)
995
- else:
996
- vid = (s or "")[:11]
997
- return {"url": "https://www.youtube.com/watch?v=" + vid,
998
- "title": title or "Highlight MU",
999
- "img": "https://i.ytimg.com/vi/" + vid + "/hqdefault.jpg"}
1000
-
1001
-
1002
  def _board_persist():
1003
  """Ghi playlist hiện tại xuống đĩa (fail-safe — không bao giờ ném lỗi)."""
1004
  try:
@@ -1018,13 +263,7 @@ def _board_load():
1018
  with open(_BOARD_FILE, "r", encoding="utf-8") as f:
1019
  d = json.load(f)
1020
  if isinstance(d.get("videos"), list) and d["videos"]:
1021
- def _norm(v):
1022
- if isinstance(v, str):
1023
- return _yt_meta(v)
1024
- if isinstance(v, dict) and v.get("url"):
1025
- return _yt_meta(v["url"], v.get("title") or "")
1026
- return None
1027
- BOARD["videos"] = [x for x in (_norm(v) for v in d["videos"]) if x][:12]
1028
  _BOARD_SCRAPE["at"] = float(d.get("scraped", 0))
1029
  _BOARD_SCRAPE["last_refresh"] = int(d.get("last_refresh", 0))
1030
  print(f"[board] loaded {len(BOARD['videos'])} videos from {_BOARD_FILE}")
@@ -1137,9 +376,8 @@ def _board_refresh_playlist() -> List[str]:
1137
  break
1138
  if not ids:
1139
  raise RuntimeError("no youtube ids found")
1140
- # playlist cũ giữ ở cuối làm dự phòng độ dài (hỗ trợ cả string lẫn object)
1141
- base = [v if isinstance(v, str) else (v.get("url") or "") for v in BOARD["videos"]]
1142
- base = [v for v in base if v and v not in seen][:4]
1143
  return (ids + base)[:12]
1144
  except Exception as e:
1145
  _BOARD_SCRAPE["error"] = str(e)[:200]
@@ -1162,13 +400,9 @@ async def _board_loop():
1162
  _BOARD_SCRAPE["at"] = now
1163
  if fresh and fresh != BOARD["videos"]:
1164
  old = BOARD["videos"]
1165
- BOARD["videos"] = [_yt_meta(v) for v in fresh]
1166
  _BOARD_SCRAPE["last_refresh"] = int(now)
1167
- print(f"[board] initial refresh: {len(old)} -> {len(fresh)} videos, first={_yt_meta(fresh[0])['url']}")
1168
- vn = await asyncio.get_event_loop().run_in_executor(None, _board_vnews)
1169
- if vn:
1170
- keep = [v for v in BOARD.get("videos", []) if not (v.get("mp4") or "").startswith("https://bep40-vnews.hf.space")][:12]
1171
- BOARD["videos"] = vn + keep
1172
  _board_persist()
1173
  except Exception as e:
1174
  print(f"[board] initial refresh error: {e}")
@@ -1182,18 +416,11 @@ async def _board_loop():
1182
  _BOARD_SCRAPE["at"] = now
1183
  if fresh and fresh != BOARD["videos"]:
1184
  old = BOARD["videos"]
1185
- BOARD["videos"] = [_yt_meta(v) for v in fresh]
1186
  _BOARD_SCRAPE["last_refresh"] = int(now)
1187
- print(f"[board] playlist refreshed: {len(old)} -> {len(fresh)} videos, first={_yt_meta(fresh[0])['url']}")
1188
- vn = await asyncio.get_event_loop().run_in_executor(None, _board_vnews)
1189
- if vn:
1190
- keep = [v for v in BOARD.get("videos", []) if not (v.get("mp4") or "").startswith("https://bep40-vnews.hf.space")][:12]
1191
- BOARD["videos"] = vn + keep
1192
- _board_persist()
1193
- try:
1194
  await broadcast("lobby", {"type": "board", "videos": BOARD["videos"], "music": BOARD["music"]})
1195
- except Exception:
1196
- pass
1197
  except Exception as e:
1198
  print(f"[board] loop error: {e}")
1199
  await asyncio.sleep(5 * 60)
@@ -1225,40 +452,27 @@ class PushUnsubscribeRequest(BaseModel):
1225
 
1226
  # ============ Quiz ============
1227
  QUIZ_QUESTIONS = [
1228
- {"id": "q1", "q": "Model Grok thuộc về công ty nào?",
1229
- "answers": [{"id": "a1", "text": "xAI"}, {"id": "a2", "text": "OpenAI"}, {"id": "a3", "text": "Google DeepMind"}, {"id": "a4", "text": "Anthropic"}], "correct": "a1"},
1230
- {"id": "q2", "q": "Ai là cha đẻ của NVIDIA?",
1231
- "answers": [{"id": "a1", "text": "Jensen Huang"}, {"id": "a2", "text": "Sam Altman"}, {"id": "a3", "text": "Elon Musk"}, {"id": "a4", "text": "Sundar Pichai"}], "correct": "a1"},
1232
- {"id": "q3", "q": "ChatGPT do công ty nào phát triển?",
1233
- "answers": [{"id": "a1", "text": "OpenAI"}, {"id": "a2", "text": "Meta"}, {"id": "a3", "text": "Microsoft"}, {"id": "a4", "text": "xAI"}], "correct": "a1"},
1234
- {"id": "q4", "q": "AlphaGo — hệ thống đánh bại kỳ thủ cờ vây Hàn Quốc Lee Sedol — do ai phát triển?",
1235
- "answers": [{"id": "a1", "text": "Google DeepMind"}, {"id": "a2", "text": "IBM"}, {"id": "a3", "text": "OpenAI"}, {"id": "a4", "text": "NVIDIA"}], "correct": "a1"},
1236
- {"id": "q5", "q": "Google Gemini do công ty nào phát triển?",
1237
- "answers": [{"id": "a1", "text": "Google"}, {"id": "a2", "text": "OpenAI"}, {"id": "a3", "text": "Meta"}, {"id": "a4", "text": "Amazon"}], "correct": "a1"},
1238
- {"id": "q6", "q": "Llama là dòng mô hình ngôn ngữ mở của công ty nào?",
1239
- "answers": [{"id": "a1", "text": "Meta"}, {"id": "a2", "text": "Google"}, {"id": "a3", "text": "Anthropic"}, {"id": "a4", "text": "Mistral"}], "correct": "a1"},
1240
- {"id": "q7", "q": "Anthropic là công ty đứng sau dòng model AI nào?",
1241
- "answers": [{"id": "a1", "text": "Claude"}, {"id": "a2", "text": "Gemini"}, {"id": "a3", "text": "Grok"}, {"id": "a4", "text": "Copilot"}], "correct": "a1"},
1242
- {"id": "q8", "q": "GPU là viết tắt của cụm từ nào?",
1243
- "answers": [{"id": "a1", "text": "Graphics Processing Unit"}, {"id": "a2", "text": "General Program Unit"}, {"id": "a3", "text": "Grid Power Unit"}, {"id": "a4", "text": "Global Processor Utility"}], "correct": "a1"},
1244
- {"id": "q9", "q": "Deep Learning là một nhánh của lĩnh vực nào?",
1245
- "answers": [{"id": "a1", "text": "Machine Learning"}, {"id": "a2", "text": "Khoa học vật liệu"}, {"id": "a3", "text": "Cơ sở dữ liệu"}, {"id": "a4", "text": "Mạng máy tính"}], "correct": "a1"},
1246
- {"id": "q10", "q": "Mô hình ngôn ngữ lớn (LLM) thường được viết tắt từ cụm nào?",
1247
- "answers": [{"id": "a1", "text": "Large Language Model"}, {"id": "a2", "text": "Linear Learning Machine"}, {"id": "a3", "text": "Logical Layer Model"}, {"id": "a4", "text": "Long Latency Memory"}], "correct": "a1"},
1248
- {"id": "q11", "q": "Phát biểu nào mô tả đúng nhất về \"học có giám sát\" (supervised learning)?",
1249
- "answers": [{"id": "a1", "text": "Học từ dữ liệu đã có nhãn đúng"}, {"id": "a2", "text": "Học không cần dữ liệu"}, {"id": "a3", "text": "Học chỉ từ phần thưởng"}, {"id": "a4", "text": "Học bằng cách nén dữ liệu"}], "correct": "a1"},
1250
- {"id": "q12", "q": "Tham số \"temperature\" của một LLM chủ yếu điều chỉnh điều gì?",
1251
- "answers": [{"id": "a1", "text": "Mức độ ngẫu nhiên / sáng tạo của câu trả lời"}, {"id": "a2", "text": "Số token tối đa"}, {"id": "a3", "text": "Tốc độ mạng"}, {"id": "a4", "text": "Kích thước mô hình"}], "correct": "a1"},
1252
- {"id": "q13", "q": "Ai được mệnh danh là \"cha đẻ của trí tuệ nhân tạo\" với bài kiểm tra Turing?",
1253
- "answers": [{"id": "a1", "text": "Alan Turing"}, {"id": "a2", "text": "Geoffrey Hinton"}, {"id": "a3", "text": "Yann LeCun"}, {"id": "a4", "text": "John McCarthy"}], "correct": "a1"},
1254
- {"id": "q14", "q": "CUDA — nền tảng tính toán song song phổ biến cho AI — do công ty nào tạo ra?",
1255
- "answers": [{"id": "a1", "text": "NVIDIA"}, {"id": "a2", "text": "AMD"}, {"id": "a3", "text": "Intel"}, {"id": "a4", "text": "Qualcomm"}], "correct": "a1"},
1256
  ]
1257
- _right_messages = ["Chuẩn! Kiến thức AI của bạn vững thật.", "Chính xác! Mời vào hang cùng anh em.",
1258
- "Đúng rồi! Trí tuệ nhân tạo đang chờ bạn trong hang."]
1259
- _wrong_messages = ["Chưa đúng — không sao, vào hang anh em trao đổi thêm.",
1260
  "Sai một chút thôi, hang vẫn mở cửa chào bạn.",
1261
- "Hụt rồi! Đáp án đúng đang được tô xanh đó."]
1262
 
1263
  def _rand_pick(arr):
1264
  return arr[random.randrange(len(arr))]
@@ -1329,7 +543,6 @@ async def join_room(req: JoinRequest):
1329
  if number is not None and not (1 <= number <= 99):
1330
  raise HTTPException(422, "Jersey number must be 1-99")
1331
  player = Player(id=player_id, name=req.player_name, number=number, sid=uuid.uuid4().hex[:12])
1332
- _att_join(req.player_name) # V89: visits theo ngày
1333
  rooms[req.room_id][player_id] = player
1334
  player_rooms[player_id] = req.room_id
1335
  return {"player_id": player_id, "room": {"id": req.room_id, "name": "Hang chung"},
@@ -1346,76 +559,9 @@ async def leave_queue(req: JoinRequest):
1346
  async def board():
1347
  return {"videos": BOARD["videos"], "music": BOARD["music"]}
1348
 
1349
- @app.get("/api/diag")
1350
- async def api_diag(ok: str = "0", y: str = "0", px: str = "0", pz: str = "0", d: str = "", n: str = "0"):
1351
- print(f"[diag] boardPx.ok={ok} yaw={y} cam=({px},{pz}) disp={d} n={n}")
1352
- return {"ok": True}
1353
-
1354
-
1355
  @app.get("/api/board")
1356
  async def api_board():
1357
- vids = list(BOARD.get("videos", []))
1358
- # V46: cố lấy short AI Tường AI mới nhất (cache) — chèn đầu playlist
1359
- vn = await asyncio.get_event_loop().run_in_executor(None, _board_vnews)
1360
- if vn:
1361
- keep = [v for v in vids if not (v.get("mp4") or "").startswith("https://bep40-vnews.hf.space")][:12]
1362
- vids = vn + keep
1363
- return {"videos": vids, "music": BOARD["music"]}
1364
-
1365
- @app.get("/api/board/video")
1366
- async def api_board_video(url: str = "", request: _Request = None):
1367
- """V46: proxy stream mp4 short AI từ VNEWS — trình duyệt user chỉ tải từ
1368
- domain hangmu (tránh CORS + lệ thuộc + chặn mạng). Range supported."""
1369
- if not url.startswith("https://bep40-vnews.hf.space/api/ai/short-file/"):
1370
- return JSONResponse({"error": "bad url"}, status_code=400)
1371
- try:
1372
- hdrs = {"User-Agent": "hangmu-board/1.0"}
1373
- if request is not None:
1374
- rg = request.headers.get("range")
1375
- if rg:
1376
- hdrs["Range"] = rg
1377
- req = _urq.Request(url, headers=hdrs)
1378
- resp = _urq.urlopen(req, timeout=30)
1379
- code = resp.status
1380
- if code not in (200, 206):
1381
- try: resp.close()
1382
- except Exception: pass
1383
- return JSONResponse({"error": "origin " + str(code)}, status_code=502)
1384
- ctype = resp.headers.get("Content-Type", "video/mp4")
1385
- out_h = {"Cache-Control": "public, max-age=3600", "Accept-Ranges": "bytes"}
1386
- if resp.headers.get("Content-Range"):
1387
- out_h["Content-Range"] = resp.headers["Content-Range"]
1388
- if resp.headers.get("Content-Length"):
1389
- out_h["Content-Length"] = resp.headers["Content-Length"]
1390
-
1391
- def _stream():
1392
- try:
1393
- while True:
1394
- chunk = resp.read(65536)
1395
- if not chunk:
1396
- break
1397
- yield chunk
1398
- finally:
1399
- try: resp.close()
1400
- except Exception: pass
1401
-
1402
- from fastapi.responses import StreamingResponse
1403
- return StreamingResponse(_stream(), media_type=ctype, status_code=code, headers=out_h)
1404
- except Exception as e:
1405
- return JSONResponse({"error": str(e)[:160]}, status_code=502)
1406
-
1407
-
1408
- @app.get("/api/video-proxy")
1409
- async def api_video_proxy(url: str = "", title: str = "", img: str = "", loop: int = 1):
1410
- """V43: trang embed YouTube nội bộ (xem ở VN, gửi hangmu-playing trung
1411
- thực) — màn hình lớn không phụ thuộc VNEWS build."""
1412
- return video_proxy.render_video_proxy(url, title, img, loop)
1413
-
1414
- @app.get("/api/video-proxy")
1415
- async def api_video_proxy(url: str = "", title: str = "", img: str = "", loop: int = 1):
1416
- """V43: trang embed YouTube nội bộ (xem ở VN, gửi hangmu-playing trung
1417
- thực) — màn hình lớn không phụ thuộc VNEWS build."""
1418
- return video_proxy.render_video_proxy(url, title, img, loop)
1419
 
1420
  @app.get("/api/board/status")
1421
  async def api_board_status():
@@ -1429,7 +575,7 @@ async def api_board_refresh():
1429
  fresh = await asyncio.get_event_loop().run_in_executor(None, _board_refresh_playlist)
1430
  _BOARD_SCRAPE["at"] = time.time()
1431
  if fresh and fresh != BOARD["videos"]:
1432
- BOARD["videos"] = [_yt_meta(v) for v in fresh]
1433
  _BOARD_SCRAPE["last_refresh"] = int(time.time())
1434
  _board_persist()
1435
  return {"ok": True, "videos": BOARD["videos"], "refreshed": bool(fresh)}
@@ -1837,7 +983,6 @@ async def websocket_endpoint(ws: WebSocket, player_id: str):
1837
  if not text.strip():
1838
  continue
1839
  p.lastChatAt = now
1840
- _att_bump(p.name, "chats")
1841
  await broadcast(room_id, {"type": "chat", "player_id": player_id,
1842
  "player_name": p.name, "message": text,
1843
  "timestamp": now})
@@ -1898,7 +1043,6 @@ async def websocket_endpoint(ws: WebSocket, player_id: str):
1898
  if p and poll and not poll.get("voted", {}).get(player_id):
1899
  poll["voted"][player_id] = True
1900
  poll["counts"][int(msg.get("option", 0)) % len(poll["options"])] += 1
1901
- _att_bump(p.name, "votes") # V116: diem danh theo luot binh chon
1902
  await send(ws, {"type": "poll_result", "poll": poll})
1903
 
1904
  elif t == "inviteAsk":
@@ -2084,21 +1228,6 @@ async def websocket_endpoint(ws: WebSocket, player_id: str):
2084
  elif t == "ping":
2085
  await send(ws, {"type": "pong", "t": msg.get("t", 0)})
2086
 
2087
- elif t == "christmas_decor":
2088
- # Trang tri cay thong — broadcast cho tat ca trong phong
2089
- decor = {
2090
- "type": "christmas_decor",
2091
- "player_id": player_id,
2092
- "kind": str(msg.get("kind", ""))[:20],
2093
- "x": float(msg.get("x", 0)),
2094
- "y": float(msg.get("y", 0)),
2095
- "z": float(msg.get("z", 0)),
2096
- "color": str(msg.get("color", "#e8262b"))[:20],
2097
- }
2098
- await broadcast(room_id, decor)
2099
- # Gui lai cho nguoi gui de ho biet da nhan
2100
- await send(ws, {"type": "christmas_ack", "seq": msg.get("seq", 0)})
2101
-
2102
  except WebSocketDisconnect:
2103
  pass
2104
  finally:
@@ -2186,10 +1315,7 @@ app.mount("/static", StaticFiles(directory="frontend"), name="static")
2186
 
2187
  @app.get("/")
2188
  async def serve_index():
2189
- # V38: no-store — cấm trình duyệt cache index.html (trước đây heuristic
2190
- # cache giữ bản HTML cũ nhiều giờ -> server v37 mà user vẫn chạy bundle v34
2191
- # "màn hình vẫn y như cũ" dù đã fix).
2192
- return FileResponse("frontend/index.html", headers={"Cache-Control": "no-store"})
2193
 
2194
  @app.get("/env.js")
2195
  async def env_js():
@@ -2202,7 +1328,7 @@ _PWA_ROOT = ["manifest.json", "sw.js", "icon-192.png", "icon-512.png",
2202
  async def serve_static(path: str):
2203
  import os
2204
  # không nuốt websocket / API routes
2205
- if path.startswith("ws/") or path.startswith("ext/") or path.startswith("push/") or path.startswith("api/"):
2206
  raise HTTPException(404, "Not found")
2207
  if path in _PWA_ROOT:
2208
  pf = os.path.join("frontend", "pwa", path)
@@ -2211,8 +1337,7 @@ async def serve_static(path: str):
2211
  file_path = os.path.join("frontend", path)
2212
  if os.path.exists(file_path) and os.path.isfile(file_path):
2213
  return FileResponse(file_path)
2214
- # V38: fallback SPA cũng no-store (tránh cache HTML ở route ảo)
2215
- return FileResponse("frontend/index.html", headers={"Cache-Control": "no-store"})
2216
 
2217
  if __name__ == "__main__":
2218
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
13
  """
14
  import asyncio
15
  import json
 
16
  import os
17
  import random
18
  import re
 
25
 
26
  from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException
27
  from fastapi.staticfiles import StaticFiles
28
+ from fastapi.responses import FileResponse, JSONResponse
 
 
29
  from pydantic import BaseModel
30
  import uvicorn
31
 
 
34
  # VERSION ổn định — khớp cache-bust ?v=10 của bundle. Không đổi ngẫu nhiên
35
  # theo uuid (trước đây uuid4().hex[:8] đổi mỗi lần restart → client tưởng
36
  # "Có bản mới" và tự reload liên tục). Chỉ đổi khi ta chủ động deploy bản mới.
37
+ VERSION_ID = "v31"
38
 
39
  # ============ Client error log (từ ErrorBoundary / window.onerror) ============
40
  _client_logs = []
 
53
  return {"logs": _client_logs[-200:]}
54
 
55
  # ============ Attendance (chuyên cần bia đá) ============
 
 
 
 
 
 
 
 
56
  @app.get("/api/attendance")
57
  async def api_attendance():
58
  plist = list(rooms.get("lobby", {}).values())
 
117
  (12, 31, 1941, "Sir Alex Ferguson chào đời", "HLV vĩ đại nhất lịch sử bóng đá Anh, sinh ở Govan, Glasgow."),
118
  ]
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  @app.get("/api/legends")
121
  async def api_legends():
122
  return {"legends": _LEGENDS}
 
160
  number: Optional[int] = None
161
  sid: str = "" # mã ngẫu nhiên (hm_sid)
162
  position: Dict[str, float] = field(default_factory=lambda: {"x": 0.0, "y": 0.0, "z": 36.0})
163
+ rotation: float = 0.0
164
  animation: str = "idle"
165
  connected: bool = True
166
  lastSeen: float = field(default_factory=time.time)
 
208
  polls: Dict[str, dict] = {}
209
  POLL_INTERVAL_S = 180 # cứ 3 phút phát 1 poll nếu chưa có
210
  POLL_QUESTIONS = [
211
+ {"question": "Ai là huyền thoại vĩ đại nhất MU?", "options": [
212
+ {"icon": "👑", "text": "Sir Alex"}, {"icon": "🥅", "text": "Rooney"},
213
+ {"icon": "⚡", "text": "Ronaldo"}, {"icon": "🔥", "text": "Cantona"}]},
214
+ {"question": "Mùa này MU về đích thứ mấy?", "options": [
215
+ {"icon": "🥇", "text": "Top 4"}, {"icon": "🏆", "text": "Vô địch"},
216
+ {"icon": "😅", "text": "Top 6"}, {"icon": "💀", "text": "Ngoài top 6"}]},
217
+ {"question": "Đêm nay ai xem đá với nhau?", "options": [
218
+ {"icon": "📺", "text": "Có tôi"}, {"icon": "😴", "text": "Ngủ sớm"},
219
+ {"icon": "🍺", "text": "Nhậu xem luôn"}]},
220
+ {"question": "MU nên mua ai hè này?", "options": [
221
+ {"icon": "🦁", "text": "Tiền đạo"}, {"icon": "🧠", "text": "Tiền vệ"},
222
+ {"icon": "🛡️", "text": "Hậu vệ"}, {"icon": "🧤", "text": "Thủ môn"}]},
223
  ]
224
 
225
  def _make_poll():
 
232
  # bongdaplus.vn (nguồn highlight bóng đá mở, không cần API key) để lấy
233
  # YouTube ID các clip Highlight MU / Premier League mới, đưa lên đầu playlist.
234
  # Nếu quét thất bại → GIỮ NGUYÊN playlist cũ (không làm trống màn hình).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
  BOARD = {
236
+ "videos": ["JuRD8gSdmps"], # Highlight MU (kênh YouTube chính thức)
237
+ "music": ["VKmVJKDoPwk"], # "Glory Glory Man United" — bài hát chính thức của MU
 
 
 
238
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  _BOARD_LOCK = asyncio.Lock()
240
  _BOARD_SCRAPE = {"at": 0.0, "last_refresh": 0, "error": ""}
241
 
 
244
  _BOARD_FILE = os.environ.get("BOARD_FILE", os.path.join(os.sep, "data", "board.json"))
245
 
246
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  def _board_persist():
248
  """Ghi playlist hiện tại xuống đĩa (fail-safe — không bao giờ ném lỗi)."""
249
  try:
 
263
  with open(_BOARD_FILE, "r", encoding="utf-8") as f:
264
  d = json.load(f)
265
  if isinstance(d.get("videos"), list) and d["videos"]:
266
+ BOARD["videos"] = [v for v in d["videos"] if isinstance(v, str) and len(v) == 11][:12]
 
 
 
 
 
 
267
  _BOARD_SCRAPE["at"] = float(d.get("scraped", 0))
268
  _BOARD_SCRAPE["last_refresh"] = int(d.get("last_refresh", 0))
269
  print(f"[board] loaded {len(BOARD['videos'])} videos from {_BOARD_FILE}")
 
376
  break
377
  if not ids:
378
  raise RuntimeError("no youtube ids found")
379
+ # playlist cũ giữ ở cuối làm dự phòng độ dài
380
+ base = [v for v in BOARD["videos"] if v not in seen][:4]
 
381
  return (ids + base)[:12]
382
  except Exception as e:
383
  _BOARD_SCRAPE["error"] = str(e)[:200]
 
400
  _BOARD_SCRAPE["at"] = now
401
  if fresh and fresh != BOARD["videos"]:
402
  old = BOARD["videos"]
403
+ BOARD["videos"] = fresh
404
  _BOARD_SCRAPE["last_refresh"] = int(now)
405
+ print(f"[board] initial refresh: {len(old)} -> {len(fresh)} ids, first={fresh[0]}")
 
 
 
 
406
  _board_persist()
407
  except Exception as e:
408
  print(f"[board] initial refresh error: {e}")
 
416
  _BOARD_SCRAPE["at"] = now
417
  if fresh and fresh != BOARD["videos"]:
418
  old = BOARD["videos"]
419
+ BOARD["videos"] = fresh
420
  _BOARD_SCRAPE["last_refresh"] = int(now)
421
+ print(f"[board] playlist refreshed: {len(old)} -> {len(fresh)} ids, first={fresh[0]}")
 
 
 
 
 
 
422
  await broadcast("lobby", {"type": "board", "videos": BOARD["videos"], "music": BOARD["music"]})
423
+ _board_persist()
 
424
  except Exception as e:
425
  print(f"[board] loop error: {e}")
426
  await asyncio.sleep(5 * 60)
 
452
 
453
  # ============ Quiz ============
454
  QUIZ_QUESTIONS = [
455
+ {"id": "q1", "q": "Sân nhà của Manchester United tên là gì?",
456
+ "answers": [{"id": "a1", "text": "Anfield"}, {"id": "a2", "text": "Old Trafford"},
457
+ {"id": "a3", "text": "Etihad Stadium"}, {"id": "a4", "text": "Stamford Bridge"}], "correct": "a2"},
458
+ {"id": "q2", "q": "Huấn luyện viên thành công nhất lịch sử MU là ai?",
459
+ "answers": [{"id": "a1", "text": "José Mourinho"}, {"id": "a2", "text": "Ole Gunnar Solskjær"},
460
+ {"id": "a3", "text": "Sir Alex Ferguson"}, {"id": "a4", "text": "Erik ten Hag"}], "correct": "a3"},
461
+ {"id": "q3", "q": "MU lần đầu vô địch UEFA Champions League vào năm nào?",
462
+ "answers": [{"id": "a1", "text": "1968"}, {"id": "a2", "text": "1999"},
463
+ {"id": "a3", "text": "2008"}, {"id": "a4", "text": "2011"}], "correct": "a1"},
464
+ {"id": "q4", "q": "Biệt danh nổi tiếng của câu lạc bộ là gì?",
465
+ "answers": [{"id": "a1", "text": "The Gunners"}, {"id": "a2", "text": "The Blues"},
466
+ {"id": "a3", "text": "The Citizens"}, {"id": "a4", "text": "Quỷ Đỏ (Red Devils)"}], "correct": "a4"},
467
+ {"id": "q5", "q": "Huyền thoại nào khoác áo số 7 huyền thoại của MU?",
468
+ "answers": [{"id": "a1", "text": "David Beckham"}, {"id": "a2", "text": "Cristiano Ronaldo"},
469
+ {"id": "a3", "text": "Eric Cantona"}, {"id": "a4", "text": "Tất cả đều đúng"}], "correct": "a4"},
 
 
 
 
 
 
 
 
 
 
 
 
 
470
  ]
471
+ _right_messages = ["Chuẩn fan Quỷ đỏ! Mời vào hang.", "Chính xác! Sir Alex mà biết chắc cũng gật gù.",
472
+ "Đúng rồi! Glory Glory Man United!"]
473
+ _wrong_messages = ["Trượt mất rồi! Không sao, vào hang anh em kể thêm cho.",
474
  "Sai một chút thôi, hang vẫn mở cửa chào bạn.",
475
+ "Hụt như sút phạt đền vọt xà! Đáp án đúng tô xanh đó."]
476
 
477
  def _rand_pick(arr):
478
  return arr[random.randrange(len(arr))]
 
543
  if number is not None and not (1 <= number <= 99):
544
  raise HTTPException(422, "Jersey number must be 1-99")
545
  player = Player(id=player_id, name=req.player_name, number=number, sid=uuid.uuid4().hex[:12])
 
546
  rooms[req.room_id][player_id] = player
547
  player_rooms[player_id] = req.room_id
548
  return {"player_id": player_id, "room": {"id": req.room_id, "name": "Hang chung"},
 
559
  async def board():
560
  return {"videos": BOARD["videos"], "music": BOARD["music"]}
561
 
 
 
 
 
 
 
562
  @app.get("/api/board")
563
  async def api_board():
564
+ return {"videos": BOARD["videos"], "music": BOARD["music"]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565
 
566
  @app.get("/api/board/status")
567
  async def api_board_status():
 
575
  fresh = await asyncio.get_event_loop().run_in_executor(None, _board_refresh_playlist)
576
  _BOARD_SCRAPE["at"] = time.time()
577
  if fresh and fresh != BOARD["videos"]:
578
+ BOARD["videos"] = fresh
579
  _BOARD_SCRAPE["last_refresh"] = int(time.time())
580
  _board_persist()
581
  return {"ok": True, "videos": BOARD["videos"], "refreshed": bool(fresh)}
 
983
  if not text.strip():
984
  continue
985
  p.lastChatAt = now
 
986
  await broadcast(room_id, {"type": "chat", "player_id": player_id,
987
  "player_name": p.name, "message": text,
988
  "timestamp": now})
 
1043
  if p and poll and not poll.get("voted", {}).get(player_id):
1044
  poll["voted"][player_id] = True
1045
  poll["counts"][int(msg.get("option", 0)) % len(poll["options"])] += 1
 
1046
  await send(ws, {"type": "poll_result", "poll": poll})
1047
 
1048
  elif t == "inviteAsk":
 
1228
  elif t == "ping":
1229
  await send(ws, {"type": "pong", "t": msg.get("t", 0)})
1230
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1231
  except WebSocketDisconnect:
1232
  pass
1233
  finally:
 
1315
 
1316
  @app.get("/")
1317
  async def serve_index():
1318
+ return FileResponse("frontend/index.html")
 
 
 
1319
 
1320
  @app.get("/env.js")
1321
  async def env_js():
 
1328
  async def serve_static(path: str):
1329
  import os
1330
  # không nuốt websocket / API routes
1331
+ if path.startswith("ws/") or path.startswith("ext/") or path.startswith("push/"):
1332
  raise HTTPException(404, "Not found")
1333
  if path in _PWA_ROOT:
1334
  pf = os.path.join("frontend", "pwa", path)
 
1337
  file_path = os.path.join("frontend", path)
1338
  if os.path.exists(file_path) and os.path.isfile(file_path):
1339
  return FileResponse(file_path)
1340
+ return FileResponse("frontend/index.html")
 
1341
 
1342
  if __name__ == "__main__":
1343
  uvicorn.run(app, host="0.0.0.0", port=7860)
build/esbuild.config.mjs CHANGED
@@ -1,120 +1,10 @@
1
  // esbuild bundle config: bundles app.js + all deps (react, three, zustand) into ONE file
2
- // V83: FAIL FAST instead of shipping a stale/partial bundle.
3
- // An earlier esbuild error left a half-written app.bundle.js in the image,
4
- // so the Space kept serving a bundle without the new boards.
5
- // V96: guard markers updated — the flat HTML logo overlay ('vai-logo-overlay')
6
- // was REPLACED in v95 by the 3D rock stele. v95 creates VaiSteleRock, but
7
- // patch_v97.mjs REPLACES it with VaiSteleRockV2 (rectangular stele) — so the
8
- // name that actually exists in the final source is VaiSteleRockV2.
9
- // V116: runs the v116 patches FIRST, before bundling, so everything V116
10
- // changes is what actually gets compiled.
11
- //
12
- // DELIBERATE DECISION — the V116 contract check below WARNS, it does NOT
13
- // fail the build. Reason: the v116 patches restore their sources and exit 0
14
- // when an anchor drifts, so a failed V116 means "the Space still behaves
15
- // exactly like v115". If this check threw, that same situation would instead
16
- // FAIL the Docker build and take a working Space DOWN — strictly worse. A
17
- // patch that already self-restored must never break the build.
18
- // A hard failure is still correct for the pre-existing V83/V96 MUST list,
19
- // because those markers have always been present.
20
- //
21
- // V116e: THREE FIXES, all found by reading this file / the patches, not by
22
- // running them.
23
- // (a) `src` WAS NEVER DEFINED. Sections 3, 3b, 3c and the final log all use
24
- // `src.includes(...)`, but nothing in this file declared `src`. That is a
25
- // ReferenceError thrown immediately after a successful bundle — i.e. the
26
- // build dies AFTER esbuild did all the work, so the V83 fail-fast guard,
27
- // the V116 contract report and the 3c hard check never ran at all.
28
- // Now read once, right after the artifact is verified.
29
- // (b) THE 'React.React' REPAIR HAD A WHITESPACE HOLE. Detector tested
30
- // includes('React.React.useEffect') (NO space) and the repair used
31
- // /React\.[ \t]+React\./ (tab/space, no newline) — while the comment right
32
- // below writes the artifact as 'React. React.useEffect(' (WITH a space).
33
- // If that whitespace is a newline (what a multi-line replacement produces)
34
- // then detector, repair AND hard check all miss it: broken bundle, green
35
- // build. All three now use \bReact\.\s+React\.(?=useEffect\().
36
- // (c) THE BUILD ORDER WAS WRONG. patch_v116.mjs anchors home3d's stele text
37
- // with cutFn(s,'VaiSteleText'), but patch_v97 DELETES `function
38
- // VaiSteleText(` (it slices [const VAI_ROCK_POS = .. function
39
- // HomeForecourt(], which is where patch_v95 had put it) and defines
40
- // `VaiSteleText2` instead. cutFn's /function\s+VaiSteleText\s*\(/ cannot
41
- // match 'VaiSteleText2(', so it threw, `fatal` was set, and v116 restored
42
- // ALL FIVE FILES and exited 0: every goal discarded, build green.
43
- // patch_v116e.mjs now runs FIRST and repoints that anchor.
44
  import { build } from 'esbuild'
45
- import { existsSync, rmSync, statSync, readFileSync, writeFileSync } from 'node:fs'
46
- import { spawnSync } from 'node:child_process'
47
 
48
- /* ---------------------------------------------------------------------------
49
- V116 — apply the patches before bundling, IN THIS ORDER:
50
- patch_v116e.mjs FIRST: repair patch_v116.mjs's dead VaiSteleText anchor
51
- (patch_v97 deleted that name, creating VaiSteleText2).
52
- Without it v116 restores itself and nothing ships.
53
- patch_v116.mjs loaders/hook/textures, video effect, playlist, poll, board
54
- patch_v116a.mjs pick a RANDOM track on cave entry (playIdx < 0)
55
- patch_v116b.mjs replace the V115 back plate with the real poster, guarded
56
- by vaiLogoTex so it can never render a WHITE patch
57
- patch_v116c.mjs rebuild BangVangDiemDanh keeping the ORIGINAL 1024x1180
58
- canvas + geometry + rotation (-0.42 rad), adding the 4th
59
- "BINH CHON" column, and KEEPING the 60s polling from
60
- patch_v83 (v116 had dropped polling and resized the board)
61
- patch_v116d.mjs repair v116's function cut ('React.' was left behind, so
62
- the effect became React.React.useEffect -> TypeError)
63
- Output goes straight to the Docker log, so the build tells us exactly which
64
- items landed (and which anchor drifted).
65
- --------------------------------------------------------------------------- */
66
- for (const script of ['patch_v116e.mjs', 'patch_v116.mjs', 'patch_v116a.mjs', 'patch_v116b.mjs', 'patch_v116c.mjs', 'patch_v116d.mjs', 'patch_v117.mjs', 'patch_v118.mjs', 'patch_v119.mjs', 'patch_v120.mjs', 'patch_v121.mjs', 'patch_v122.mjs', 'patch_v122b.mjs', 'patch_v123.mjs', 'patch_v123b.mjs', 'patch_v124.mjs', 'patch_v125.mjs', 'patch_v126.mjs', 'patch_v127.mjs', 'patch_v128.mjs', 'patch_v129.mjs', 'patch_v130.mjs', 'patch_v131.mjs', 'patch_v132.mjs', 'patch_v133.mjs', 'patch_v134.mjs', 'patch_v135.mjs', 'patch_v136.mjs', 'patch_v137.mjs', 'patch_v138.mjs', 'patch_v139.mjs']) {
67
- if (!existsSync(script)) {
68
- if (script === 'patch_v116e.mjs') console.warn('[v116] MISSING ' + script + ' — v116 will restore itself (VaiSteleText anchor is dead) unless patch_v116.mjs was fixed another way')
69
- else console.warn('[v116] missing ' + script + ' — skip')
70
- continue
71
- }
72
- const r = spawnSync(process.execPath, [script, '.'], { stdio: 'inherit', env: process.env })
73
- if (r.error) console.warn('[v116] could not run ' + script + ': ' + r.error.message)
74
- else console.log('[v116] ' + script + ' exit=' + r.status)
75
- }
76
-
77
- /* ---------------------------------------------------------------------------
78
- V116 BELT AND BRACES — repair the dangling 'React.' directly here.
79
- patch_v116 cuts the video effect by function NAME, and lastIndexOf('useEffect(')
80
- lands INSIDE 'React.useEffect(' — so 6 chars ('React.') are left before the
81
- replacement and the result reads 'React. React.useEffect(', i.e.
82
- React.React.useEffect at runtime. That is a TypeError, but it is valid JS, so
83
- esbuild accepts it and the failure would only show in the browser.
84
- patch_v116d normally fixes this; doing it here as well means the source is
85
- correct even if that patch skipped (e.g. a guard mismatch). Idempotent.
86
- V116e: use \s+ so a NEWLINE between the two 'React.' is caught as well.
87
- --------------------------------------------------------------------------- */
88
- // 'React.' + whitespace + 'React.useEffect(' -> 'React.useEffect('
89
- // Narrow on purpose: it only matches when followed by useEffect(, so a comment
90
- // such as "React.ReactNode" can never be touched.
91
- const BAD_REACT = /\bReact\.\s+React\.(?=useEffect\()/g
92
- if (existsSync('frontend/app.js')) {
93
- const a = readFileSync('frontend/app.js', 'utf8')
94
- if (BAD_REACT.test(a)) {
95
- const fixed = a.replace(BAD_REACT, 'React.')
96
- if (!BAD_REACT.test(fixed)) {
97
- writeFileSync('frontend/app.js', fixed)
98
- console.log('[v116] repaired dangling "React." before bundling (would be a TypeError)')
99
- } else {
100
- console.warn('[v116] could NOT repair dangling "React." — bundle guard will fail')
101
- }
102
- }
103
- }
104
-
105
- const OUT = 'frontend/app.bundle.js'
106
-
107
- // 1) remove any stale artifact first
108
- if (existsSync(OUT)) {
109
- rmSync(OUT, { force: true })
110
- console.log('[esbuild] removed stale', OUT)
111
- }
112
-
113
- // 2) build; any error throws and fails the Docker build
114
- const res = await build({
115
  entryPoints: ['frontend/app.js'],
116
  bundle: true,
117
- outfile: OUT,
118
  format: 'iife',
119
  platform: 'browser',
120
  target: ['es2020', 'chrome110', 'firefox115', 'safari14'],
@@ -124,108 +14,5 @@ const res = await build({
124
  define: { 'process.env.NODE_ENV': '"production"' },
125
  external: [],
126
  logLevel: 'info',
127
- write: true,
128
  })
129
-
130
- if (res.errors && res.errors.length) {
131
- throw new Error('esbuild failed with ' + res.errors.length + ' error(s)')
132
- }
133
- if (!existsSync(OUT)) {
134
- throw new Error('esbuild reported success but ' + OUT + ' is missing')
135
- }
136
-
137
- /* V116e: read the bundle ONCE. 'src' was referenced by every check below but
138
- was never declared, so this whole file threw ReferenceError after a
139
- successful bundle and no guard ever ran. */
140
- const src = readFileSync(OUT, 'utf8')
141
-
142
- /* 3) verify the artifacts we care about actually landed in the bundle.
143
- NOTE: esbuild escapes non-ASCII, so match ASCII identifiers only.
144
- Each name below was checked against the patch that CREATES it in the FINAL
145
- source (i.e. after the whole chain, not just its first author):
146
- VaiSteleRockV2 <- patch_v97.mjs. patch_v95 first creates VaiSteleRock,
147
- then v97 replaces the whole block with VaiSteleRockV2
148
- (plus VaiSteleText2) and rewrites the JSX mounting it.
149
- So VaiSteleRock is NOT in the final source; V2 is.
150
- BangTinAI <- patch_v83.mjs
151
- makeAiNewsTex <- patch_v83.mjs
152
- BangVangDiemDanh <- patch_v83.mjs
153
- AiNewsModal <- patch_v96.mjs
154
- AiNewsModalHost <- patch_v98.mjs. CONFIRMED by reading v98 bytes 3..16KB:
155
- it defines `function AiNewsModalHost(item, onClose)`
156
- plus `function AiNewsModalBridge({ item, onClose })`
157
- and inserts both before `const MU_POEM = [`. An earlier
158
- note here said "see note below" and no note existed.
159
- */
160
- const MUST = ['VaiSteleRockV2', 'BangTinAI', 'makeAiNewsTex', 'BangVangDiemDanh', 'AiNewsModal', 'AiNewsModalHost']
161
- const missing = MUST.filter((m) => !src.includes(m))
162
- if (missing.length) {
163
- throw new Error(
164
- 'BUNDLE GUARD FAILED: missing ' + missing.join(', ') +
165
- ' — a patch did not apply; refusing to ship a broken bundle'
166
- )
167
- }
168
-
169
- /* 3b) V116 CONTRACT — report (do NOT fail) whether the five user requests are
170
- really in the bundle. These are ASCII identifiers/strings, so esbuild cannot
171
- mangle them. If v116 restored itself because an anchor drifted, this log is
172
- loud and specific, but the build still succeeds and the Space keeps running
173
- the previous behaviour instead of going down. */
174
- const V116 = [
175
- 'useVaiLogoTex', // (1) shirt logo = real image + async state
176
- 'VAI_LOGO_URL', // (1) /images/vai-logo.png
177
- '_v116NumTex', // (1) shirt number keeps its own plane
178
- '_v116FallbackTex', // (1) canvas crest if the image 404s
179
- 'vaiLogoTex &&', // (1) poster mesh guarded -> no WHITE patch
180
- // (esbuild injects /* @__PURE__ */ before
181
- // the JSX factory call, so 'vaiLogoTex && ('
182
- // never appears verbatim in the bundle)
183
- '_v116LoadVaiPoster', // (2) home3d poster loader
184
- 'loadV116Logo', // (2) cave3d poster loader
185
- 'hangmu-ended', // (4) auto-advance signal from the proxy
186
- 'Math.floor(Math.random() * useIds.length)', // (4) random track on cave entry
187
- 'playbarOpen', // (5) playlist panel is a toggle
188
- 'board-playbar-toggle', // (5) the button itself
189
- 'setInterval(pull,', // (3) attendance board still polls (60s, patch_v83 parity)
190
- // (esbuild minifies 60000 -> 6e4)
191
- 'width = 1024', // (3) board keeps its ORIGINAL size
192
- // (two statements on one line get re-spaced)
193
- '- 190, 164', // (3) 4th column header position: the TIN NHAN
194
- // column sits at (W - 190, 164) and the votes
195
- // column at (W - 54, 164). 'W' is RENAMED to 'W2'
196
- // by esbuild, so anchor on the stable numeric
197
- // offset instead of the variable name.
198
- ]
199
- const v116Missing = V116.filter((m) => !src.includes(m))
200
- if (v116Missing.length) {
201
- console.warn(
202
- 'V116 WARN: bundle is missing ' + v116Missing.join(', ') +
203
- ' — the v116 patches did not fully apply (see the [v116]/[v116a]/[v116b]/' +
204
- '[v116c]/[v116d] WARN lines above). The Space still runs the previous' +
205
- ' behaviour; NOT failing the build.'
206
- )
207
- } else {
208
- console.log('[esbuild] v116 markers present: ' + V116.join(', '))
209
- }
210
-
211
- /* 3c) HARD CHECK — a bundle containing a dangling 'React.' immediately before
212
- 'React.useEffect(' always crashes in the browser (React.React is undefined),
213
- yet esbuild accepts it because it is valid JS. The repair above should have
214
- removed it, so if it is STILL here something is badly wrong and we refuse to
215
- ship it. Kept deliberately NARROW (must be followed by useEffect() so a
216
- comment such as "React.ReactNode" or a legitimate JSX type annotation can
217
- never false-positive and take a working Space down).
218
- V116e: test the same \s+ pattern the repair uses, not the space-less
219
- substring — otherwise a newline-separated artifact passes every check. */
220
- if (src.includes('React.React.useEffect') || /\bReact\.\s+React\.(?=useEffect\()/.test(src)) {
221
- throw new Error(
222
- 'BUNDLE GUARD FAILED: bundle contains a dangling "React." before ' +
223
- '"React.useEffect" — this is a runtime TypeError. Fix patch_v116.mjs ' +
224
- 'cutCallContaining (it must prefer the LONGEST matching name, e.g. ' +
225
- '"React.useEffect(") before shipping.'
226
- )
227
- }
228
-
229
- const kb = (statSync(OUT).size / 1024).toFixed(1)
230
- console.log('[esbuild] bundle OK -> ' + OUT + ' (' + kb + ' kB)')
231
- console.log('[esbuild] guard markers present: ' + MUST.filter((m) => src.includes(m)).join(', '))
 
1
  // esbuild bundle config: bundles app.js + all deps (react, three, zustand) into ONE file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import { build } from 'esbuild'
 
 
3
 
4
+ await build({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  entryPoints: ['frontend/app.js'],
6
  bundle: true,
7
+ outfile: 'frontend/app.bundle.js',
8
  format: 'iife',
9
  platform: 'browser',
10
  target: ['es2020', 'chrome110', 'firefox115', 'safari14'],
 
14
  define: { 'process.env.NODE_ENV': '"production"' },
15
  external: [],
16
  logLevel: 'info',
 
17
  })
18
+ console.log('bundle OK -> frontend/app.bundle.js')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deploy-v37.txt DELETED
@@ -1 +0,0 @@
1
- deploy-v37: self-avatar rot PI + proxy always + yt_meta normalize
 
 
esbuild.config.mjs DELETED
@@ -1,231 +0,0 @@
1
- // esbuild bundle config: bundles app.js + all deps (react, three, zustand) into ONE file
2
- // V83: FAIL FAST instead of shipping a stale/partial bundle.
3
- // An earlier esbuild error left a half-written app.bundle.js in the image,
4
- // so the Space kept serving a bundle without the new boards.
5
- // V96: guard markers updated — the flat HTML logo overlay ('vai-logo-overlay')
6
- // was REPLACED in v95 by the 3D rock stele. v95 creates VaiSteleRock, but
7
- // patch_v97.mjs REPLACES it with VaiSteleRockV2 (rectangular stele) — so the
8
- // name that actually exists in the final source is VaiSteleRockV2.
9
- // V116: runs the v116 patches FIRST, before bundling, so everything V116
10
- // changes is what actually gets compiled.
11
- //
12
- // DELIBERATE DECISION — the V116 contract check below WARNS, it does NOT
13
- // fail the build. Reason: the v116 patches restore their sources and exit 0
14
- // when an anchor drifts, so a failed V116 means "the Space still behaves
15
- // exactly like v115". If this check threw, that same situation would instead
16
- // FAIL the Docker build and take a working Space DOWN — strictly worse. A
17
- // patch that already self-restored must never break the build.
18
- // A hard failure is still correct for the pre-existing V83/V96 MUST list,
19
- // because those markers have always been present.
20
- //
21
- // V116e: THREE FIXES, all found by reading this file / the patches, not by
22
- // running them.
23
- // (a) `src` WAS NEVER DEFINED. Sections 3, 3b, 3c and the final log all use
24
- // `src.includes(...)`, but nothing in this file declared `src`. That is a
25
- // ReferenceError thrown immediately after a successful bundle — i.e. the
26
- // build dies AFTER esbuild did all the work, so the V83 fail-fast guard,
27
- // the V116 contract report and the 3c hard check never ran at all.
28
- // Now read once, right after the artifact is verified.
29
- // (b) THE 'React.React' REPAIR HAD A WHITESPACE HOLE. Detector tested
30
- // includes('React.React.useEffect') (NO space) and the repair used
31
- // /React\.[ \t]+React\./ (tab/space, no newline) — while the comment right
32
- // below writes the artifact as 'React. React.useEffect(' (WITH a space).
33
- // If that whitespace is a newline (what a multi-line replacement produces)
34
- // then detector, repair AND hard check all miss it: broken bundle, green
35
- // build. All three now use \bReact\.\s+React\.(?=useEffect\().
36
- // (c) THE BUILD ORDER WAS WRONG. patch_v116.mjs anchors home3d's stele text
37
- // with cutFn(s,'VaiSteleText'), but patch_v97 DELETES `function
38
- // VaiSteleText(` (it slices [const VAI_ROCK_POS = .. function
39
- // HomeForecourt(], which is where patch_v95 had put it) and defines
40
- // `VaiSteleText2` instead. cutFn's /function\s+VaiSteleText\s*\(/ cannot
41
- // match 'VaiSteleText2(', so it threw, `fatal` was set, and v116 restored
42
- // ALL FIVE FILES and exited 0: every goal discarded, build green.
43
- // patch_v116e.mjs now runs FIRST and repoints that anchor.
44
- import { build } from 'esbuild'
45
- import { existsSync, rmSync, statSync, readFileSync, writeFileSync } from 'node:fs'
46
- import { spawnSync } from 'node:child_process'
47
-
48
- /* ---------------------------------------------------------------------------
49
- V116 — apply the patches before bundling, IN THIS ORDER:
50
- patch_v116e.mjs FIRST: repair patch_v116.mjs's dead VaiSteleText anchor
51
- (patch_v97 deleted that name, creating VaiSteleText2).
52
- Without it v116 restores itself and nothing ships.
53
- patch_v116.mjs loaders/hook/textures, video effect, playlist, poll, board
54
- patch_v116a.mjs pick a RANDOM track on cave entry (playIdx < 0)
55
- patch_v116b.mjs replace the V115 back plate with the real poster, guarded
56
- by vaiLogoTex so it can never render a WHITE patch
57
- patch_v116c.mjs rebuild BangVangDiemDanh keeping the ORIGINAL 1024x1180
58
- canvas + geometry + rotation (-0.42 rad), adding the 4th
59
- "BINH CHON" column, and KEEPING the 60s polling from
60
- patch_v83 (v116 had dropped polling and resized the board)
61
- patch_v116d.mjs repair v116's function cut ('React.' was left behind, so
62
- the effect became React.React.useEffect -> TypeError)
63
- Output goes straight to the Docker log, so the build tells us exactly which
64
- items landed (and which anchor drifted).
65
- --------------------------------------------------------------------------- */
66
- for (const script of ['patch_v116e.mjs', 'patch_v116.mjs', 'patch_v116a.mjs', 'patch_v116b.mjs', 'patch_v116c.mjs', 'patch_v116d.mjs', 'patch_v117.mjs', 'patch_v118.mjs', 'patch_v119.mjs', 'patch_v120.mjs', 'patch_v121.mjs', 'patch_v122.mjs', 'patch_v122b.mjs', 'patch_v123.mjs', 'patch_v123b.mjs', 'patch_v124.mjs', 'patch_v125.mjs', 'patch_v126.mjs', 'patch_v127.mjs']) {
67
- if (!existsSync(script)) {
68
- if (script === 'patch_v116e.mjs') console.warn('[v116] MISSING ' + script + ' — v116 will restore itself (VaiSteleText anchor is dead) unless patch_v116.mjs was fixed another way')
69
- else console.warn('[v116] missing ' + script + ' — skip')
70
- continue
71
- }
72
- const r = spawnSync(process.execPath, [script, '.'], { stdio: 'inherit', env: process.env })
73
- if (r.error) console.warn('[v116] could not run ' + script + ': ' + r.error.message)
74
- else console.log('[v116] ' + script + ' exit=' + r.status)
75
- }
76
-
77
- /* ---------------------------------------------------------------------------
78
- V116 BELT AND BRACES — repair the dangling 'React.' directly here.
79
- patch_v116 cuts the video effect by function NAME, and lastIndexOf('useEffect(')
80
- lands INSIDE 'React.useEffect(' — so 6 chars ('React.') are left before the
81
- replacement and the result reads 'React. React.useEffect(', i.e.
82
- React.React.useEffect at runtime. That is a TypeError, but it is valid JS, so
83
- esbuild accepts it and the failure would only show in the browser.
84
- patch_v116d normally fixes this; doing it here as well means the source is
85
- correct even if that patch skipped (e.g. a guard mismatch). Idempotent.
86
- V116e: use \s+ so a NEWLINE between the two 'React.' is caught as well.
87
- --------------------------------------------------------------------------- */
88
- // 'React.' + whitespace + 'React.useEffect(' -> 'React.useEffect('
89
- // Narrow on purpose: it only matches when followed by useEffect(, so a comment
90
- // such as "React.ReactNode" can never be touched.
91
- const BAD_REACT = /\bReact\.\s+React\.(?=useEffect\()/g
92
- if (existsSync('frontend/app.js')) {
93
- const a = readFileSync('frontend/app.js', 'utf8')
94
- if (BAD_REACT.test(a)) {
95
- const fixed = a.replace(BAD_REACT, 'React.')
96
- if (!BAD_REACT.test(fixed)) {
97
- writeFileSync('frontend/app.js', fixed)
98
- console.log('[v116] repaired dangling "React." before bundling (would be a TypeError)')
99
- } else {
100
- console.warn('[v116] could NOT repair dangling "React." — bundle guard will fail')
101
- }
102
- }
103
- }
104
-
105
- const OUT = 'frontend/app.bundle.js'
106
-
107
- // 1) remove any stale artifact first
108
- if (existsSync(OUT)) {
109
- rmSync(OUT, { force: true })
110
- console.log('[esbuild] removed stale', OUT)
111
- }
112
-
113
- // 2) build; any error throws and fails the Docker build
114
- const res = await build({
115
- entryPoints: ['frontend/app.js'],
116
- bundle: true,
117
- outfile: OUT,
118
- format: 'iife',
119
- platform: 'browser',
120
- target: ['es2020', 'chrome110', 'firefox115', 'safari14'],
121
- minify: false,
122
- sourcemap: false,
123
- loader: { '.js': 'jsx' },
124
- define: { 'process.env.NODE_ENV': '"production"' },
125
- external: [],
126
- logLevel: 'info',
127
- write: true,
128
- })
129
-
130
- if (res.errors && res.errors.length) {
131
- throw new Error('esbuild failed with ' + res.errors.length + ' error(s)')
132
- }
133
- if (!existsSync(OUT)) {
134
- throw new Error('esbuild reported success but ' + OUT + ' is missing')
135
- }
136
-
137
- /* V116e: read the bundle ONCE. 'src' was referenced by every check below but
138
- was never declared, so this whole file threw ReferenceError after a
139
- successful bundle and no guard ever ran. */
140
- const src = readFileSync(OUT, 'utf8')
141
-
142
- /* 3) verify the artifacts we care about actually landed in the bundle.
143
- NOTE: esbuild escapes non-ASCII, so match ASCII identifiers only.
144
- Each name below was checked against the patch that CREATES it in the FINAL
145
- source (i.e. after the whole chain, not just its first author):
146
- VaiSteleRockV2 <- patch_v97.mjs. patch_v95 first creates VaiSteleRock,
147
- then v97 replaces the whole block with VaiSteleRockV2
148
- (plus VaiSteleText2) and rewrites the JSX mounting it.
149
- So VaiSteleRock is NOT in the final source; V2 is.
150
- BangTinAI <- patch_v83.mjs
151
- makeAiNewsTex <- patch_v83.mjs
152
- BangVangDiemDanh <- patch_v83.mjs
153
- AiNewsModal <- patch_v96.mjs
154
- AiNewsModalHost <- patch_v98.mjs. CONFIRMED by reading v98 bytes 3..16KB:
155
- it defines `function AiNewsModalHost(item, onClose)`
156
- plus `function AiNewsModalBridge({ item, onClose })`
157
- and inserts both before `const MU_POEM = [`. An earlier
158
- note here said "see note below" and no note existed.
159
- */
160
- const MUST = ['VaiSteleRockV2', 'BangTinAI', 'makeAiNewsTex', 'BangVangDiemDanh', 'AiNewsModal', 'AiNewsModalHost']
161
- const missing = MUST.filter((m) => !src.includes(m))
162
- if (missing.length) {
163
- throw new Error(
164
- 'BUNDLE GUARD FAILED: missing ' + missing.join(', ') +
165
- ' — a patch did not apply; refusing to ship a broken bundle'
166
- )
167
- }
168
-
169
- /* 3b) V116 CONTRACT — report (do NOT fail) whether the five user requests are
170
- really in the bundle. These are ASCII identifiers/strings, so esbuild cannot
171
- mangle them. If v116 restored itself because an anchor drifted, this log is
172
- loud and specific, but the build still succeeds and the Space keeps running
173
- the previous behaviour instead of going down. */
174
- const V116 = [
175
- 'useVaiLogoTex', // (1) shirt logo = real image + async state
176
- 'VAI_LOGO_URL', // (1) /images/vai-logo.png
177
- '_v116NumTex', // (1) shirt number keeps its own plane
178
- '_v116FallbackTex', // (1) canvas crest if the image 404s
179
- 'vaiLogoTex &&', // (1) poster mesh guarded -> no WHITE patch
180
- // (esbuild injects /* @__PURE__ */ before
181
- // the JSX factory call, so 'vaiLogoTex && ('
182
- // never appears verbatim in the bundle)
183
- '_v116LoadVaiPoster', // (2) home3d poster loader
184
- 'loadV116Logo', // (2) cave3d poster loader
185
- 'hangmu-ended', // (4) auto-advance signal from the proxy
186
- 'Math.floor(Math.random() * useIds.length)', // (4) random track on cave entry
187
- 'playbarOpen', // (5) playlist panel is a toggle
188
- 'board-playbar-toggle', // (5) the button itself
189
- 'setInterval(pull,', // (3) attendance board still polls (60s, patch_v83 parity)
190
- // (esbuild minifies 60000 -> 6e4)
191
- 'width = 1024', // (3) board keeps its ORIGINAL size
192
- // (two statements on one line get re-spaced)
193
- '- 190, 164', // (3) 4th column header position: the TIN NHAN
194
- // column sits at (W - 190, 164) and the votes
195
- // column at (W - 54, 164). 'W' is RENAMED to 'W2'
196
- // by esbuild, so anchor on the stable numeric
197
- // offset instead of the variable name.
198
- ]
199
- const v116Missing = V116.filter((m) => !src.includes(m))
200
- if (v116Missing.length) {
201
- console.warn(
202
- 'V116 WARN: bundle is missing ' + v116Missing.join(', ') +
203
- ' — the v116 patches did not fully apply (see the [v116]/[v116a]/[v116b]/' +
204
- '[v116c]/[v116d] WARN lines above). The Space still runs the previous' +
205
- ' behaviour; NOT failing the build.'
206
- )
207
- } else {
208
- console.log('[esbuild] v116 markers present: ' + V116.join(', '))
209
- }
210
-
211
- /* 3c) HARD CHECK — a bundle containing a dangling 'React.' immediately before
212
- 'React.useEffect(' always crashes in the browser (React.React is undefined),
213
- yet esbuild accepts it because it is valid JS. The repair above should have
214
- removed it, so if it is STILL here something is badly wrong and we refuse to
215
- ship it. Kept deliberately NARROW (must be followed by useEffect() so a
216
- comment such as "React.ReactNode" or a legitimate JSX type annotation can
217
- never false-positive and take a working Space down).
218
- V116e: test the same \s+ pattern the repair uses, not the space-less
219
- substring — otherwise a newline-separated artifact passes every check. */
220
- if (src.includes('React.React.useEffect') || /\bReact\.\s+React\.(?=useEffect\()/.test(src)) {
221
- throw new Error(
222
- 'BUNDLE GUARD FAILED: bundle contains a dangling "React." before ' +
223
- '"React.useEffect" — this is a runtime TypeError. Fix patch_v116.mjs ' +
224
- 'cutCallContaining (it must prefer the LONGEST matching name, e.g. ' +
225
- '"React.useEffect(") before shipping.'
226
- )
227
- }
228
-
229
- const kb = (statSync(OUT).size / 1024).toFixed(1)
230
- console.log('[esbuild] bundle OK -> ' + OUT + ' (' + kb + ' kB)')
231
- console.log('[esbuild] guard markers present: ' + MUST.filter((m) => src.includes(m)).join(', '))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/app.bundle.js DELETED
The diff for this file is too large to render. See raw diff
 
frontend/app.js CHANGED
@@ -62,32 +62,32 @@ function TallyGlyph({ r }) {
62
  PLAYER AVATAR + TÊN (bubble) — trong Canvas
63
  ========================================================================= */
64
  const COLORS = ['#c8102e', '#da291c', '#fdbd10', '#4ade80', '#60a5fa', '#f472b6', '#a78bfa', '#fb923c']
65
- /* V108: Ao VANG + logo V.AI STUDIO sau lung. Mac dinh = vang (khong con do MU).
66
- Vẫn tôn trọng 'kit' mỗi người khi có (đa sắc), nhưng mặc định là vàng V.AI. */
67
  const MKIT = { toggle: false, _tex: null }
68
  function muKitTex() {
69
  if (MKIT._tex) return MKIT._tex
70
- // V108: AO VANG + logo V.AI STUDIO sau lung.
71
- const c = document.createElement('canvas'); c.width = 256; c.height = 160
72
  const g = c.getContext('2d')
73
- const yellowTop = g.createLinearGradient(0, 0, 0, 160)
74
- yellowTop.addColorStop(0, '#ffd83a'); yellowTop.addColorStop(0.5, '#f2c200'); yellowTop.addColorStop(1, '#c99e00')
75
- g.fillStyle = yellowTop; g.fillRect(0, 0, 256, 160)
76
- // co ao vang dam
77
- g.fillStyle = '#b8860b'
78
- g.beginPath(); g.moveTo(96, 0); g.lineTo(160, 0); g.lineTo(166, 18); g.lineTo(128, 22); g.lineTo(90, 18); g.closePath(); g.fill()
79
- // vien ao
80
- g.fillStyle = '#1b1b1b'; g.fillRect(0, 150, 256, 4); g.fillRect(0, 146, 256, 2)
81
- // LOGO V.AI STUDIO sau lung (giua lung)
82
- g.save()
83
- g.translate(128, 82)
84
- g.fillStyle = '#1a1a1a'
85
- g.font = '800 30px "Be Vietnam Pro", Arial, sans-serif'
86
- g.textAlign = 'center'; g.textBaseline = 'middle'
87
- g.fillText('V.AI', 0, -14)
88
- g.font = '700 18px "Be Vietnam Pro", Arial, sans-serif'
89
- g.fillText('STUDIO', 0, 16)
90
- g.restore()
 
91
  const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.needsUpdate = true
92
  MKIT._tex = t
93
  return t
@@ -125,8 +125,8 @@ function makeFaceTex(seed, mood) {
125
  torsoY 1, headR .25, headY 1.66, shoulderY 1.3, shoulderX .34,
126
  upperArm .22, foreArm .2, armR .075, handR .092, footR .105 */
127
  function PlayerAvatar({ id, p, isLocal }) {
128
- const color = (p.kit != null && COLORS[p.kit % COLORS.length]) || '#f2c200'
129
- const isMuKit = (p.kit == null) || color === '#f2c200'
130
  const bob = React.useRef(0)
131
  const rootRef = React.useRef(null)
132
  const armL = React.useRef(null)
@@ -144,9 +144,7 @@ function PlayerAvatar({ id, p, isLocal }) {
144
  setMood(p.talking ? 'talk' : (p.anim === 'run' || p.anim === 'walk') ? 'normal' : 'happy')
145
  }, [p.anim, p.talking])
146
  useFrame((_, dt) => {
147
- // V108: dung yen = KHONG co dong tac chay. Chi animate khi anim la run/walk
148
- // VA thuc su dang di chuyen (p.moving !== false).
149
- const A = (p.anim === 'run' && p.moving !== false) ? 14 : ((p.anim === 'walk' && p.moving !== false) ? 8 : 0)
150
  let sw = 0
151
  if (A) {
152
  bob.current += dt * A
@@ -184,10 +182,10 @@ function PlayerAvatar({ id, p, isLocal }) {
184
  const AVATAR_SCALE = 1
185
  return (
186
  <group ref={rootRef} position={[p.pos.x, gy, p.pos.z]} rotation={[0, p.rot, 0]} scale={[AVATAR_SCALE, AVATAR_SCALE, AVATAR_SCALE]}>
187
- {/* THÂN — áo đấu vàng V.AI (mặc định), mảnh giống gốc (torsoR 0.3, torsoLen 0.34) */}
188
  <mesh castShadow position={[0, 1.0, 0]}>
189
  <capsuleGeometry args={[0.3, 0.34, 4, 10]} />
190
- <meshStandardMaterial map={isMuKit ? muKitTex() : null} color={isMuKit ? '#f2c200' : color} roughness={0.72} metalness={0.08} />
191
  </mesh>
192
  {/* CỔ */}
193
  <mesh position={[0, 1.4, 0]}>
@@ -216,33 +214,32 @@ function PlayerAvatar({ id, p, isLocal }) {
216
  <meshStandardMaterial color={0x1c1610} roughness={0.92} />
217
  </mesh>
218
  </group>
219
- {/* V108: TAY NHỎ GỌN + LỊCH SỰ HƠN — thu nhỏ bán kính + giảm nghiêng
220
- (0.35→0.12) để tay xuôi thẳng, dáng đứng lịch sự, không xòe chữ V. */}
221
  <group ref={armL} position={[-0.34, 1.3, 0]}>
222
- <mesh castShadow rotation={[0, 0, 0.12]}>
223
- <capsuleGeometry args={[0.06, 0.22, 4, 8]} />
224
- <meshStandardMaterial color={isMuKit ? '#f2c200' : color} roughness={0.72} />
225
  </mesh>
226
- <mesh castShadow position={[0, -0.2, 0]} rotation={[0, 0, 0.12]}>
227
- <capsuleGeometry args={[0.05, 0.2, 4, 8]} />
228
  <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />
229
  </mesh>
230
- <mesh castShadow position={[0, -0.38, 0]} rotation={[0, 0, 0.12]}>
231
- <sphereGeometry args={[0.05, 8, 8]} />
232
  <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />
233
  </mesh>
234
  </group>
235
  <group ref={armR} position={[0.34, 1.3, 0]}>
236
- <mesh castShadow rotation={[0, 0, -0.12]}>
237
- <capsuleGeometry args={[0.06, 0.22, 4, 8]} />
238
- <meshStandardMaterial color={isMuKit ? '#f2c200' : color} roughness={0.72} />
239
  </mesh>
240
- <mesh castShadow position={[0, -0.2, 0]} rotation={[0, 0, -0.12]}>
241
- <capsuleGeometry args={[0.05, 0.2, 4, 8]} />
242
  <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />
243
  </mesh>
244
- <mesh castShadow position={[0, -0.38, 0]} rotation={[0, 0, -0.12]}>
245
- <sphereGeometry args={[0.05, 8, 8]} />
246
  <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />
247
  </mesh>
248
  </group>
@@ -254,7 +251,7 @@ function PlayerAvatar({ id, p, isLocal }) {
254
  </mesh>
255
  <mesh castShadow position={[0, -0.33, 0.02]}>
256
  <capsuleGeometry args={[0.075, 0.24, 4, 8]} />
257
- <meshStandardMaterial color={0xf2c200} roughness={0.8} />
258
  </mesh>
259
  <mesh position={[0, -0.52, 0.1]} rotation-x={0.25}>
260
  <boxGeometry args={[0.12, 0.07, 0.21]} />
@@ -268,7 +265,7 @@ function PlayerAvatar({ id, p, isLocal }) {
268
  </mesh>
269
  <mesh castShadow position={[0, -0.33, 0.02]}>
270
  <capsuleGeometry args={[0.075, 0.24, 4, 8]} />
271
- <meshStandardMaterial color={0xf2c200} roughness={0.8} />
272
  </mesh>
273
  <mesh position={[0, -0.52, 0.1]} rotation-x={0.25}>
274
  <boxGeometry args={[0.12, 0.07, 0.21]} />
@@ -543,7 +540,6 @@ function Movement({ touch }) {
543
  }
544
  const anim = running ? 'run' : (moving ? 'walk' : 'idle')
545
  me.anim = anim
546
- me.moving = moving
547
  // dùng me.pos (luôn tồn tại) thay nx/nz — chống ReferenceError khi đứng yên
548
  const p = last.current
549
  if (!p.pos || Math.abs(me.pos.x - p.pos.x) > 0.01 || Math.abs(me.pos.z - p.pos.z) > 0.01 || p.rot !== rot || p.anim !== anim) {
@@ -641,9 +637,9 @@ function RoomBadge() {
641
  function TelegramBtn() {
642
  return (
643
  <div className="cave-tele-wrap">
644
- <a className="cave-tele" href="https://zalo.me/g/lqqsdb924" target="_blank" rel="noopener noreferrer" data-attn>
645
- <ZaloIcon />
646
- Group Zalo
647
  </a>
648
  </div>
649
  )
@@ -1058,24 +1054,24 @@ function Home({ me, queuePhase, queuePos, retryIn, onEnter, onRename, onShowLega
1058
  const waiting = status ? status.waiting : 0
1059
  return (
1060
  <main className="home">
1061
- <h1 className="visually-hidden">Hang Tu Trí AI V.AI Studio</h1>
1062
  <div className="home-scene">
1063
  <Canvas shadows camera={{ position: [0, 2, 16], fov: 44, near: 0.1, far: 120 }}
1064
  gl={{ antialias: true, alpha: true, powerPreference: 'high-performance' }}
1065
- aria-label="Cửa hang động với bia đá khắc chữ Hang Tu Trí AI V.AI Studio">
1066
  <HomeScene />
1067
  </Canvas>
1068
  </div>
1069
  <section className="home-panel plaque" aria-labelledby="home-title">
1070
  <header className="home-head">
1071
- <p className="plaque-kicker">Hang Tu Trí AI</p>
1072
- <p className="plaque-title home-title" id="home-title">AI V.AI STUDIO</p>
1073
  </header>
1074
  <p className="forecourt-step" role="note">
1075
  🏟️ Bước 1 · Sân trước cửa hang — <strong>đặt tên nhân vật</strong> trước khi vào
1076
  </p>
1077
  <hr className="plaque-rule" />
1078
- <p className="home-lede">Nơi học sĩ không biết AI vào hang và ra hang sau mỗi lần VIBE CODE</p>
1079
  {inRoom != null && (
1080
  <p className="home-count">
1081
  <span>Đang trong hang</span> <Tally n={inRoom} label={`${inRoom} anh em`} />
@@ -1101,249 +1097,1077 @@ function Home({ me, queuePhase, queuePos, retryIn, onEnter, onRename, onShowLega
1101
  )}
1102
  </section>
1103
  <nav className="home-links" aria-label="Liên kết khác">
1104
- <a className="home-tele" href="https://zalo.me/g/lqqsdb924" target="_blank" rel="noopener noreferrer" aria-label="Tham gia group Zalo HangMu (mở tab mới)">
1105
- <ZaloIcon /> Group Zalo
1106
  </a>
1107
  <PwaInstall className="home-install" short />
1108
  <PushButton className="home-push" />
1109
  </nav>
 
 
 
 
1110
  </main>
1111
  )
1112
  }
1113
- function ZaloIcon() {
1114
- // Biểu tượng Zalo (ảnh chính thức từ zalobot.vn).
1115
  return (
1116
- <img src="https://zalobot.vn/wp-content/uploads/2025/09/zalo-icon.png" alt="" width="18" height="18" loading="lazy" decoding="async" className="zalo-icon" />
1117
  )
1118
  }
1119
 
1120
  /* =========================================================================
1121
- QUIZ
1122
  ========================================================================= */
1123
- const QUIZ_QS = [
1124
- { q: 'V.AI STUDIO là gì?', a: ['Một studio game', 'Một AI vibe coding club', 'Một quán cà phê', 'Một CLB bóng đá'], c: 1 },
1125
- { q: 'Hang Tu Trí AI dành cho ai?', a: ['Chỉ lập trình viên', 'Chỉ nhà khoa học', 'Người muốn học AI từ đầu', 'Chỉ du khách'], c: 2 },
1126
- { q: 'Muốn vào hang cần gì?', a: ['Một chiếc đèn pin', 'Một cái tên + tinh thần VIBE CODE', 'Một vé máy bay', 'Một laptop xịn'], c: 1 },
1127
- { q: ' linh vật của hang là gì?', a: ['Con rồng', 'Hố lửa', 'Bảng phong thần', 'Cả ba'], c: 3 },
1128
- ]
1129
- function QuizModal({ onDone }) {
1130
- const [step, setStep] = React.useState(0)
1131
- const [picked, setPicked] = React.useState(null)
1132
- const quiz = QUIZ_QS[step]
1133
- const choose = (i) => {
1134
- if (picked != null) return
1135
- setPicked(i)
1136
- setTimeout(() => {
1137
- if (step + 1 >= QUIZ_QS.length) onDone()
1138
- else { setStep(step + 1); setPicked(null) }
1139
- }, 650)
 
 
 
 
1140
  }
1141
  return (
1142
- <div className="quiz-scrim">
1143
- <section className="quiz-card slab">
1144
- <p className="quiz-kicker">V.AI STUDIO · CÂU {step + 1}/{QUIZ_QS.length}</p>
1145
- <h2 className="quiz-q">{quiz.q}</h2>
1146
- <div className="quiz-opts">
1147
- {quiz.a.map((txt, i) => (
1148
- <button key={i} type="button"
1149
- className={`quiz-opt${picked == null ? '' : (i === quiz.c ? ' is-ok' : (i === picked ? ' is-bad' : ' is-dim'))}`}
1150
- onClick={() => choose(i)}>
1151
- {txt}
1152
- </button>
1153
- ))}
 
 
 
 
 
 
 
1154
  </div>
1155
- </section>
 
 
 
 
1156
  </div>
1157
  )
1158
  }
1159
 
1160
  /* =========================================================================
1161
- LEGAL
1162
  ========================================================================= */
1163
- function LegalModal({ kind, onClose }) {
1164
- if (!kind) return null
1165
- const title = kind === 'terms' ? 'Điều khoản' : 'Chính sách bảo mật'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1166
  return (
1167
- <div className="legal-scrim" onClick={onClose}>
1168
- <div className="legal-card slab" onClick={(e) => e.stopPropagation()}>
1169
- <button type="button" className="legal-x" onClick={onClose} aria-label="Đóng">×</button>
1170
- <h2 className="legal-title">{title}</h2>
1171
- <p className="legal-body">Hang Tu Trí AI V.AI STUDIO là một không gian cộng đồng. Khi vào hang, bạn đồng ý giữ thái độ lịch sự, không spam, không quấy rối. Dữ liệu tên và số áo của bạn chỉ dùng để hiển thị trong hang.</p>
1172
- <button type="button" className="legal-ok carved-btn carved-btn--primary" onClick={onClose}>Đã hiểu</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1173
  </div>
1174
  </div>
1175
  )
1176
  }
1177
 
1178
  /* =========================================================================
1179
- DONATE
1180
  ========================================================================= */
1181
- function DonateModal({ onClose }) {
1182
- if (!onClose) return null
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1183
  return (
1184
- <div className="legal-scrim" onClick={onClose}>
1185
- <div className="legal-card slab" onClick={(e) => e.stopPropagation()}>
1186
- <button type="button" className="legal-x" onClick={onClose} aria-label="Đóng">×</button>
1187
- <h2 className="legal-title">Ủng hộ hang</h2>
1188
- <p className="legal-body">Mọi đóng góp giúp hang duy trì server và thêm tính năng. Cảm ơn anh em!</p>
1189
- <img src="/images/donate-qr.png" alt="Mã QR ủng hộ" className="donate-qr" />
1190
- <button type="button" className="legal-ok carved-btn carved-btn--primary" onClick={onClose}>Đóng</button>
 
1191
  </div>
1192
  </div>
1193
  )
1194
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1195
 
1196
  /* =========================================================================
1197
- APP — root
1198
  ========================================================================= */
1199
- function App() {
1200
- const touch = ('ontouchstart' in window)
1201
- const playerId = useGame((s) => s.playerId)
1202
- const players = useGame((s) => s.players)
1203
- const screen = useGame((s) => s.screen)
1204
- const me = players.get(playerId)
1205
- const [nameModal, setNameModal] = React.useState(false)
1206
- const [quizDone, setQuizDone] = React.useState(false)
1207
- const [legal, setLegal] = React.useState(null)
1208
- const [donate, setDonate] = React.useState(false)
1209
- const [queuePhase, setQueuePhase] = React.useState('idle')
1210
- const [queuePos, setQueuePos] = React.useState(0)
1211
- const [retryIn, setRetryIn] = React.useState(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1212
 
1213
- React.useEffect(() => { connect() }, [])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1214
 
1215
- useEffect(() => { if (me && !quizDone && screen === 'home') setNameModal(true) }, [me, quizDone, screen])
 
 
 
 
 
 
 
 
 
 
 
1216
 
1217
- const enter = () => {
1218
- if (!me) { setNameModal(true); return }
1219
- setQueuePhase('connecting')
1220
- apiJoin().then((res) => {
1221
- if (res.ok) { setQueuePhase('idle'); useGame.getState().setScreen('cave') }
1222
- else if (res.waiting) { setQueuePhase('queued'); setQueuePos(res.pos); }
1223
- else { setQueuePhase('idle'); setRetryIn(res.retryIn || 5) }
1224
- }).catch(() => { setQueuePhase('idle') })
1225
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1226
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1227
  React.useEffect(() => {
1228
- if (queuePhase !== 'queued') return
 
1229
  const iv = setInterval(() => {
1230
- apiJoin().then((res) => {
1231
- if (res.ok) { setQueuePhase('idle'); useGame.getState().setScreen('cave') }
1232
- else if (res.waiting) setQueuePos(res.pos)
1233
- else { setQueuePhase('idle'); setRetryIn(res.retryIn || 5) }
1234
- }).catch(() => {})
1235
- }, 3000)
1236
  return () => clearInterval(iv)
1237
- }, [queuePhase])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1238
 
1239
  React.useEffect(() => {
1240
- if (retryIn <= 0) return
1241
- const t = setTimeout(() => setRetryIn(retryIn - 1), 1000)
1242
- return () => clearTimeout(t)
1243
- }, [retryIn])
 
 
 
 
 
 
 
 
1244
 
1245
- const leaveHang = () => { leave(); useGame.getState().setScreen('home'); setQueuePhase('idle') }
1246
- const queueCancel = () => { apiLeaveQueue(); setQueuePhase('idle') }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1247
 
 
1248
  return (
1249
- <div className={screen === 'cave' ? 'app is-cave' : 'app is-home'}>
1250
- {screen === 'home' && (
1251
- <Home me={me} queuePhase={queuePhase} queuePos={queuePos} retryIn={retryIn}
1252
- onEnter={enter} onRename={() => setNameModal(true)} onShowLegal={setLegal} onQueueCancel={queueCancel} />
 
 
 
 
 
 
 
1253
  )}
1254
- {screen === 'cave' && (
1255
- <div className="cave-wrap" id="cave-canvas-wrap">
1256
- <Canvas shadows camera={{ position: [0, 8, 18], fov: 50, near: 0.1, far: 300 }}
1257
- gl={{ antialias: true, alpha: false, powerPreference: 'high-performance' }}>
1258
- <color attach="background" args={['#1a0f0a']} />
1259
- <fog attach="fog" args={['#1a0f0a', 18, 70]} />
1260
- <CaveScene />
1261
- <PlayerAvatars />
1262
- <CameraRig />
1263
- <Movement touch={touch} />
1264
- <Projector />
1265
- </Canvas>
1266
- <NameTags />
1267
- <div className="cave-topbar">
1268
- <button type="button" className="cave-leave" onClick={leaveHang}>← Ra hang</button>
1269
- <RoomBadge />
1270
- <SoundButton />
1271
- <TvButton />
1272
- <TelegramBtn />
1273
  </div>
1274
- <ChatToggle touch={touch} />
1275
- <PunchButton touch={touch} />
1276
- <CelebrateButton touch={touch} />
1277
- <InviteOverlay touch={touch} />
1278
- <PollOverlay />
1279
- <GoalOverlay />
1280
- <ReconnectOverlay />
1281
- <PunchedOverlay />
1282
- <HelpButton />
1283
- <Credits />
1284
- <Crosshair />
1285
- <button type="button" className="cave-donate" onClick={() => setDonate(true)}>❤ Ủng hộ</button>
1286
- {touch && <Scoreboard touch={touch} />}
1287
- {touch && <VoiceHall touch={touch} />}
1288
- {touch && <TugGame touch={touch} />}
1289
- {touch && <BallGame touch={touch} />}
1290
- {touch && <PwaInstall touch={touch} />}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1291
  </div>
1292
  )}
1293
- {nameModal && <NameModal me={me} onClose={() => setNameModal(false)} onSaved={() => { setNameModal(false); if (!quizDone) setQuizDone(true) }} />}
1294
- {!nameModal && me && !quizDone && screen === 'home' && quizDone === false && null}
1295
- <LegalModal kind={legal} onClose={() => setLegal(null)} />
1296
- <DonateModal onClose={donate ? () => setDonate(false) : null} />
1297
- </div>
1298
  )
1299
  }
1300
 
1301
  /* =========================================================================
1302
- NAME MODAL
1303
  ========================================================================= */
1304
- function NameModal({ me, onClose, onSaved }) {
1305
- const [name, setName] = React.useState(me?.name || '')
1306
- const [num, setNum] = React.useState(me?.number ?? '')
1307
- const [saving, setSaving] = React.useState(false)
1308
- const submit = (e) => {
 
 
 
 
 
 
 
1309
  e.preventDefault()
1310
- if (!name.trim()) return
1311
- setSaving(true)
1312
- apiJoin({ name: name.trim(), number: num ? Number(num) : null }).then(() => { setSaving(false); onSaved() })
1313
- .catch(() => setSaving(false))
1314
  }
1315
  return (
1316
- <div className="name-scrim">
1317
- <form className="name-card slab" onSubmit={submit}>
1318
- <p className="name-kicker">V.AI STUDIO · ĐẶT TÊN</p>
1319
- <h2 className="name-title">Bạn tên gì?</h2>
1320
- <input className="name-input" value={name} onChange={(e) => setName(e.target.value)} maxLength={20} placeholder="Tên nhân vật" autoFocus />
1321
- <input className="name-num" type="number" min="0" max="99" value={num} onChange={(e) => setNum(e.target.value)} placeholder="Số áo (0-99)" />
1322
- <button type="submit" className="name-save carved-btn carved-btn--primary" disabled={saving || !name.trim()}>
1323
- {saving ? 'Đang lưu…' : 'Lưu'}
1324
- </button>
1325
- </form>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1326
  </div>
1327
  )
1328
  }
1329
-
1330
- /* =========================================================================
1331
- PLAYER AVATARS renderer
1332
- ========================================================================= */
1333
- function PlayerAvatars() {
1334
- const players = useGame((s) => s.players)
1335
  const playerId = useGame((s) => s.playerId)
 
 
 
 
 
 
 
 
 
1336
  return (
1337
- <group>
1338
- {[...players.entries()].map(([id, p]) => (
1339
- <PlayerAvatar key={id} id={id} p={p} isLocal={id === playerId} />
1340
- ))}
1341
- </group>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1342
  )
1343
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1344
 
1345
  /* =========================================================================
1346
- MOUNT
1347
  ========================================================================= */
1348
- const root = createRoot(document.getElementById('root'))
1349
- root.render(<App />)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  PLAYER AVATAR + TÊN (bubble) — trong Canvas
63
  ========================================================================= */
64
  const COLORS = ['#c8102e', '#da291c', '#fdbd10', '#4ade80', '#60a5fa', '#f472b6', '#a78bfa', '#fb923c']
65
+ /* Áo MU đỏ đặc trưng — được dùng làm kit mặc định để nhân vật trông giống cầu thủ MU.
66
+ Vẫn tôn trọng 'kit' mỗi người khi có (đa sắc), nhưng mặc định là đỏ Quỷ Đỏ. */
67
  const MKIT = { toggle: false, _tex: null }
68
  function muKitTex() {
69
  if (MKIT._tex) return MKIT._tex
70
+ const c = document.createElement('canvas'); c.width = 128; c.height = 160
 
71
  const g = c.getContext('2d')
72
+ const redTop = g.createLinearGradient(0, 0, 0, 160)
73
+ redTop.addColorStop(0, '#e11d3c'); redTop.addColorStop(0.5, '#c8102e'); redTop.addColorStop(1, '#9a0b22')
74
+ g.fillStyle = redTop; g.fillRect(0, 0, 128, 160)
75
+ // collar trắng (cổ áo đội)
76
+ g.fillStyle = '#f4f0e6'
77
+ g.beginPath(); g.moveTo(44, 0); g.lineTo(84, 0); g.lineTo(88, 18); g.lineTo(72, 22); g.lineTo(56, 22); g.lineTo(40, 18); g.closePath(); g.fill()
78
+ g.fillStyle = '#cf1128'; g.fillRect(52, 0, 24, 8)
79
+ // viền vàng chạy ngang thân áo (đai áo)
80
+ g.fillStyle = '#d0a83c'; g.fillRect(0, 126, 128, 6)
81
+ g.fillStyle = '#f4f0e6'; g.fillRect(0, 132, 128, 7)
82
+ g.fillStyle = '#b98d30'; g.fillRect(0, 139, 128, 4)
83
+ // viền tay áo
84
+ g.fillStyle = '#d0a83c'; g.fillRect(0, 40, 12, 10); g.fillRect(116, 40, 12, 10)
85
+ g.fillStyle = '#f4f0e6'; g.fillRect(0, 50, 12, 10); g.fillRect(116, 50, 12, 10)
86
+ // huy hiệu gợi ý trên ngực (cây đinh ba vàng)
87
+ g.fillStyle = '#f2c14e'
88
+ g.beginPath(); g.moveTo(64, 74); g.lineTo(70, 88); g.lineTo(74, 84); g.lineTo(74, 98); g.lineTo(70, 94); g.lineTo(64, 108); g.lineTo(58, 94); g.lineTo(54, 98); g.lineTo(54, 84); g.lineTo(58, 88); g.closePath(); g.fill()
89
+ g.fillStyle = '#c8102e'; g.font = '700 11px Georgia, serif'; g.textAlign = 'center'
90
+ g.fillText('★ UNITED ★', 64, 122)
91
  const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.needsUpdate = true
92
  MKIT._tex = t
93
  return t
 
125
  torsoY 1, headR .25, headY 1.66, shoulderY 1.3, shoulderX .34,
126
  upperArm .22, foreArm .2, armR .075, handR .092, footR .105 */
127
  function PlayerAvatar({ id, p, isLocal }) {
128
+ const color = (p.kit != null && COLORS[p.kit % COLORS.length]) || '#c8102e'
129
+ const isMuKit = (p.kit == null) || color === '#c8102e'
130
  const bob = React.useRef(0)
131
  const rootRef = React.useRef(null)
132
  const armL = React.useRef(null)
 
144
  setMood(p.talking ? 'talk' : (p.anim === 'run' || p.anim === 'walk') ? 'normal' : 'happy')
145
  }, [p.anim, p.talking])
146
  useFrame((_, dt) => {
147
+ const A = p.anim === 'run' ? 14 : (p.anim === 'walk' ? 8 : 0)
 
 
148
  let sw = 0
149
  if (A) {
150
  bob.current += dt * A
 
182
  const AVATAR_SCALE = 1
183
  return (
184
  <group ref={rootRef} position={[p.pos.x, gy, p.pos.z]} rotation={[0, p.rot, 0]} scale={[AVATAR_SCALE, AVATAR_SCALE, AVATAR_SCALE]}>
185
+ {/* THÂN — áo đấu đỏ MU (mặc định), mảnh giống gốc (torsoR 0.3, torsoLen 0.34) */}
186
  <mesh castShadow position={[0, 1.0, 0]}>
187
  <capsuleGeometry args={[0.3, 0.34, 4, 10]} />
188
+ <meshStandardMaterial map={isMuKit ? muKitTex() : null} color={isMuKit ? '#c8102e' : color} roughness={0.72} metalness={0.08} />
189
  </mesh>
190
  {/* CỔ */}
191
  <mesh position={[0, 1.4, 0]}>
 
214
  <meshStandardMaterial color={0x1c1610} roughness={0.92} />
215
  </mesh>
216
  </group>
217
+ {/* TAY — áo đỏ + cẳng tay da, mảnh (shoulderX .34, armR .075) */}
 
218
  <group ref={armL} position={[-0.34, 1.3, 0]}>
219
+ <mesh castShadow rotation={[0, 0, 0.35]}>
220
+ <capsuleGeometry args={[0.075, 0.22, 4, 8]} />
221
+ <meshStandardMaterial color={color} roughness={0.72} />
222
  </mesh>
223
+ <mesh castShadow position={[0, -0.2, 0]} rotation={[0, 0, 0.35]}>
224
+ <capsuleGeometry args={[0.058, 0.2, 4, 8]} />
225
  <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />
226
  </mesh>
227
+ <mesh castShadow position={[0, -0.38, 0]} rotation={[0, 0, 0.35]}>
228
+ <sphereGeometry args={[0.06, 8, 8]} />
229
  <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />
230
  </mesh>
231
  </group>
232
  <group ref={armR} position={[0.34, 1.3, 0]}>
233
+ <mesh castShadow rotation={[0, 0, -0.35]}>
234
+ <capsuleGeometry args={[0.075, 0.22, 4, 8]} />
235
+ <meshStandardMaterial color={color} roughness={0.72} />
236
  </mesh>
237
+ <mesh castShadow position={[0, -0.2, 0]} rotation={[0, 0, -0.35]}>
238
+ <capsuleGeometry args={[0.058, 0.2, 4, 8]} />
239
  <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />
240
  </mesh>
241
+ <mesh castShadow position={[0, -0.38, 0]} rotation={[0, 0, -0.35]}>
242
+ <sphereGeometry args={[0.06, 8, 8]} />
243
  <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />
244
  </mesh>
245
  </group>
 
251
  </mesh>
252
  <mesh castShadow position={[0, -0.33, 0.02]}>
253
  <capsuleGeometry args={[0.075, 0.24, 4, 8]} />
254
+ <meshStandardMaterial color={0xc8102e} roughness={0.8} />
255
  </mesh>
256
  <mesh position={[0, -0.52, 0.1]} rotation-x={0.25}>
257
  <boxGeometry args={[0.12, 0.07, 0.21]} />
 
265
  </mesh>
266
  <mesh castShadow position={[0, -0.33, 0.02]}>
267
  <capsuleGeometry args={[0.075, 0.24, 4, 8]} />
268
+ <meshStandardMaterial color={0xc8102e} roughness={0.8} />
269
  </mesh>
270
  <mesh position={[0, -0.52, 0.1]} rotation-x={0.25}>
271
  <boxGeometry args={[0.12, 0.07, 0.21]} />
 
540
  }
541
  const anim = running ? 'run' : (moving ? 'walk' : 'idle')
542
  me.anim = anim
 
543
  // dùng me.pos (luôn tồn tại) thay nx/nz — chống ReferenceError khi đứng yên
544
  const p = last.current
545
  if (!p.pos || Math.abs(me.pos.x - p.pos.x) > 0.01 || Math.abs(me.pos.z - p.pos.z) > 0.01 || p.rot !== rot || p.anim !== anim) {
 
637
  function TelegramBtn() {
638
  return (
639
  <div className="cave-tele-wrap">
640
+ <a className="cave-tele" href="https://t.me/hangmu_online" target="_blank" rel="noopener noreferrer" data-attn>
641
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M9.78 18.65l.28-4.23 7.68-6.92c.34-.31-.07-.46-.52-.19L7.74 13.3 3.64 12c-.88-.25-.89-.86.2-1.3l15.97-6.16c.73-.33 1.43.18 1.15 1.3l-2.72 12.81c-.19.91-.74 1.13-1.5.71L12.6 16.3l-1.99 1.93c-.23.23-.42.42-.83.42z"/></svg>
642
+ Group Telegram
643
  </a>
644
  </div>
645
  )
 
1054
  const waiting = status ? status.waiting : 0
1055
  return (
1056
  <main className="home">
1057
+ <h1 className="visually-hidden">Di tích lịch sử Hang MU</h1>
1058
  <div className="home-scene">
1059
  <Canvas shadows camera={{ position: [0, 2, 16], fov: 44, near: 0.1, far: 120 }}
1060
  gl={{ antialias: true, alpha: true, powerPreference: 'high-performance' }}
1061
+ aria-label="Cửa hang động với bia đá khắc chữ Di tích lịch sử Hang MU">
1062
  <HomeScene />
1063
  </Canvas>
1064
  </div>
1065
  <section className="home-panel plaque" aria-labelledby="home-title">
1066
  <header className="home-head">
1067
+ <p className="plaque-kicker">Di tích lịch sử</p>
1068
+ <p className="plaque-title home-title" id="home-title">Hang MU</p>
1069
  </header>
1070
  <p className="forecourt-step" role="note">
1071
  🏟️ Bước 1 · Sân trước cửa hang — <strong>đặt tên nhân vật</strong> trước khi vào
1072
  </p>
1073
  <hr className="plaque-rule" />
1074
+ <p className="home-lede">Nơi anh em trú sau mỗi trận thua, và cùng ra hang khi đội thắng.</p>
1075
  {inRoom != null && (
1076
  <p className="home-count">
1077
  <span>Đang trong hang</span> <Tally n={inRoom} label={`${inRoom} anh em`} />
 
1097
  )}
1098
  </section>
1099
  <nav className="home-links" aria-label="Liên kết khác">
1100
+ <a className="home-tele" href="https://t.me/hangmu_online" target="_blank" rel="noopener noreferrer" aria-label="Tham gia group Telegram HangMu (mở tab mới)">
1101
+ <TelegramIcon /> Group Telegram
1102
  </a>
1103
  <PwaInstall className="home-install" short />
1104
  <PushButton className="home-push" />
1105
  </nav>
1106
+ <footer className="home-footer">
1107
+ Trang của người hâm mộ, không liên kết chính thức với Manchester United. ·
1108
+ <button type="button" className="legal-link" onClick={onShowLegal}>Điều khoản &amp; quyền riêng tư</button>
1109
+ </footer>
1110
  </main>
1111
  )
1112
  }
1113
+ function TelegramIcon() {
 
1114
  return (
1115
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M9.78 18.65l.28-4.23 7.68-6.92c.34-.31-.07-.46-.52-.19L7.74 13.3 3.64 12c-.88-.25-.89-.86.2-1.3l15.97-6.16c.73-.33 1.43.18 1.15 1.3l-2.72 12.81c-.19.91-.74 1.13-1.5.71L12.6 16.3l-1.99 1.93c-.23.23-.42.42-.83.42z"/></svg>
1116
  )
1117
  }
1118
 
1119
  /* =========================================================================
1120
+ NAME DIALOG
1121
  ========================================================================= */
1122
+ const NAME_MAX = 30
1123
+ function sanitizeName(s) {
1124
+ return Array.from(s.normalize('NFC')).filter((ch) => {
1125
+ const cp = ch.codePointAt(0)
1126
+ return !(cp < 32 || (cp >= 127 && cp < 160))
1127
+ }).join('').replace(/\s+/g, ' ').trim()
1128
+ }
1129
+ function NameDialog({ rename = false, initial = null, onCancel, onSubmit }) {
1130
+ const [name, setName] = React.useState(() => initial ? initial.name : (localStorage.getItem('hangmu.name') || ''))
1131
+ const [number, setNumber] = React.useState(() => initial ? String(initial.number ?? '') : String(localStorage.getItem('hangmu.number') || '').replace(/\D/g, '').slice(0, 2))
1132
+ const inputRef = React.useRef(null)
1133
+ const clean = sanitizeName(name)
1134
+ const len = Array.from(clean).length
1135
+ const valid = len >= 1 && len <= NAME_MAX
1136
+ React.useEffect(() => { inputRef.current?.focus(); inputRef.current?.select() }, [])
1137
+ const submit = (e) => {
1138
+ e.preventDefault()
1139
+ if (!valid) return
1140
+ localStorage.setItem('hangmu.name', clean)
1141
+ localStorage.setItem('hangmu.number', number)
1142
+ onSubmit(clean, number ? Number(number) : null)
1143
  }
1144
  return (
1145
+ <div className="name-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onCancel()}>
1146
+ <form className="name-dialog plaque" role="dialog" aria-modal="true" aria-labelledby="name-title" onKeyDown={(e) => e.key === 'Escape' && onCancel()} onSubmit={submit}>
1147
+ <p className="quiz-kicker" id="name-step">🏟️ Bước 1 · Sân trước cửa hang</p>
1148
+ <h2 id="name-title">{rename ? 'Đổi tên' : 'Anh em gọi bạn là gì?'}</h2>
1149
+ <label htmlFor="name-name" className="name-label">Tên hiện trên đầu nhân vật (không mạo danh, không phản cảm)</label>
1150
+ <input ref={inputRef} id="name-name" className="name-input" value={name} maxLength={60} autoComplete="nickname" enterKeyHint="go" spellCheck={false}
1151
+ onChange={(e) => setName(e.target.value)} />
1152
+ <p className={`name-count${len > NAME_MAX ? ' is-over' : ''}`} aria-live="polite">{len}/{NAME_MAX} ký tự</p>
1153
+ <div className="name-number-row">
1154
+ <div className="name-number-text">
1155
+ <label htmlFor="name-number" className="name-label">Số áo sau lưng</label>
1156
+ <p className="name-hint">1–99, để trống = áo trơn</p>
1157
+ </div>
1158
+ <div className="name-jersey" aria-hidden="true">
1159
+ <span className="name-jersey-num">{number || ''}</span>
1160
+ </div>
1161
+ <input id="name-number" className="name-input name-number" value={number}
1162
+ onChange={(e) => setNumber(e.target.value.replace(/\D/g, '').replace(/^0+/, '').slice(0, 2))}
1163
+ inputMode="numeric" pattern="[0-9]*" maxLength={2} autoComplete="off" enterKeyHint="go" placeholder="7" />
1164
  </div>
1165
+ <div className="name-actions">
1166
+ <button type="button" className="name-cancel carved-btn carved-btn--ghost" onClick={onCancel}>Huỷ</button>
1167
+ <button type="submit" className="home-enter carved-btn carved-btn--primary" disabled={!valid}>Vào hang</button>
1168
+ </div>
1169
+ </form>
1170
  </div>
1171
  )
1172
  }
1173
 
1174
  /* =========================================================================
1175
+ QUIZ DIALOG
1176
  ========================================================================= */
1177
+ function QuizDialog({ onDone, onCancel }) {
1178
+ const [step, setStep] = React.useState('loading')
1179
+ const [q, setQ] = React.useState(null)
1180
+ const [chosen, setChosen] = React.useState(null)
1181
+ const [res, setRes] = React.useState(null)
1182
+ const [error, setError] = React.useState('')
1183
+ React.useEffect(() => {
1184
+ let alive = true
1185
+ apiQuiz().then((d) => {
1186
+ if (alive && d.questions?.[0]) { setQ(d.questions[0]); setStep('answer') }
1187
+ else if (alive) setError('Không lấy được câu hỏi. Thử lại nhé.')
1188
+ }).catch(() => alive && setError('Không lấy được câu hỏi. Thử lại nhé.'))
1189
+ return () => { alive = false }
1190
+ }, [])
1191
+ const pick = async (qid, aid) => {
1192
+ if (chosen != null || step !== 'answer') return
1193
+ setChosen(aid)
1194
+ try {
1195
+ const data = await apiQuizAnswer(qid, aid)
1196
+ setRes(data); setStep('result')
1197
+ } catch {
1198
+ setChosen(null); setError('Không gửi được câu trả lời. Thử lại nhé.')
1199
+ }
1200
+ }
1201
+ const answerClass = (aid) => {
1202
+ let c = 'quiz-answer carved-btn'
1203
+ if (step === 'result') {
1204
+ if (aid === res?.correctAnswerId || (res?.correct && aid === chosen)) c += ' is-right'
1205
+ else if (aid === chosen) c += ' is-wrong'
1206
+ }
1207
+ return c
1208
+ }
1209
  return (
1210
+ <div className="name-backdrop" onMouseDown={(e) => e.target === e.currentTarget && step !== 'result' && onCancel()}>
1211
+ <div className="name-dialog quiz-dialog plaque" role="dialog" aria-modal="true" aria-labelledby="quiz-title" aria-busy={step === 'loading'} tabIndex={-1}>
1212
+ <p className="quiz-kicker" id="quiz-title">Câu hỏi vui trước khi vào hang</p>
1213
+ {step === 'loading' ? (
1214
+ <p className="quiz-loading" role="status">Đang lấy câu hỏi…</p>
1215
+ ) : (
1216
+ <>
1217
+ <h2 className="quiz-question">{q.q}</h2>
1218
+ {error && <p className="quiz-error" role="alert">{error}</p>}
1219
+ <div className="quiz-answers" role="group" aria-labelledby="quiz-title">
1220
+ {q.answers.map((a) => (
1221
+ <button key={a.id} type="button" className={answerClass(a.id)} disabled={step === 'result' || chosen != null} onClick={() => pick(q.id, a.id)}>
1222
+ {a.text}
1223
+ </button>
1224
+ ))}
1225
+ </div>
1226
+ </>
1227
+ )}
1228
+ {step === 'result' && (
1229
+ <>
1230
+ <p className={`quiz-result ${res.correct ? 'is-right' : 'is-wrong'}`} role="status">{res.message}</p>
1231
+ <div className="name-actions">
1232
+ <button type="button" className="home-enter carved-btn carved-btn--primary" onClick={onDone}>Vào hang</button>
1233
+ </div>
1234
+ </>
1235
+ )}
1236
+ {step !== 'result' && (
1237
+ <div className="name-actions">
1238
+ <button type="button" className="name-cancel carved-btn carved-btn--ghost" onClick={onCancel}>Huỷ</button>
1239
+ </div>
1240
+ )}
1241
  </div>
1242
  </div>
1243
  )
1244
  }
1245
 
1246
  /* =========================================================================
1247
+ LEGAL + CONSENT + DONATE
1248
  ========================================================================= */
1249
+ function LegalDialog({ onClose }) {
1250
+ const ref = React.useRef(null)
1251
+ React.useEffect(() => {
1252
+ ref.current?.focus()
1253
+ const onKey = (e) => { if (e.key === 'Escape') onClose() }
1254
+ document.addEventListener('keydown', onKey)
1255
+ return () => document.removeEventListener('keydown', onKey)
1256
+ }, [onClose])
1257
+ return (
1258
+ <div className="legal-backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
1259
+ <div ref={ref} className="legal-dialog" role="dialog" aria-modal="true" aria-labelledby="legal-title" tabIndex={-1}>
1260
+ <div className="legal-head">
1261
+ <h2 id="legal-title">Điều khoản &amp; Quyền riêng tư</h2>
1262
+ <button type="button" className="legal-close" aria-label="Đóng" onClick={onClose}>×</button>
1263
+ </div>
1264
+ <div className="legal-body">
1265
+ <h3>Trang của người hâm mộ</h3>
1266
+ <p>Hang MU là sân chơi phi lợi nhuận do fan tự làm, <b>không liên kết, không được tài trợ hay chứng thực</b> bởi Manchester United, Premier League hay bất kỳ tổ chức nào. Tên, logo CLB thuộc về chủ sở hữu tương ứng và chỉ dùng để thể hiện tình yêu với đội bóng.</p>
1267
+ <h3>Độ tuổi</h3>
1268
+ <ul><li>Hang MU dành cho người <b>từ 16 tuổi</b>. Dưới 16 tuổi chỉ dùng khi cha mẹ hoặc người giám hộ biết và đồng ý.</li></ul>
1269
+ <h3>Video, nhạc và hình ảnh</h3>
1270
+ <p>Màn hình lớn trong hang có 2 kênh: <b>Highlight MU</b> và <b>nhạc</b>. Tất cả được <b>nhúng qua trình phát chính thức của YouTube</b> — Hang MU không tải xuống, không lưu. Trang <b>không phát trực tiếp trận đấu</b>; tỷ số chỉ là thông tin kết quả. Ảnh huyền thoại lấy từ Wikimedia Commons theo giấy phép CC.</p>
1271
+ <h3>Chat, giọng nói và hành vi</h3>
1272
+ <p>Bạn <b>tự chịu trách nhiệm</b> về tên, tin nhắn và lời nói của mình. Khi dùng Hang MU, bạn đồng ý không chửi bới, xúc phạm, đăng nội dung vi phạm pháp luật, spam, tiết lộ thông tin cá nhân của người khác, ghi âm/ghi hình phát tán khi chưa đồng ý, đặt tên mạo danh hoặc phản cảm. Từ ngữ thô tục được lọc tự động. Tin nhắn chỉ hiện trực tiếp, <b>không được lưu lại</b>.</p>
1273
+ <p>Hang MU có quyền xoá nội dung, mời ra khỏi phòng / khỏi hang hoặc chặn người vi phạm mà không cần báo trước.</p>
1274
+ <h3>Dữ liệu chúng tôi xử lý</h3>
1275
+ <ul>
1276
+ <li><b>Tên và số áo</b>: hiện cho người trong hang. Máy chủ lưu kèm mã ngẫu nhiên trong <b>14 ngày</b> kể từ lần vào hang gần nhất để lần sau không phải nhập lại và được giữ chỗ ~30 giây khi rớt mạng; quá hạn thì tự xoá.</li>
1277
+ <li><b>Bảng phong thần</b>: máy chủ lưu tên + số trận thắng tuần này, hiện top 5 mỗi bảng. Tự xoá sau khoảng 8 ngày.</li>
1278
+ <li><b>Tin nhắn chat, tin nhắn riêng, vị trí nhân vật</b>: chuyển tiếp trực tiếp, không lưu.</li>
1279
+ <li><b>Cookie cần thiết</b> <code>hm_sid</code> (HttpOnly): chỉ chứa mã ngẫu nhiên để máy chủ nhận ra bạn.</li>
1280
+ <li><b>Cookie phân tích</b> (Google Analytics): <b>chỉ khi bạn đồng ý</b>.</li>
1281
+ </ul>
1282
+ <p>Hang MU không bán, không chia sẻ dữ liệu cá nhân, không dùng dữ liệu để quảng cáo.</p>
1283
+ <h3>Ủng hộ</h3>
1284
+ <p>Tiền ủng hộ là <b>tự nguyện</b>, dùng để trả chi phí máy chủ, không hoàn lại và không phải quyên góp từ thiện.</p>
1285
+ <p className="legal-updated">Cập nhật: 11/2026</p>
1286
+ </div>
1287
+ </div>
1288
+ </div>
1289
+ )
1290
+ }
1291
+ const CONSENT_KEY = 'hangmu.consent'
1292
+ function hasGACookies() {
1293
+ return document.cookie.split(';').some((c) => /^(_ga|_gid|_gat|_gcl)/.test(c.trim().split('=')[0]))
1294
+ }
1295
+ function getConsent() {
1296
+ const v = localStorage.getItem(CONSENT_KEY)
1297
+ return (v === 'yes' || v === 'no') ? v : null
1298
+ }
1299
+ function Consent({ onShowLegal }) {
1300
+ const [consent, setConsent] = React.useState(getConsent)
1301
+ React.useEffect(() => setConsent(getConsent()), [])
1302
+ if (consent === 'yes' || consent === 'no' || hasGACookies()) return null
1303
+ const set = (v) => { localStorage.setItem(CONSENT_KEY, v); if (v === 'yes') window.__hangmuLoadGtm && window.__hangmuLoadGtm(); setConsent(v) }
1304
  return (
1305
+ <div className="consent-banner" role="region" aria-label="Đồng ý cookie">
1306
+ <p>
1307
+ Hang MU muốn dùng cookie Google Analytics để đếm lượt truy cập (không quảng cáo).{' '}
1308
+ <button type="button" className="consent-link" onClick={onShowLegal}>Chi tiết</button>
1309
+ </p>
1310
+ <div className="consent-actions">
1311
+ <button type="button" className="consent-no" onClick={() => set('no')}>Từ chối</button>
1312
+ <button type="button" className="consent-yes" onClick={() => set('yes')}>Đồng ý</button>
1313
  </div>
1314
  </div>
1315
  )
1316
  }
1317
+ function Donate({ className = '' }) {
1318
+ const [open, setOpen] = React.useState(false)
1319
+ const [showNudge, setShowNudge] = React.useState(false)
1320
+ React.useEffect(() => {
1321
+ const delay = new URLSearchParams(window.location.search).has('donate') ? 3000 : 18000
1322
+ const t = setTimeout(() => { if (!document.hidden) setShowNudge(true) }, delay)
1323
+ return () => clearTimeout(t)
1324
+ }, [])
1325
+ return (
1326
+ <div className={`donate ${className}`}>
1327
+ {showNudge && !open && (
1328
+ <button type="button" className="donate-nudge" onClick={() => { setShowNudge(false); setOpen(true) }}>Ủng hộ cho sơ vơ ☕</button>
1329
+ )}
1330
+ {open && (
1331
+ <div className="donate-card" role="dialog" aria-label="Ủng hộ Hang MU">
1332
+ <p className="donate-title">Góp vào sơ vơ 🔥</p>
1333
+ <img className="donate-qr" src="/images/donate-qr.png" width="200" height="200" alt="Mã VietQR chuyển khoản ủng hộ" />
1334
+ <p className="donate-note">Quét bằng app ngân hàng bất kỳ</p>
1335
+ <p className="donate-note">Ủng hộ tự nguyện để trả tiền máy chủ · không hoàn lại</p>
1336
+ </div>
1337
+ )}
1338
+ <button type="button" className="donate-toggle" aria-expanded={open} onClick={() => { setShowNudge(false); setOpen(!open) }}>☕ Ủng hộ</button>
1339
+ </div>
1340
+ )
1341
+ }
1342
 
1343
  /* =========================================================================
1344
+ UPDATE NOTICE (version.json) — chỉ báo "Có bản mới" khi version thay đổi thật
1345
  ========================================================================= */
1346
+ function UpdateNotice() {
1347
+ const [state, setState] = React.useState(null)
1348
+ React.useEffect(() => {
1349
+ let alive = true
1350
+ let baseline = null
1351
+ const check = async () => {
1352
+ try {
1353
+ const r = await fetch('/version.json', { cache: 'no-store' })
1354
+ if (!r.ok) return
1355
+ const { id } = await r.json()
1356
+ if (!alive || !id) return
1357
+ if (baseline === null) { baseline = id; return }
1358
+ if (id !== baseline) setState({ available: true, seconds: 15, busy: false })
1359
+ } catch { }
1360
+ }
1361
+ const t = setTimeout(check, 8000)
1362
+ const iv = setInterval(check, 60000)
1363
+ return () => { alive = false; clearTimeout(t); clearInterval(iv) }
1364
+ }, [])
1365
+ React.useEffect(() => {
1366
+ if (!state?.available || state.busy) return
1367
+ const iv = setInterval(() => {
1368
+ setState((s) => {
1369
+ if (!s) return s
1370
+ const sec = s.seconds - 1
1371
+ if (sec <= 0) { window.location.reload(); return s }
1372
+ return { ...s, seconds: sec }
1373
+ })
1374
+ }, 1000)
1375
+ return () => clearInterval(iv)
1376
+ }, [state?.available, state?.busy])
1377
+ if (!state?.available) return null
1378
+ return (
1379
+ <div className="update-notice" role="status" aria-live="polite">
1380
+ <strong>Có bản mới</strong>
1381
+ <p>{state.busy ? 'Sẽ tự tải lại ngay khi bạn xong trận / cuộc trò chuyện / gõ chữ.' : `Tự tải lại sau ${state.seconds} giây — bạn vẫn giữ nguyên chỗ và nhân vật trong hang.`}</p>
1382
+ {!state.busy && <div className="update-notice-bar"><i style={{ transform: `scaleX(${state.seconds / 15})` }} /></div>}
1383
+ <button type="button" onClick={() => { setState({ ...state, busy: true }); setTimeout(() => window.location.reload(), 300) }}>Tải lại ngay</button>
1384
+ </div>
1385
+ )
1386
+ }
1387
 
1388
+ /* =========================================================================
1389
+ FPS BADGE
1390
+ ========================================================================= */
1391
+ function FpsBadge() {
1392
+ const ref = React.useRef(null)
1393
+ React.useEffect(() => {
1394
+ let frames = 0, time = 0, raf
1395
+ const loop = (t) => {
1396
+ const dt = t - time
1397
+ time = t
1398
+ frames++
1399
+ if (dt >= 1000) {
1400
+ const fps = Math.round((frames * 1000) / dt)
1401
+ frames = 0
1402
+ if (ref.current) {
1403
+ ref.current.textContent = `${fps} FPS`
1404
+ ref.current.dataset.level = fps >= 55 ? 'good' : (fps >= 35 ? 'ok' : 'bad')
1405
+ }
1406
+ }
1407
+ raf = requestAnimationFrame(loop)
1408
+ }
1409
+ raf = requestAnimationFrame(loop)
1410
+ return () => cancelAnimationFrame(raf)
1411
+ }, [])
1412
+ return <output ref={ref} id="fps-badge" className="fps-badge" aria-live="off">… FPS</output>
1413
+ }
1414
 
1415
+ /* =========================================================================
1416
+ CAVE SCREEN
1417
+ ========================================================================= */
1418
+ function Cave({ onLeave }) {
1419
+ const players = useGame((s) => s.players)
1420
+ const playerId = useGame((s) => s.playerId)
1421
+ const activity = useGame((s) => s.activity)
1422
+ const unstable = useGame((s) => s.unstable)
1423
+ const touch = ('ontouchstart' in window)
1424
+ const boardVideo = useGame((s) => s.boardVideo)
1425
+ const boardMusic = useGame((s) => s.boardMusic)
1426
+ const [channel] = React.useState(() => localStorage.getItem('hangmu.board.channel') || 'football')
1427
 
1428
+ return (
1429
+ <main className="cave" data-activity={activity || undefined}>
1430
+ <h1 className="visually-hidden">Trong Hang MU</h1>
1431
+ <div className="cave-scene" id="cave-canvas-wrap">
1432
+ <Canvas shadows camera={{ position: [0, 8, 45], fov: 55, near: 0.1, far: 200 }}
1433
+ gl={{ antialias: true, alpha: true, preserveDrawingBuffer: true }}
1434
+ onCreated={({ gl, scene }) => {
1435
+ gl.setClearColor(0x2a1408, 1)
1436
+ scene.fog = new THREE.Fog(0x2a1408, 55, 130)
1437
+ }}>
1438
+ <CaveScene />
1439
+ {[...players.entries()].map(([id, p]) => (
1440
+ <PlayerAvatar key={id} id={id} p={p} isLocal={id === playerId} />
1441
+ ))}
1442
+ <CameraRig />
1443
+ <Projector />
1444
+ <BoardProjector />
1445
+ </Canvas>
1446
+ </div>
1447
+ <NameTags />
1448
+ <header className="cave-bar">
1449
+ <div className="cave-bar-left">
1450
+ <button type="button" className="cave-leave" onClick={onLeave}>Ra hang</button>
1451
+ <SoundButton />
1452
+ <TvButton />
1453
+ <HelpButton />
1454
+ </div>
1455
+ <RoomBadge />
1456
+ <div className="cave-bar-right">
1457
+ <TelegramBtn />
1458
+ </div>
1459
+ </header>
1460
+ <BoardVideoOverlay videoIds={channel === 'football' ? boardVideo : boardMusic} channel={channel} />
1461
+ <GoalOverlay />
1462
+ <NoticeOverlay />
1463
+ <CelebrateButton touch={touch} />
1464
+ <ChatToggle touch={touch} />
1465
+ <InviteOverlay touch={touch} />
1466
+ <PollOverlay />
1467
+ <PunchButton touch={touch} />
1468
+ <PunchedOverlay />
1469
+ <RageLayer touch={touch} />
1470
+ <TalkLayer touch={touch} />
1471
+ <DuelLayer touch={touch} />
1472
+ <PenaltyLayer touch={touch} />
1473
+ <TugLayer touch={touch} />
1474
+ <BallLayer touch={touch} />
1475
+ <Movement touch={touch} />
1476
+ {touch && <Crosshair />}
1477
+ <ReconnectOverlay />
1478
+ {unstable && <p className="cave-net" role="alert">Mạng đang chập chờn, đang chờ kết nối lại… Người khác có thể tạm đứng yên.</p>}
1479
+ <Credits />
1480
+ <Donate className="cave-donate" nudge />
1481
+ <Scoreboard />
1482
+ <VoiceHall />
1483
+ </main>
1484
+ )
1485
+ }
1486
 
1487
+ /* =========================================================================
1488
+ BOARD VIDEO — CSS3D projection lên mặt phẳng 3D
1489
+ ========================================================================= */
1490
+ // Khớp chính xác với BOARD = { w:24, h:14, y:7.3, z:-47.5 } trong cave3d.js
1491
+ // (mặt phẳng bảng: x ∈ [-12,12], y ∈ [0.3,14.3], z = -47.5 + 0.55 ≈ -46.95)
1492
+ const BOARD_CORNERS = [
1493
+ [-12, 14.3, -46.95], [12, 14.3, -46.95],
1494
+ [12, 0.3, -46.95], [-12, 0.3, -46.95],
1495
+ ]
1496
+ const boardPx = { pts: null, ok: false }
1497
+ function BoardProjector() {
1498
+ const { camera, size } = useThree()
1499
+ const v = React.useMemo(() => [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()], [])
1500
+ useFrame(() => {
1501
+ const w = size.width, h = size.height
1502
+ const out = []
1503
+ let any = false
1504
+ for (let i = 0; i < 4; i++) {
1505
+ v[i].set(...BOARD_CORNERS[i]).project(camera)
1506
+ const z = v[i].z
1507
+ if (z < 1 && z > -1) any = true
1508
+ out.push(((v[i].x * 0.5 + 0.5) * w) / 1, ((-v[i].y * 0.5 + 0.5) * h) / 1)
1509
+ }
1510
+ boardPx.pts = out
1511
+ boardPx.ok = any
1512
+ })
1513
+ return null
1514
+ }
1515
+ function quadMatrix(x0, y0, x1, y1, x2, y2, x3, y3) {
1516
+ const A = [x0, y0, x1, y1, x2, y2, x3, y3]
1517
+ const sx = A[0], sy = A[1]
1518
+ const dx1 = A[2] - sx, dy1 = A[3] - sy
1519
+ const dx2 = A[4] - sx, dy2 = A[5] - sy
1520
+ const dx3 = A[6] - sx, dy3 = A[7] - sy
1521
+ const u = (dx1 * dy3 - dy1 * dx3) / (dx1 * dy2 - dy1 * dx2)
1522
+ const v = (dx1 * dx3 + dy1 * dy3) / (dx1 * dx2 + dy1 * dy2)
1523
+ const a = x1 - x0 + u * (x3 - x1)
1524
+ const b = x2 - x0 + u * (x3 - x2)
1525
+ const c = x3
1526
+ const d = y1 - y0 + u * (y3 - y1)
1527
+ const e = y2 - y0 + u * (y3 - y2)
1528
+ const f = y3
1529
+ const g = u
1530
+ return `matrix3d(${a},${d},0,${g}, ${b},${e},0,0, 0,0,1,0, ${c},${f},0,1)`
1531
+ }
1532
+ function BoardVideoOverlay({ videoIds, channel }) {
1533
+ const ref = React.useRef(null)
1534
+ const [ids, setIds] = React.useState(videoIds)
1535
+ const [thumbIdx, setThumbIdx] = React.useState(0)
1536
+ const idxRef = React.useRef(0)
1537
+ React.useEffect(() => { if (videoIds && videoIds.length) setIds(videoIds) }, [videoIds?.join(',')])
1538
+ React.useEffect(() => {
1539
+ // nếu WS chưa gửi 'board' kịp — tự lấy playlist từ /api/board để màn hình không trống
1540
+ if (ids && ids.length) return
1541
+ let alive = true
1542
+ fetch('/api/board', { cache: 'no-store' })
1543
+ .then((r) => r.ok ? r.json() : Promise.reject(new Error('board ' + r.status)))
1544
+ .then((d) => { if (alive && d) setIds(channel === 'football' ? (d.videos || null) : (d.music || null)) })
1545
+ .catch(() => {})
1546
+ return () => { alive = false }
1547
+ }, [ids?.join(',')])
1548
+ const useIds = ids || videoIds
1549
+ const n = useIds && useIds.length ? useIds.length : 0
1550
  React.useEffect(() => {
1551
+ if (!n) return
1552
+ idxRef.current = 0; setThumbIdx(0)
1553
  const iv = setInterval(() => {
1554
+ idxRef.current = (idxRef.current + 1) % n
1555
+ setThumbIdx(idxRef.current)
1556
+ }, 8000)
 
 
 
1557
  return () => clearInterval(iv)
1558
+ }, [useIds?.join(','), n])
1559
+ React.useEffect(() => {
1560
+ /* MÀN HÌNH LỚN luôn có nội dung — không bao giờ trống (fix v29):
1561
+ - Poster MU động là LỚP NỀN, luôn hiện nếu không có video/thumb nào lên.
1562
+ - Thumbnail YouTube (i.ytimg.com) nằm TRÊN poster, nền trong su���t
1563
+ (nếu ảnh không tải được thì poster vẫn hiện — không bao giờ đen).
1564
+ - iframe video nằm TRÊN CÙNG (z-index:5). Nếu YT phát được → video che
1565
+ hết. Nếu YT bị chặn → iframe ẩn (display:none) và thumbnail/poster lộ ra.
1566
+ Phát hiện YT bị chặn: theo dõi 'load' + khoảng 6s sau; nếu trang embed
1567
+ không có phần tử #player rõ ràng (YT bị chặn trả trang lỗi/thô) thì ẩn. */
1568
+ if (!useIds || !useIds.length) return
1569
+ const wrap = ref.current
1570
+ if (!wrap) return
1571
+ let cancelled = false
1572
+ let thumbFailed = false
1573
+ // Tầng 1 — poster (nền, trong suốt nếu có thumbnail bên trên)
1574
+ const poster = document.createElement('div')
1575
+ poster.style.cssText = 'position:absolute;inset:0;z-index:0;display:flex;flex-direction:column;align-items:center;justify-content:center;background:radial-gradient(circle at 50% 30%, #5c0e1b, #1b0508);color:#ffd76a;font:700 20px/1.3 "Be Vietnam Pro",sans-serif;text-align:center;padding:6px;gap:4px'
1576
+ poster.innerHTML = '<span style="font-size:36px;line-height:1">🔴⚪</span><span>BẢNG TIN HANG MU</span><span style="font-size:12px;color:#f0d9a8">Glory Glory Man United</span>'
1577
+ wrap.appendChild(poster)
1578
+ // Tầng 2 — thumbnail hiện tại (nền TRONG SUỐT để không che poster khi ảnh lỗi)
1579
+ const thumb = document.createElement('div')
1580
+ thumb.style.cssText = 'position:absolute;inset:0;z-index:2;background:transparent;overflow:hidden;display:block;opacity:0'
1581
+ const img = document.createElement('img')
1582
+ img.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:.95'
1583
+ img.alt = ''
1584
+ img.onerror = () => { thumbFailed = true; if (!cancelled) thumb.style.opacity = '0' }
1585
+ img.onload = () => { if (!cancelled) thumb.style.opacity = '1' }
1586
+ const cap = document.createElement('div')
1587
+ cap.style.cssText = 'position:absolute;left:0;right:0;bottom:0;z-index:2;padding:5px 8px 6px;background:linear-gradient(180deg,transparent,rgba(0,0,0,.82));color:#ffd76a;font:700 13px/1.2 "Be Vietnam Pro",sans-serif;text-align:left;display:flex;align-items:center;gap:6px'
1588
+ cap.innerHTML = '<span style="background:#ff0202;color:#fff;border-radius:3px;padding:1px 5px;font-size:10px;font-weight:800">YOUTUBE</span><span style="color:#fff">Glory Glory Man United</span>'
1589
+ thumb.appendChild(img)
1590
+ thumb.appendChild(cap)
1591
+ const badge = document.createElement('div')
1592
+ badge.style.cssText = 'position:absolute;left:6px;top:5px;z-index:3;background:rgba(0,0,0,.55);color:#fff;border-radius:999px;padding:2px 8px;font:800 12px/1.2 "Be Vietnam Pro",sans-serif'
1593
+ badge.textContent = channel === 'football' ? '⚽ HIGHLIGHT MU' : '🎵 NHẠC MU'
1594
+ thumb.appendChild(badge)
1595
+ const setThumb = (i) => {
1596
+ const id = useIds[i % useIds.length]
1597
+ img.src = `https://i.ytimg.com/vi/${id}/hqdefault.jpg`
1598
+ // làm nổi nội dung mới (ảnh load xong sẽ tự opacity=1)
1599
+ img.style.transition = 'opacity .4s'
1600
+ img.style.opacity = '0.3'
1601
+ requestAnimationFrame(() => { requestAnimationFrame(() => { if (!cancelled && img.complete) img.style.opacity = '.95' }) })
1602
+ }
1603
+ setThumb(0)
1604
+ wrap.appendChild(thumb)
1605
+ // Tầng 3 — iframe video (trên cùng). Ẩn nếu YT bị chặn.
1606
+ const iframe = document.createElement('iframe')
1607
+ iframe.setAttribute('allow', 'autoplay; encrypted-media; picture-in-picture; fullscreen')
1608
+ iframe.setAttribute('allowfullscreen', '')
1609
+ iframe.setAttribute('referrerpolicy', 'no-referrer-when-downgrade')
1610
+ iframe.setAttribute('title', 'MU highlight')
1611
+ iframe.style.cssText = 'position:absolute;inset:0;z-index:5;width:100%;height:100%;border:0;opacity:0.999'
1612
+ iframe.src = `https://www.youtube-nocookie.com/embed/${useIds[0]}?autoplay=1&mute=1&controls=0&disablekb=1&fs=0&iv_load_policy=3&rel=0&playsinline=1&loop=1&playlist=${useIds[0]}&enablejsapi=1`
1613
+ wrap.appendChild(iframe)
1614
+ // Phát hiện YT có phản hồi hay không bằng giao thức postMessage của YouTube
1615
+ // IFrame API (an toàn cross-origin — KHÔNG đọc contentDocument vì SecurityError).
1616
+ // Nếu nhận được sự kiện onReady/infoDelivery → player sống → giữ iframe hiển thị.
1617
+ // Nếu YT bị chặn (VN) → không có onReady → ẩn iframe để thumbnail/poster hiện.
1618
+ let ytAlive = false
1619
+ const probe = () => {
1620
+ if (cancelled) return
1621
+ try { if (iframe.contentWindow) iframe.contentWindow.postMessage('{"event":"listening","id":"hangmu-probe"}', '*') } catch (e) {}
1622
+ }
1623
+ const onMsg = (ev) => {
1624
+ if (!ev || ev.source !== iframe.contentWindow) return
1625
+ let d = null
1626
+ try { d = JSON.parse(typeof ev.data === 'string' ? ev.data : '') } catch (e) { return }
1627
+ if (d && (d.event === 'onReady' || d.event === 'infoDelivery')) {
1628
+ ytAlive = true
1629
+ if (!cancelled) iframe.style.display = ''
1630
+ }
1631
+ }
1632
+ window.addEventListener('message', onMsg)
1633
+ const syncVis = () => { if (!cancelled) iframe.style.display = ytAlive ? '' : 'none' }
1634
+ const probeSync = () => { probe(); setTimeout(syncVis, 1200) }
1635
+ iframe.addEventListener('load', () => { setTimeout(probeSync, 300) })
1636
+ const t1 = setTimeout(probeSync, 500)
1637
+ const t2 = setTimeout(probeSync, 2000)
1638
+ const t3 = setTimeout(() => { if (!cancelled && !ytAlive) iframe.style.display = 'none' }, 6000)
1639
+ // Cứ 10s thăm lại: nếu YT hồi phục thì hiện lại iframe
1640
+ const iv = setInterval(probeSync, 10000)
1641
+ // Hiển thị ngay khi board thấy được (bỏ phụ thuộc YT.Player)
1642
+ try { window.dispatchEvent(new CustomEvent('hangmu-board-ready', { detail: { videoIds: useIds, iframe } })) } catch {}
1643
+ // Cập nhật thumbnail theo vòng quay
1644
+ wrap._setThumb = setThumb
1645
+ return () => { cancelled = true; clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); clearInterval(iv); window.removeEventListener('message', onMsg); try { wrap.innerHTML = '' } catch {} }
1646
+ }, [useIds?.join(',')])
1647
+ React.useEffect(() => {
1648
+ if (ref.current && ref.current._setThumb && n) ref.current._setThumb(thumbIdx)
1649
+ }, [thumbIdx, n])
1650
+ React.useEffect(() => {
1651
+ const el = ref.current
1652
+ if (!el) return
1653
+ let raf
1654
+ const loop = () => {
1655
+ if (boardPx.ok && boardPx.pts) {
1656
+ const [x0, y0, x1, y1, x2, y2, x3, y3] = boardPx.pts
1657
+ el.style.display = 'block'
1658
+ // Kích thước theo hình chiếu của board 3D (24×14) — iframe giữ đúng tỷ lệ
1659
+ const bw = Math.hypot(x1 - x0, y1 - y0)
1660
+ const bh = Math.hypot(x3 - x0, y3 - y0)
1661
+ el.style.width = `${bw || 19.56}px`
1662
+ el.style.height = `${bh || 11}px`
1663
+ el.style.transform = quadMatrix(x0, y0, x1, y1, x2, y2, x3, y3)
1664
+ } else {
1665
+ el.style.display = 'none'
1666
+ }
1667
+ raf = requestAnimationFrame(loop)
1668
+ }
1669
+ raf = requestAnimationFrame(loop)
1670
+ return () => cancelAnimationFrame(raf)
1671
+ }, [])
1672
+ if (!useIds || !useIds.length) return null
1673
+ return (
1674
+ <div className="board-video" ref={ref}
1675
+ style={{ position: 'absolute', left: 0, top: 0, transformOrigin: '0 0', width: '19.56px', height: '11px', overflow: 'hidden', pointerEvents: 'none', zIndex: 2, display: 'none' }} />
1676
+ )
1677
+ }
1678
+ function NoticeOverlay() {
1679
+ const notice = useNotice()
1680
+ if (!notice.notice) return null
1681
+ return (
1682
+ <div className="notice" role="status" aria-live="polite" key={notice.notice.seq || 0}>
1683
+ <p className="notice-main"><span className="notice-icon">🔔</span> {notice.notice.text}</p>
1684
+ <p className="notice-sub">Đang chạy phía dưới — bấm để xem</p>
1685
+ </div>
1686
+ )
1687
+ }
1688
+
1689
+ /* =========================================================================
1690
+ PHÒNG XẢ GIẬN (rage room) — ném cà chua vào hình nộm quanh hố lửa
1691
+ ========================================================================= */
1692
+ const RAGE_DUMMY_POS = [
1693
+ { x: 9.4, z: -3.7 }, { x: 2.0, z: -11.5 }, { x: -12.0, z: -4.6 }, { x: -6.6, z: 8.1 },
1694
+ ]
1695
+ const RAGE_NAMES = ['Hậu vệ', 'Tiền vệ', 'Tiền đạo', 'HLV']
1696
+ function RageLayer({ touch }) {
1697
+ const rage = useRage()
1698
+ const players = useGame((s) => s.players)
1699
+ const playerId = useGame((s) => s.playerId)
1700
+ const me = players.get(playerId)
1701
+ const [near, setNear] = React.useState(-1)
1702
+ const [power, setPower] = React.useState(0)
1703
+ const [charging, setCharging] = React.useState(false)
1704
+ const [score, setScore] = React.useState({ hits: 0, total: 0 })
1705
+ const [slot, setSlot] = React.useState(0)
1706
+ const active = rage.active
1707
+ const ivRef = React.useRef(null)
1708
 
1709
  React.useEffect(() => {
1710
+ if (active) return
1711
+ const id = setInterval(() => {
1712
+ if (!me || !me.pos) return
1713
+ let found = -1
1714
+ for (let i = 0; i < RAGE_DUMMY_POS.length; i++) {
1715
+ const dx = me.pos.x - RAGE_DUMMY_POS[i].x, dz = me.pos.z - RAGE_DUMMY_POS[i].z
1716
+ if (dx * dx + dz * dz < 8 * 8) { found = i; break }
1717
+ }
1718
+ setNear(found)
1719
+ }, 400)
1720
+ return () => clearInterval(id)
1721
+ }, [active, me && me.pos && me.pos.x, me && me.pos && me.pos.z])
1722
 
1723
+ React.useEffect(() => {
1724
+ const down = (e) => {
1725
+ if (e.code === 'KeyE' && near >= 0 && !active) {
1726
+ rage.set({ active: true })
1727
+ if (document.exitPointerLock) document.exitPointerLock()
1728
+ }
1729
+ if (e.code === 'Escape' && active) {
1730
+ rage.set({ active: false }); setPower(0); setCharging(false)
1731
+ }
1732
+ }
1733
+ window.addEventListener('keydown', down)
1734
+ return () => window.removeEventListener('keydown', down)
1735
+ }, [near, active])
1736
+
1737
+ const start = () => {
1738
+ if (charging) return
1739
+ setCharging(true); setPower(0)
1740
+ ivRef.current = setInterval(() => setPower((p) => Math.min(100, p + 7)), 60)
1741
+ }
1742
+ const release = () => {
1743
+ if (ivRef.current) clearInterval(ivRef.current)
1744
+ const p = power
1745
+ setCharging(false); setPower(0)
1746
+ if (active && p > 0) {
1747
+ const hit = p >= 35 && p <= 95
1748
+ setScore((s) => ({ hits: s.hits + (hit ? 1 : 0), total: s.total + 1 }))
1749
+ const el = document.querySelector('.rage-cross')
1750
+ if (el) { el.style.outlineColor = hit ? '#3fb36b' : '#ff4a3a'; setTimeout(() => { el.style.outlineColor = '' }, 350) }
1751
+ }
1752
+ }
1753
 
1754
+ if (!active && near < 0) return null
1755
  return (
1756
+ <>
1757
+ {!active && near >= 0 && (
1758
+ <div className="rage-prompt" role="status">
1759
+ <span className="rage-prompt-title">🍅 Phòng xả giận</span>
1760
+ <span className="rage-prompt-sub">ném cà chua vào hình nộm</span>
1761
+ {touch ? (
1762
+ <button type="button" className="rage-enter rage-prompt-act" onClick={() => rage.set({ active: true })}>Vào phòng</button>
1763
+ ) : (
1764
+ <span className="rage-prompt-act"><kbd>E</kbd> để vào</span>
1765
+ )}
1766
+ </div>
1767
  )}
1768
+ {active && (
1769
+ <div className="rage" data-activity="rage">
1770
+ <div className="rage-cross" style={{ left: '50%', top: '50%', position: 'absolute', transform: 'translate(-50%,-50%)', width: 36, height: 36, outline: '3px solid rgba(255,255,255,0.75)', borderRadius: '50%' }} />
1771
+ <button type="button" className="rage-exit" onClick={() => { rage.set({ active: false }); setPower(0); setCharging(false) }}>✕ Rời phòng (Esc)</button>
1772
+ <div className="rage-counter" role="status">
1773
+ 🍅 {score.hits}/{score.total} trúng
1774
+ <span style={{ opacity: 0.8, fontWeight: 400 }}> · nộm: {RAGE_NAMES[slot]}</span>
 
 
 
 
 
 
 
 
 
 
 
 
1775
  </div>
1776
+ <div className="rage-picker">
1777
+ <div className="rage-picker-head">
1778
+ <div>
1779
+ <h2>Biệt danh cho hình nộm</h2>
1780
+ <p>Chọn mục tiêu — nộm đang được highlight trong hang</p>
1781
+ </div>
1782
+ </div>
1783
+ <div className="rage-slots">
1784
+ {RAGE_NAMES.map((n, r) => (
1785
+ <button key={r} type="button" className={'rage-slot' + (slot === r ? ' is-on' : '')} onClick={() => setSlot(r)}>
1786
+ {r + 1}. {n}
1787
+ </button>
1788
+ ))}
1789
+ </div>
1790
+ <button type="button" className="rage-chip rage-random" onClick={() => setSlot(Math.floor(Math.random() * RAGE_NAMES.length))}>🎭 Ngẫu nhiên</button>
1791
+ <p style={{ opacity: 0.7, fontSize: 12, marginTop: 8 }}>Giữ / chạm để lấy lực, thả để ném 🍅 — lực 35–95% là trúng.</p>
1792
+ </div>
1793
+ <div className="rage-disclaimer" data-on={power > 0 || undefined} style={{ position: 'absolute', bottom: 96, left: '50%', transform: 'translateX(-50%)', textAlign: 'center', color: '#fff6ec', background: 'rgba(12,8,6,0.85)', padding: '10px 18px', borderRadius: 12, border: '1px solid #ecd08c66', maxWidth: 'min(420px, calc(100vw - 32px))' }}>
1794
+ {power > 0 ? '🍅 Lực ' + power + '%' + (power >= 35 && power <= 95 ? ' — thả để ném!' : ' — hơi non/già!') : 'Giữ / chạm để lấy l���c, thả để ném'}
1795
+ <div style={{ height: 6, background: '#0009', borderRadius: 3, marginTop: 8, overflow: 'hidden' }}>
1796
+ <div style={{ width: power + '%', height: '100%', background: power >= 35 && power <= 95 ? '#3fb36b' : '#ff4a3a', transition: 'width 60ms linear' }} />
1797
+ </div>
1798
+ </div>
1799
+ <button
1800
+ type="button"
1801
+ className="rage-throw"
1802
+ style={{ position: 'absolute', bottom: 24, left: '50%', transform: 'translateX(-50%)', color: '#fff4e6', background: 'linear-gradient(180deg,#ff4a3a,#c8102e)', border: '2px solid #ffd76a', borderRadius: 999, padding: '14px 32px', fontWeight: 800, fontSize: 16, cursor: 'pointer', boxShadow: '0 6px 16px #000a' }}
1803
+ onPointerDown={start}
1804
+ onPointerUp={release}
1805
+ onPointerLeave={release}
1806
+ >🍅 NÉM!</button>
1807
  </div>
1808
  )}
1809
+ </>
 
 
 
 
1810
  )
1811
  }
1812
 
1813
  /* =========================================================================
1814
+ MINIGAME LAYERS
1815
  ========================================================================= */
1816
+ function TalkLayer({ touch }) {
1817
+ const talk = useTalk()
1818
+ const chat = useChat()
1819
+ const [input, setInput] = React.useState('')
1820
+ const [confirm, setConfirm] = React.useState(false)
1821
+ const endRef = React.useRef(null)
1822
+ const conv = talk.conv
1823
+ React.useEffect(() => { endRef.current?.scrollIntoView({ behavior: 'smooth' }) }, [conv?.msgs?.length])
1824
+ if (!conv) return null
1825
+ const peer = conv.peer
1826
+ const msgs = conv.msgs || []
1827
+ const send = (e) => {
1828
  e.preventDefault()
1829
+ if (!input.trim()) return
1830
+ Net.dm(peer, input.trim())
1831
+ setInput('')
 
1832
  }
1833
  return (
1834
+ <div className="talk-overlay">
1835
+ <div className="talk-box slab">
1836
+ <div className="talk-head">
1837
+ <span className="talk-who">💬 Giao lưu mồm với {chat.dms[peer]?.name || 'bạn'}</span>
1838
+ <button type="button" className="talk-close" onClick={() => { if (msgs.length) setConfirm(true); else Net.inviteAnswer(conv.inviteId, false) }}>×</button>
1839
+ </div>
1840
+ <div className="talk-msgs">
1841
+ {msgs.map((m, i) => (
1842
+ <div key={i} className={`talk-msg${m.mine ? ' is-mine' : ''}`}>
1843
+ <span className="talk-who">{m.mine ? 'Bạn' : (chat.dms[peer]?.name || '')}:</span> {m.text}
1844
+ </div>
1845
+ ))}
1846
+ <div ref={endRef} />
1847
+ </div>
1848
+ <form className="talk-form" onSubmit={send}>
1849
+ <input className="talk-input" value={input} placeholder="Nhắn riêng…" onChange={(e) => setInput(e.target.value)} maxLength={400} />
1850
+ <button type="submit" className="talk-btn is-ok">Gửi</button>
1851
+ </form>
1852
+ </div>
1853
+ {confirm && (
1854
+ <div className="talk-confirm">
1855
+ <p className="talk-confirm-text">Kết thúc cuộc giao lưu mồm?</p>
1856
+ <div className="talk-confirm-acts">
1857
+ <button type="button" className="talk-btn" onClick={() => setConfirm(false)}>Tiếp tục</button>
1858
+ <button type="button" className="talk-btn is-danger" onClick={() => { Net.send({ type: 'talk_end' }); useGame.getState().talk.set({ conv: null }); useGame.getState().set({ activity: null }) }}>Kết thúc</button>
1859
+ </div>
1860
+ </div>
1861
+ )}
1862
  </div>
1863
  )
1864
  }
1865
+ function DuelLayer({ touch }) {
1866
+ const duel = useDuel()
1867
+ const game = duel.game
 
 
 
1868
  const playerId = useGame((s) => s.playerId)
1869
+ const [blocking, setBlocking] = React.useState(false)
1870
+ const [flash, setFlash] = React.useState(0)
1871
+ if (!game) return null
1872
+ const meFirst = game.p1 === playerId
1873
+ const myHp = meFirst ? game.hp1 : game.hp2
1874
+ const oppHp = meFirst ? game.hp2 : game.hp1
1875
+ const left = Math.max(0, Math.ceil((game.until - Date.now() / 1000)))
1876
+ const punch = () => { Net.duelAction('punch', blocking); setFlash((f) => f + 1) }
1877
+ const toggleBlock = () => { const b = !blocking; setBlocking(b); Net.duelAction('block', b) }
1878
  return (
1879
+ <div className="duel-rank is-collapsed">
1880
+ <div className="duel-rank-head">
1881
+ <div>
1882
+ <h3 className="duel-rank-title">🥊 Giao lưu võ thuật</h3>
1883
+ <p className="duel-rank-sub">{left}s còn lại · tay trái đỡ, tay phải đấm</p>
1884
+ </div>
1885
+ </div>
1886
+ <div className="duel-rank-board">
1887
+ <div className="duel-rank-row is-me"><span className="duel-rank-pos">Bạn</span><span className="duel-rank-name">❤️ {myHp}</span><span className="duel-rank-wins">VS</span></div>
1888
+ <div className="duel-rank-row"><span className="duel-rank-pos">Đối thủ</span><span className="duel-rank-name">❤️ {oppHp}</span><span className="duel-rank-wins">{game.p1 === playerId ? 'p2' : 'p1'}</span></div>
1889
+ </div>
1890
+ <div className="duel-rank-acts">
1891
+ <button type="button" className={`talk-btn${blocking ? ' is-ok' : ''}`} onClick={toggleBlock}>🛡️ Đỡ (trái)</button>
1892
+ <button type="button" className="talk-btn is-danger" onClick={punch}>👊 Đấm (phải)</button>
1893
+ </div>
1894
+ {flash > 0 && <div key={flash} className="cave-punch-flash" />}
1895
+ </div>
1896
+ )
1897
+ }
1898
+ function PenaltyLayer({ touch }) {
1899
+ const penalty = usePenalty()
1900
+ const game = penalty.game
1901
+ const playerId = useGame((s) => s.playerId)
1902
+ const [side, setSide] = React.useState(null)
1903
+ if (!game) return null
1904
+ const meFirst = game.p1 === playerId
1905
+ const myScore = meFirst ? game.s1 : game.s2
1906
+ const oppScore = meFirst ? game.s2 : game.s1
1907
+ const shooting = (game.turn === playerId)
1908
+ const pick = (s) => { if (!side) { setSide(s); Net.penaltyPick(s) } }
1909
+ return (
1910
+ <div className="penalty-overlay">
1911
+ <div className="penalty-card slab">
1912
+ <h3 className="penalty-title">⚽ Sút luân lưu</h3>
1913
+ <div className="penalty-score">
1914
+ <span>Bạn {myScore}</span><span>–</span><span>{oppScore} Đối thủ</span>
1915
+ </div>
1916
+ <p className="penalty-hint">{shooting ? 'Bạn sút — chọn hướng!' : 'Bạn bắt — chọn hướng!'}</p>
1917
+ {!side ? (
1918
+ <div className="penalty-choices">
1919
+ {['L', 'C', 'R'].map((s) => (
1920
+ <button key={s} type="button" className="penalty-choice" onClick={() => pick(s)}>
1921
+ {s === 'L' ? '⬅️ Trái' : s === 'C' ? '🎯 Giữa' : 'Phải ➡️'}
1922
+ </button>
1923
+ ))}
1924
+ </div>
1925
+ ) : (
1926
+ <p className="penalty-wait">Đã chọn — chờ đối thủ…</p>
1927
+ )}
1928
+ {penalty.last && (
1929
+ <p className={`penalty-last ${penalty.last.scored ? 'is-ok' : 'is-danger'}`}>
1930
+ {penalty.last.scored ? '⚽ VÀO!' : '❌ Cản phá!'} (lượt {penalty.last.round})
1931
+ </p>
1932
+ )}
1933
+ </div>
1934
+ </div>
1935
  )
1936
  }
1937
+ function TugLayer({ touch }) {
1938
+ const tug = useTug()
1939
+ const game = tug.game
1940
+ const playerId = useGame((s) => s.playerId)
1941
+ const [combo, setCombo] = React.useState(0)
1942
+ if (!game) return null
1943
+ const meFirst = game.p1 === playerId
1944
+ const pos = game.pos || 0
1945
+ const pull = (power) => { Net.tugPull(power); setCombo((c) => c + 1) }
1946
+ return (
1947
+ <div className="tug" data-activity="tug">
1948
+ <div className="tug-top">
1949
+ <div className="tug-team is-white"><b>Bạn {combo > 0 ? `🔥 x${combo}` : ''}</b></div>
1950
+ <div className="tug-timer">💪 KÉO CO</div>
1951
+ <div className="tug-team"><b>Đối thủ</b></div>
1952
+ </div>
1953
+ <div className="tug-meter-box">
1954
+ <div className="tug-meter">
1955
+ <div className="tug-count" style={{ left: `${50 + pos / 2}%` }}>●</div>
1956
+ </div>
1957
+ </div>
1958
+ <div className="tug-ctrl">
1959
+ <button type="button" className="tug-btn" onPointerDown={() => pull(2.5)} onPointerUp={() => pull(0)}>💪 KÉO!</button>
1960
+ </div>
1961
+ </div>
1962
+ )
1963
+ }
1964
+ function BallLayer({ touch }) {
1965
+ const ball = useBall()
1966
+ const game = ball.game
1967
+ if (!game) return null
1968
+ const holder = game.holder
1969
+ return (
1970
+ <div className="ball">
1971
+ <div className="ball-top">
1972
+ <div className="ball-timer">👑 GIỮ BÓNG</div>
1973
+ </div>
1974
+ <div className="ball-board">
1975
+ <p className="ball-banner">Người giữ: <strong>{holder ? game.holderName : '— chưa ai —'}</strong></p>
1976
+ </div>
1977
+ <div className="ball-ctrl">
1978
+ <button type="button" className="ball-btn" onClick={() => Net.ballClaim()}>👑 Nhận bóng</button>
1979
+ <button type="button" className="ball-btn is-steal" onClick={() => Net.ballSteal()}>⚡ Cướp bóng</button>
1980
+ </div>
1981
+ </div>
1982
+ )
1983
+ }
1984
+
1985
+ /* =========================================================================
1986
+ ERROR BOUNDARY — chống màn hình đen
1987
+ ========================================================================= */
1988
+ class CaveErrorBoundary extends React.Component {
1989
+ constructor(props) { super(props); this.state = { err: null } }
1990
+ static getDerivedStateFromError(err) { return { err } }
1991
+ componentDidCatch(err, info) {
1992
+ try {
1993
+ fetch('/api/log', { method: 'POST', headers: { 'Content-Type': 'application/json' },
1994
+ body: JSON.stringify({ kind: 'react', msg: String((err && err.message) || err).slice(0, 600),
1995
+ stack: String((err && err.stack) || '').slice(0, 2500),
1996
+ info: String((info && info.componentStack) || '').slice(0, 2500), href: location.href }) }).catch(() => {})
1997
+ } catch {}
1998
+ }
1999
+ render() {
2000
+ if (this.state.err) {
2001
+ return (
2002
+ <div style={{ position: 'fixed', inset: 0, zIndex: 99999, display: 'grid', placeItems: 'center',
2003
+ background: '#120b08', color: '#f3e7d8', fontFamily: 'system-ui, sans-serif', padding: 24, textAlign: 'center' }}>
2004
+ <div>
2005
+ <p style={{ fontSize: 28, fontWeight: 800, margin: '0 0 8px' }}>Có lỗi xảy ra 🛠️</p>
2006
+ <p style={{ opacity: 0.85, wordBreak: 'break-word', maxWidth: 640 }}>
2007
+ {String((this.state.err && this.state.err.message) || this.state.err)}
2008
+ </p>
2009
+ <button onClick={() => location.reload()} style={{ marginTop: 14, padding: '10px 24px',
2010
+ background: '#c8102e', color: '#fff', border: 0, borderRadius: 8, fontSize: 16, cursor: 'pointer' }}>
2011
+ Tải lại
2012
+ </button>
2013
+ </div>
2014
+ </div>
2015
+ )
2016
+ }
2017
+ return this.props.children
2018
+ }
2019
+ }
2020
+ window.addEventListener('error', (e) => {
2021
+ try {
2022
+ fetch('/api/log', { method: 'POST', headers: { 'Content-Type': 'application/json' },
2023
+ body: JSON.stringify({ kind: 'window', msg: String(e.message || '').slice(0, 600),
2024
+ stack: String((e.error && e.error.stack) || '').slice(0, 2500), href: location.href }) }).catch(() => {})
2025
+ } catch {}
2026
+ })
2027
+ window.addEventListener('unhandledrejection', (e) => {
2028
+ try {
2029
+ fetch('/api/log', { method: 'POST', headers: { 'Content-Type': 'application/json' },
2030
+ body: JSON.stringify({ kind: 'promise', msg: String((e.reason && e.reason.message) || e.reason || '').slice(0, 600), href: location.href }) }).catch(() => {})
2031
+ } catch {}
2032
+ })
2033
 
2034
  /* =========================================================================
2035
+ APP ROOT
2036
  ========================================================================= */
2037
+ function App() {
2038
+ const phase = useGame((s) => s.phase)
2039
+ const me = useGame((s) => s.me)
2040
+ const queuePos = useGame((s) => s.queuePos)
2041
+ const retryIn = useGame((s) => s.retryIn)
2042
+ const [dialog, setDialog] = React.useState(null)
2043
+ const [showLegal, setShowLegal] = React.useState(false)
2044
+ const [route, setRoute] = React.useState(window.location.hash === '#/hang' ? 'cave' : 'home')
2045
+ const namedOnce = React.useRef(false)
2046
+
2047
+ /* 🏟️ SÂN TRƯỚC CỬA HANG = BƯỚC 1 ĐẶT TÊN NHÂN VẬT:
2048
+ khi vừa tới sân trước cửa hang mà chưa có tên lưu sẵn → tự mở hộp đặt tên
2049
+ ngay (bước đầu tiên), KHÔNG đợi bấm "Vào hang". */
2050
+ React.useEffect(() => {
2051
+ if (route !== 'home' || namedOnce.current || dialog || phase !== 'idle') return
2052
+ const saved = (localStorage.getItem('hangmu.name') || '').trim()
2053
+ if (!saved) {
2054
+ namedOnce.current = true
2055
+ setDialog({ type: 'name', rename: false })
2056
+ }
2057
+ }, [route, dialog, phase])
2058
+
2059
+ React.useEffect(() => {
2060
+ const onHash = () => {
2061
+ const r = window.location.hash === '#/hang' ? 'cave' : 'home'
2062
+ setRoute(r)
2063
+ if (r === 'home' && useGame.getState().phase === 'inCave') leave()
2064
+ }
2065
+ window.addEventListener('hashchange', onHash)
2066
+ return () => window.removeEventListener('hashchange', onHash)
2067
+ }, [])
2068
+
2069
+ const enterCave = React.useCallback(async (name, number) => {
2070
+ const g = useGame.getState()
2071
+ g.set({ me: { name, number } })
2072
+ try {
2073
+ const data = await apiJoin(name, number)
2074
+ if (data.queued) {
2075
+ g.set({ phase: 'queued', queuePos: data.queue_position })
2076
+ const poll = setInterval(async () => {
2077
+ const st = await apiStatus()
2078
+ if (!st) return
2079
+ if (st.inRoom < st.capacity) {
2080
+ clearInterval(poll)
2081
+ try {
2082
+ const d2 = await apiJoin(name, number)
2083
+ if (!d2.queued && d2.player_id) {
2084
+ g.set({ phase: 'connecting', queuePos: 0 })
2085
+ connect(d2.player_id, name, number)
2086
+ window.location.hash = '#/hang'
2087
+ }
2088
+ } catch { }
2089
+ } else {
2090
+ g.set({ queuePos: Math.max(1, st.inRoom - st.capacity + 1), retryIn: 0 })
2091
+ }
2092
+ }, 2500)
2093
+ return
2094
+ }
2095
+ if (!data.player_id) throw new Error('no player_id')
2096
+ g.set({ phase: 'connecting' })
2097
+ connect(data.player_id, name, number)
2098
+ window.location.hash = '#/hang'
2099
+ } catch (e) {
2100
+ console.error('[hangmu] join failed:', e)
2101
+ g.set({ error: 'Không vào hang được. Kiểm tra kết nối và thử lại.', phase: 'idle' })
2102
+ }
2103
+ }, [])
2104
+
2105
+ const handleNameSubmit = (name, number) => {
2106
+ setDialog({ type: 'quiz', name, number })
2107
+ }
2108
+ const handleQuizDone = () => {
2109
+ const d = dialog
2110
+ setDialog(null)
2111
+ enterCave(d.name, d.number)
2112
+ }
2113
+
2114
+ const handleLeave = () => {
2115
+ if (useGame.getState().phase === 'inCave') {
2116
+ Net.send({ type: 'leave' })
2117
+ }
2118
+ leave()
2119
+ window.location.hash = '#/'
2120
+ }
2121
+
2122
+ React.useEffect(() => {
2123
+ if (phase !== 'queued') return
2124
+ const iv = setInterval(async () => {
2125
+ const st = await apiStatus()
2126
+ if (st && st.inRoom < st.capacity && me) {
2127
+ clearInterval(iv)
2128
+ enterCave(me.name, me.number)
2129
+ }
2130
+ }, 2500)
2131
+ return () => clearInterval(iv)
2132
+ }, [phase, me, enterCave])
2133
+
2134
+ const onQueueCancel = async () => {
2135
+ if (me) await apiLeaveQueue(me.name)
2136
+ useGame.getState().set({ phase: 'idle', queuePos: 0 })
2137
+ }
2138
+
2139
+ return (
2140
+ <R>
2141
+ {route === 'home' && (
2142
+ <Home
2143
+ me={me}
2144
+ queuePhase={phase === 'queued' ? 'queued' : (phase === 'connecting' ? 'connecting' : 'idle')}
2145
+ queuePos={queuePos}
2146
+ retryIn={retryIn}
2147
+ onEnter={() => setDialog({ type: 'name', rename: false })}
2148
+ onRename={() => setDialog({ type: 'name', rename: true, initial: me })}
2149
+ onShowLegal={() => setShowLegal(true)}
2150
+ onQueueCancel={onQueueCancel}
2151
+ />
2152
+ )}
2153
+ {route === 'cave' && <Cave onLeave={handleLeave} />}
2154
+ {dialog?.type === 'name' && (
2155
+ <NameDialog rename={dialog.rename} initial={dialog.initial || null} onCancel={() => setDialog(null)} onSubmit={handleNameSubmit} />
2156
+ )}
2157
+ {dialog?.type === 'quiz' && <QuizDialog onDone={handleQuizDone} onCancel={() => setDialog(null)} />}
2158
+ {showLegal && <LegalDialog onClose={() => setShowLegal(false)} />}
2159
+ <Consent onShowLegal={() => setShowLegal(true)} />
2160
+ {route === 'home' && <Donate className="home-donate" />}
2161
+ <UpdateNotice />
2162
+ <FpsBadge />
2163
+ </R>
2164
+ )
2165
+ }
2166
+
2167
+ createRoot(document.getElementById('root')).render(
2168
+ <React.StrictMode>
2169
+ <CaveErrorBoundary>
2170
+ <App />
2171
+ </CaveErrorBoundary>
2172
+ </React.StrictMode>
2173
+ )
frontend/cave3d.js CHANGED
@@ -377,14 +377,60 @@ function Entrance() {
377
  }
378
 
379
  /* =========================================================================
380
- MÀN HÌNH LỚN (board) — V108: BỎ BẢNG TRỐNG CÓ 3 BÓNG ĐÈN VÀNG.
381
- Board giờ vô hình hoàn toàn (return null). Giữ export BOARD để các module
382
- khác (scoreboard...) không vỡ import.
383
  ========================================================================= */
384
  export const BOARD = { w: 24, h: 14, y: 7.3, z: -47.5 }
385
  function Board() {
386
- // V108: bảng trống + 3 bóng đèn vàng + mái vòm + khung gỗ đã gỡ bỏ hoàn toàn.
387
- return null
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
  }
389
 
390
  /* =========================================================================
@@ -635,40 +681,6 @@ function EplBoard() {
635
  )
636
  }
637
 
638
- /* =========================================================================
639
- BẢNG THƠ (thay bảng tỷ số ESPN) — 4 dòng thơ nghiêng
640
- ========================================================================= */
641
- const MU_POEM = [
642
- 'Sáng đi thực tế, tối về hang.',
643
- 'Điện thoại, wifi đã sẵn sàng.',
644
- 'Vibe Code AI cần giới hạn.',
645
- 'Cuộc đời ứng dụng thật là sang',
646
- ]
647
- function drawMuPoemTex() {
648
- // Bảng thơ rõ nét: 4 dòng thơ nghiêng nằm trọn trong khung, chữ lớn dễ đọc.
649
- const c = document.createElement('canvas'); c.width = 1024; c.height = 680
650
- const g = c.getContext('2d')
651
- const W = 1024, H = 680
652
- const gr = g.createLinearGradient(0, 0, 0, H)
653
- gr.addColorStop(0, '#3f0a16'); gr.addColorStop(0.55, '#26050d'); gr.addColorStop(1, '#120304')
654
- g.fillStyle = gr; g.fillRect(0, 0, W, H)
655
- g.strokeStyle = 'rgba(201,162,78,0.9)'; g.lineWidth = 10; g.strokeRect(12, 12, W - 24, H - 24)
656
- g.textAlign = 'center'; g.textBaseline = 'middle'
657
- g.fillStyle = '#c9a24e'; g.font = '800 52px Bitter, Georgia, serif'
658
- g.fillText('THƠ HANG MU', W / 2, 78, W - 80)
659
- g.strokeStyle = 'rgba(201,162,78,0.6)'; g.lineWidth = 4
660
- g.beginPath(); g.moveTo(220, 128); g.lineTo(W - 220, 128); g.stroke()
661
- // 4 dòng thơ nghiêng (italic), canh giữa, maxWidth để KHÔNG tràn khung.
662
- g.font = 'italic 700 60px Georgia, "Times New Roman", serif'
663
- g.fillStyle = '#fff2c8'
664
- const y0 = 210, dy = 112
665
- MU_POEM.forEach((line, i) => {
666
- g.fillText(line, W / 2, y0 + i * dy, W - 100)
667
- })
668
- const tx = new THREE.CanvasTexture(c); tx.colorSpace = THREE.SRGBColorSpace; tx.anisotropy = 8
669
- return tx
670
- }
671
-
672
  /* =========================================================================
673
  TRẬN GẦN NHẤT + TRẬN SẮP TỚI CỦA MU — 2 bảng đặt NGAY gần bảng xếp hạng EPL
674
  (dữ liệu thật từ /api/mu/last + /api/mu/next — backend proxy ESPN team 360,
@@ -720,12 +732,68 @@ function MuMatchBoard({ pos, rot, tex, w = 2.9, h = 2.0 }) {
720
  }
721
 
722
  function MuMatchBoards() {
723
- // BẢNG THƠ — đặt ngang tầm mắt, bên trái, hướng ra cửa hang (+z) để dễ đọc.
724
- // Không billboard (tránh xoay khó nhìn); bảng có khung đỡ như các bảng khác.
725
- const tex = React.useMemo(() => drawMuPoemTex(), [])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
726
  return (
727
- <group position={[-13, 4.2, -26]} rotation={[0, 0.18, 0]}>
728
- <MuMatchBoard pos={[0, 0, 0]} rot={0} tex={tex} w={5.0} h={3.33} />
 
 
 
 
729
  </group>
730
  )
731
  }
@@ -818,7 +886,7 @@ function OnThisDayBoard() {
818
  TƯỜNG HUYỀN THOẠI — 3 bảng lớn quanh vòm + 10 chân dung
819
  ========================================================================= */
820
  const LEGEND_PANELS = [
821
- { kicker: 'HANG TU TRÍ AI V.AI STUDIO', title: 'Hang MU', sub: 'Nơi anh em fan Quỷ Đỏ tụ họp' },
822
  { kicker: 'MANCHESTER UNITED', title: 'Từ 1878', sub: 'Glory Glory Man United' },
823
  { kicker: 'TƯỜNG HUYỀN THOẠI', title: 'Thế hệ vàng', sub: 'Mười huyền thoại khoác áo đỏ' },
824
  ]
@@ -1021,19 +1089,7 @@ function CourtMarks() {
1021
  <meshBasicMaterial color="#1c1612" transparent opacity={0.45} />
1022
  </mesh>
1023
  <mesh position={[0, 0.01, -13]}>
1024
- <circleGeometry args={[0.28, 20]} />
1025
- <meshBasicMaterial color="#ffd76a" />
1026
- </mesh>
1027
- <mesh position={[0, 0.01, 13]}>
1028
- <circleGeometry args={[0.28, 20]} />
1029
- <meshBasicMaterial color="#ffd76a" />
1030
- </mesh>
1031
- <mesh position={[-13, 0.01, 0]}>
1032
- <circleGeometry args={[0.28, 20]} />
1033
- <meshBasicMaterial color="#ffd76a" />
1034
- </mesh>
1035
- <mesh position={[13, 0.01, 0]}>
1036
- <circleGeometry args={[0.28, 20]} />
1037
  <meshBasicMaterial color="#ffd76a" />
1038
  </mesh>
1039
  </group>
@@ -1042,124 +1098,172 @@ function CourtMarks() {
1042
  }
1043
 
1044
  /* =========================================================================
1045
- CÚP + BANNER + NÔM + SÂN CHƠI (giữ nguyên bản gốc e419952)
1046
  ========================================================================= */
1047
  function Trophy() {
1048
- const gold = useMemo(() => new THREE.MeshStandardMaterial({ color: '#e8b23a', metalness: 0.9, roughness: 0.25, flatShading: true }), [])
1049
  return (
1050
- <group position={[0, 0.6, 18]}>
1051
- <mesh castShadow position={[0, 0.9, 0]}>
1052
- <cylinderGeometry args={[0.55, 0.35, 0.5, 10]} />
1053
- {gold}
1054
  </mesh>
1055
- <mesh castShadow position={[0, 1.5, 0]}>
1056
- <cylinderGeometry args={[0.16, 0.22, 0.8, 8]} />
1057
- {gold}
1058
  </mesh>
1059
- <mesh castShadow position={[0, 2.05, 0]}>
1060
- <sphereGeometry args={[0.42, 14, 12, 0, Math.PI * 2, 0, Math.PI * 0.62]} />
1061
- {gold}
1062
  </mesh>
1063
- {[-1, 1].map((s) => (
1064
- <mesh key={s} position={[s * 0.42, 1.7, 0]} rotation={[0, 0, s * 0.5]}>
1065
- <torusGeometry args={[0.22, 0.05, 6, 12, Math.PI]} />
1066
- {gold}
1067
- </mesh>
1068
- ))}
1069
- <mesh position={[0, 0.25, 0]} castShadow>
1070
- <boxGeometry args={[0.7, 0.5, 0.7]} />
1071
- <meshLambertMaterial color="#2a1a10" flatShading />
 
 
1072
  </mesh>
 
 
 
 
 
1073
  </group>
1074
  )
1075
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1076
  function CaveBanners() {
1077
- const tex = useMemo(() => {
1078
- if (typeof document === 'undefined') return null
1079
- const c = document.createElement('canvas'); c.width = 512; c.height = 256
1080
- const g = c.getContext('2d')
1081
- const gr = g.createLinearGradient(0, 0, 0, 256)
1082
- gr.addColorStop(0, '#c8102e'); gr.addColorStop(1, '#7a0a1c')
1083
- g.fillStyle = gr; g.fillRect(0, 0, 512, 256)
1084
- g.strokeStyle = '#c9a24e'; g.lineWidth = 10; g.strokeRect(10, 10, 492, 236)
1085
- g.fillStyle = '#fff2c8'; g.font = '800 60px Bitter, Georgia, serif'; g.textAlign = 'center'; g.textBaseline = 'middle'
1086
- g.fillText('GLORY GLORY', 256, 96, 460)
1087
- g.font = '800 72px Bitter, Georgia, serif'; g.fillText('MAN UNITED', 256, 170, 460)
1088
- const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8
1089
- return t
1090
- }, [])
1091
- if (!tex) return null
1092
- const slots = [[-32, 9, -44, 0.5], [32, 9, -44, -0.5]]
1093
  return (
1094
  <group>
1095
- {slots.map(([x, y, z, rot], i) => (
1096
- <group key={i} position={[x, y, z]} rotation={[0, rot, 0]}>
1097
- <mesh position={[0, 0, -0.06]}>
1098
- <boxGeometry args={[5.6, 2.9, 0.16]} />
1099
- <meshLambertMaterial color="#3d2a1a" flatShading />
1100
- </mesh>
1101
- <mesh position={[0, 0, 0.04]}>
1102
- <planeGeometry args={[5.2, 2.6]} />
1103
- <meshBasicMaterial map={tex} transparent toneMapped={false} fog={false} />
1104
  </mesh>
1105
  </group>
1106
  ))}
1107
  </group>
1108
  )
1109
  }
 
 
 
 
1110
  function _jerseyTex() {
1111
  if (typeof document === 'undefined') return null
1112
- const c = document.createElement('canvas'); c.width = 256; c.height = 320
1113
  const g = c.getContext('2d')
1114
- g.fillStyle = '#17120d'; g.fillRect(0, 0, 256, 320)
1115
- g.fillStyle = '#f2c200'
1116
- g.beginPath(); g.moveTo(69, 84); g.lineTo(187, 84); g.lineTo(187, 234); g.lineTo(69, 234); g.closePath(); g.fill()
1117
- g.beginPath(); g.moveTo(69, 84); g.lineTo(25, 59); g.lineTo(43, 166); g.lineTo(69, 149); g.closePath(); g.fill()
1118
- g.beginPath(); g.moveTo(187, 84); g.lineTo(231, 59); g.lineTo(213, 166); g.lineTo(187, 149); g.closePath(); g.fill()
1119
- g.fillStyle = '#1a1a1a'; g.font = '800 84px "Be Vietnam Pro", Arial, sans-serif'; g.textAlign = 'center'; g.textBaseline = 'middle'
1120
- g.fillText('7', 128, 165)
1121
- const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8
 
 
 
 
 
 
 
 
1122
  return t
1123
  }
1124
  function JerseyDisplay() {
1125
- const tex = React.useMemo(() => _jerseyTex(), [])
1126
- if (!tex) return null
 
 
 
 
 
1127
  return (
1128
- <group position={[26, 5, -42]} rotation={[0, -0.4, 0]}>
1129
- <mesh position={[0, 0, -0.06]}>
1130
- <boxGeometry args={[2.0, 2.6, 0.16]} />
1131
  <meshLambertMaterial color="#3d2a1a" flatShading />
1132
  </mesh>
1133
- <mesh position={[0, 0, 0.04]}>
1134
- <planeGeometry args={[1.7, 2.2]} />
1135
- <meshBasicMaterial map={tex} transparent toneMapped={false} fog={false} />
1136
  </mesh>
 
 
 
 
 
 
1137
  </group>
1138
  )
1139
  }
1140
 
1141
  /* =========================================================================
1142
- SÂN NGOÀI (outdoor) — bầu trời + đất + lối đi + đạo cụ + cờ + ghế
1143
  ========================================================================= */
 
 
 
 
 
 
 
 
 
 
 
1144
  function SkyDome() {
 
1145
  return (
1146
- <mesh position={[0, 40, 90]}>
1147
- <sphereGeometry args={[120, 24, 16]} />
1148
- <meshBasicMaterial color="#9fc4e8" side={THREE.BackSide} fog={false} />
1149
  </mesh>
1150
  )
1151
  }
1152
  function OutdoorGround() {
1153
  const geo = useMemo(() => {
1154
- const m = new THREE.PlaneGeometry(140, 90, 40, 30)
1155
  m.rotateX(-Math.PI / 2)
1156
  const p = m.attributes.position
1157
  const cols = new Float32Array(p.count * 3)
1158
- const cA = new THREE.Color('#6d7d48'), cB = new THREE.Color('#56662d'), tmp = new THREE.Color()
1159
  for (let i = 0; i < p.count; i++) {
1160
  const x = p.getX(i), z = p.getZ(i)
1161
- p.setY(i, fbm3(x * 0.05, z * 0.05, 0, 51) * 0.3 - 0.1)
1162
- tmp.copy(cA).lerp(cB, fbm3(x * 0.1, z * 0.1, 2, 52) * 0.5 + 0.3)
 
1163
  cols[i * 3] = tmp.r; cols[i * 3 + 1] = tmp.g; cols[i * 3 + 2] = tmp.b
1164
  }
1165
  m.setAttribute('color', new THREE.BufferAttribute(cols, 3))
@@ -1167,62 +1271,64 @@ function OutdoorGround() {
1167
  return m
1168
  }, [])
1169
  return (
1170
- <mesh geometry={geo} position={[0, -0.05, 95]} fog={false}>
1171
  <meshLambertMaterial vertexColors fog={false} />
1172
  </mesh>
1173
  )
1174
  }
1175
  function OutdoorPath() {
1176
  return (
1177
- <mesh position={[0, 0.02, 70]} rotation={[-Math.PI / 2, 0, 0]} fog={false}>
1178
- <planeGeometry args={[8, 40]} />
1179
- <meshLambertMaterial color="#9a8a6c" fog={false} />
1180
  </mesh>
1181
  )
1182
  }
1183
  function OutdoorProps() {
1184
  const items = useMemo(() => {
1185
  const out = []
1186
- const rand = mulberry(77)
1187
- for (let i = 0; i < 18; i++) {
1188
- const side = i % 2 ? 1 : -1
1189
- const x = side * (6 + rand() * 18)
1190
- const z = 58 + rand() * 34
1191
- out.push({ x, z, s: 0.6 + rand() * 1.4, kind: i % 3 })
1192
  }
 
 
 
 
 
 
1193
  return out
1194
  }, [])
1195
  return (
1196
  <group>
1197
- {items.map((it, i) => it.kind === 0 ? (
1198
- <mesh key={i} position={[it.x, it.s * 0.5, it.z]} scale={[it.s, it.s, it.s]} castShadow fog={false}>
1199
- <icosahedronGeometry args={[0.6, 1]} />
1200
- <meshLambertMaterial color="#7f8a4a" flatShading fog={false} />
1201
- </mesh>
1202
- ) : it.kind === 1 ? (
1203
- <mesh key={i} position={[it.x, it.s * 0.4, it.z]} scale={[it.s, it.s * 0.8, it.s]} castShadow fog={false}>
1204
- <icosahedronGeometry args={[0.6, 0]} />
1205
- <meshLambertMaterial color="#8a7a5c" flatShading fog={false} />
1206
  </mesh>
1207
  ) : (
1208
- <mesh key={i} position={[it.x, it.s * 1.1, it.z]} castShadow fog={false}>
1209
- <coneGeometry args={[0.5 * it.s, 2.4 * it.s, 6]} />
1210
- <meshLambertMaterial color="#3f6b2e" flatShading fog={false} />
1211
- </mesh>
 
 
 
 
 
 
 
 
1212
  ))}
1213
  </group>
1214
  )
1215
  }
1216
-
1217
- /* =========================================================================
1218
- ÁNH SÁNG NGOÀI TRỜI
1219
- ========================================================================= */
1220
  function OutdoorLight() {
1221
  const tex = useMemo(() => {
1222
  const c = document.createElement('canvas'); c.width = c.height = 128
1223
  const g = c.getContext('2d')
1224
- const gr = g.createRadialGradient(64, 64, 0, 64, 64, 64)
1225
- gr.addColorStop(0, 'rgba(255,244,214,1)'); gr.addColorStop(1, 'rgba(255,214,140,0)')
1226
  g.fillStyle = gr; g.fillRect(0, 0, 128, 128)
1227
  const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace
1228
  return t
@@ -1333,56 +1439,27 @@ function ForecourtProps() {
1333
  }
1334
 
1335
  /* =========================================================================
1336
- CỜ VIỆT NAM — MỘT lá duy nhất bên PHẢI (x>0). Logo cờ lấy từ
1337
- poster_1794291583927.png (Space vaihome) làm nền cờ.
1338
  ========================================================================= */
1339
- const FLAG_POSTER_URL = 'https://huggingface.co/spaces/bep40/vaihome/resolve/main/public/poster_1794291583927.png'
1340
- let _flagPosterImg = null
1341
- function loadFlagPoster() {
1342
- if (_flagPosterImg) return Promise.resolve(_flagPosterImg)
1343
- if (typeof Image === 'undefined') return Promise.resolve(null)
1344
- return new Promise((resolve) => {
1345
- const img = new Image()
1346
- img.crossOrigin = 'anonymous'
1347
- img.decoding = 'async'
1348
- img.onload = () => { _flagPosterImg = img; resolve(img) }
1349
- img.onerror = () => { _flagPosterImg = null; resolve(null) }
1350
- img.src = FLAG_POSTER_URL
1351
- })
1352
- }
1353
- function makeFlagTex() {
1354
  if (typeof document === 'undefined') return null
1355
- const c = document.createElement('canvas'); c.width = 256; c.height = 170
1356
  const g = c.getContext('2d')
1357
- // nền đỏ cờ VN, viền vàng
1358
- g.fillStyle = '#da291c'; g.fillRect(0, 0, 256, 170)
1359
- g.strokeStyle = '#ffcd00'; g.lineWidth = 8; g.strokeRect(4, 4, 248, 162)
1360
- const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8
1361
- // Vẽ logo cờ (poster) phủ toàn bộ mặt cờ
1362
- loadFlagPoster().then((img) => {
1363
- if (img) {
1364
- g.drawImage(img, 0, 0, 256, 170)
1365
- } else {
1366
- // fallback: vẽ sao vàng nếu không tải được poster
1367
- g.fillStyle = '#ffcd00'
1368
- g.beginPath()
1369
- const cx = 128, cy = 85, R = 52, r = R * 0.382
1370
- for (let i = 0; i < 10; i++) {
1371
- const ang = -Math.PI / 2 + i * Math.PI / 5
1372
- const rad = i % 2 === 0 ? R : r
1373
- const px = cx + rad * Math.cos(ang), py = cy + rad * Math.sin(ang)
1374
- i === 0 ? g.moveTo(px, py) : g.lineTo(px, py)
1375
- }
1376
- g.closePath(); g.fill()
1377
- }
1378
- t.needsUpdate = true
1379
- })
1380
  return t
1381
  }
1382
  function OutdoorFlags() {
1383
- const tex = useMemo(() => makeFlagTex(), [])
1384
- // MỘT lá cờ duy nhất, bên PHẢI (x>0).
1385
- const flags = [{ x: 7, z: 62, tex }]
 
 
 
1386
  return (
1387
  <group>
1388
  {flags.map((f, i) => (
@@ -1507,7 +1584,7 @@ function AttendanceForecourt() {
1507
  }
1508
 
1509
  /* =========================================================================
1510
- GIÁ TREO ÁO #7 (VÀNG) — bên phải cửa hang; cột VÀNG nằm SAU bảng áo
1511
  ========================================================================= */
1512
  function JerseyStand() {
1513
  const [tex, setTex] = React.useState(null)
@@ -1519,16 +1596,15 @@ function JerseyStand() {
1519
  }, [])
1520
  return (
1521
  <group position={[6.5, 0, 70]} rotation={[0, -1.05, 0]} fog={false}>
1522
- {/* Cột VÀNG nằm phía sau tấm bảng áo (board z≈+0.06, cột z=-0.16) */}
1523
- <mesh position={[0, 1.3, -0.16]}>
1524
  <cylinderGeometry args={[0.07, 0.09, 2.6, 6]} />
1525
- <meshStandardMaterial color="#f2c200" metalness={0.25} roughness={0.5} flatShading fog={false} />
1526
  </mesh>
1527
- <mesh position={[0, 2.62, -0.16]}>
1528
  <sphereGeometry args={[0.1, 8, 8]} />
1529
- <meshStandardMaterial color="#ffcd00" metalness={0.25} roughness={0.5} fog={false} />
1530
  </mesh>
1531
- <mesh position={[0, 2.05, 0.06]} rotation-x={0.12}>
1532
  <planeGeometry args={[1.15, 1.45]} />
1533
  <meshBasicMaterial map={tex ?? null} transparent side={THREE.DoubleSide} toneMapped={false} fog={false} />
1534
  </mesh>
 
377
  }
378
 
379
  /* =========================================================================
380
+ MÀN HÌNH LỚN (board) — plane + texture "BẢNG TIN HANG MU" + khung gỗ
 
 
381
  ========================================================================= */
382
  export const BOARD = { w: 24, h: 14, y: 7.3, z: -47.5 }
383
  function Board() {
384
+ const [tex, setTex] = useState(null)
385
+ useEffect(() => {
386
+ let alive = true
387
+ const c = document.createElement('canvas')
388
+ c.width = 1920; c.height = 1120
389
+ const g = c.getContext('2d')
390
+ g.fillStyle = '#120c08'
391
+ g.fillRect(0, 0, 1920, 1120)
392
+ g.fillStyle = '#1d1510'
393
+ g.fillRect(40, 40, 1840, 1040)
394
+ g.strokeStyle = '#c9a24e'
395
+ g.lineWidth = 8
396
+ g.strokeRect(60, 60, 1800, 1000)
397
+ g.fillStyle = '#efe9dd'
398
+ g.textAlign = 'center'
399
+ g.font = '800 96px Bitter, Georgia, serif'
400
+ g.fillText('BẢNG TIN HANG MU', 960, 320)
401
+ g.font = '600 48px "Be Vietnam Pro", system-ui, sans-serif'
402
+ g.fillStyle = 'rgba(239,233,221,0.55)'
403
+ g.fillText('Highlight MU · Nhạc · Tỷ số trực tiếp', 960, 420)
404
+ g.font = '600 44px "Be Vietnam Pro", system-ui, sans-serif'
405
+ g.fillStyle = 'rgba(239,233,221,0.35)'
406
+ g.fillText('Thông báo của anh em sẽ hiện ở đây', 960, 700)
407
+ if (alive) {
408
+ const t = new THREE.CanvasTexture(c)
409
+ t.colorSpace = THREE.SRGBColorSpace
410
+ t.anisotropy = 16
411
+ setTex(t)
412
+ }
413
+ return () => { alive = false }
414
+ }, [])
415
+ const frameGeo = useMemo(() => displaceAndColor(new THREE.BoxGeometry(25.4, 15.4, 1.2, 10, 6, 2), { amp: 0.22, freq: 0.6, seed: 91, streaks: 0.4, base: '#a69682', shade: '#75685a', dark: '#352b23', warm: '#b09270' }), [])
416
+ return (
417
+ <group position={[0, BOARD.y, BOARD.z]}>
418
+ <mesh geometry={frameGeo} position={[0, 0, -0.45]}>
419
+ <meshStandardMaterial vertexColors flatShading roughness={0.95} />
420
+ </mesh>
421
+ <mesh position={[0, 0, 0.55]}>
422
+ <planeGeometry args={[BOARD.w, BOARD.h]} />
423
+ <meshStandardMaterial map={tex ?? null} color={tex ? '#ffffff' : '#6f665a'} roughness={0.9} />
424
+ </mesh>
425
+ {[-10.5, BOARD.w / 2 - 1.5].map((e) => (
426
+ <mesh key={e} position={[e, -7.3 / 2 - BOARD.h / 4, -0.4]}>
427
+ <boxGeometry args={[1.4, 7.3, 1.4]} />
428
+ <meshStandardMaterial color="#5e564c" flatShading roughness={1} />
429
+ </mesh>
430
+ ))}
431
+ <pointLight position={[0, 1, 5]} color="#ffb070" intensity={30} distance={16} decay={1.8} />
432
+ </group>
433
+ )
434
  }
435
 
436
  /* =========================================================================
 
681
  )
682
  }
683
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
684
  /* =========================================================================
685
  TRẬN GẦN NHẤT + TRẬN SẮP TỚI CỦA MU — 2 bảng đặt NGAY gần bảng xếp hạng EPL
686
  (dữ liệu thật từ /api/mu/last + /api/mu/next — backend proxy ESPN team 360,
 
732
  }
733
 
734
  function MuMatchBoards() {
735
+ const [lastTex, setLastTex] = React.useState(null)
736
+ const [nextTex, setNextTex] = React.useState(null)
737
+ React.useEffect(() => {
738
+ let alive = true
739
+ const dateStr = (iso) => {
740
+ if (!iso) return ''
741
+ try {
742
+ const d = new Date(iso)
743
+ return d.toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit' }) + '/' + d.getFullYear()
744
+ } catch { return '' }
745
+ }
746
+ const mkLast = (d) => {
747
+ if (!d) return { title: 'TRẬN GẦN NHẤT', sub: 'Chưa có dữ liệu', lines: [['Xem lại sau giờ đá', '—', '']] }
748
+ const who = d.opponent || 'Đối thủ'
749
+ const score = d.mu_score != null && d.opp_score != null
750
+ ? 'MU ' + d.mu_score + ' – ' + d.opp_score + ' ' + (who.length > 14 ? who.slice(0, 13) + '…' : who)
751
+ : 'Chưa có tỷ số'
752
+ const lines = [
753
+ ['Kết quả', score, 'P'],
754
+ ['Sân', (d.venue || (d.home ? 'Old Trafford' : 'Sân khách')) + (d.home ? ' · nhà' : ' · khách'), ''],
755
+ ]
756
+ const scorers = (d.scorers || []).slice(0, 5)
757
+ if (scorers.length) {
758
+ for (const s of scorers) {
759
+ const tag = s.side === 'mu' ? '⚽ MU' : '· ' + (d.opponent || 'đối thủ')
760
+ lines.push([`${s.minute || ''} ${s.player || '?'}`, tag, s.side === 'mu' ? 1 : 0])
761
+ }
762
+ } else {
763
+ lines.push(['Ghi bàn', 'Đang cập nhật…', ''])
764
+ }
765
+ return { title: 'TRẬN GẦN NHẤT', sub: dateStr(d.date) + ' · ' + who, lines }
766
+ }
767
+ const mkNext = (d) => {
768
+ if (!d) return { title: 'TRẬN SẮP TỚI', sub: 'Lịch chưa được công bố', lines: [['ESPN chưa đăng lịch', '—', '']] }
769
+ return {
770
+ title: 'TRẬN SẮP TỚI',
771
+ sub: (dateStr(d.date) || 'Chưa rõ ngày') + ' · ' + (d.opponent || '?'),
772
+ lines: [
773
+ ['Đối thủ', d.opponent || '?', ''],
774
+ ['Sân', (d.venue || (d.home ? 'Old Trafford' : 'Sân khách')) + (d.home ? ' · nhà' : ' · khách'), ''],
775
+ ],
776
+ }
777
+ }
778
+ Promise.all([
779
+ fetch('/api/mu/last', { cache: 'no-store' }).then((r) => r.ok ? r.json() : Promise.reject(new Error('last ' + r.status))),
780
+ fetch('/api/mu/next', { cache: 'no-store' }).then((r) => r.ok ? r.json() : Promise.reject(new Error('next ' + r.status))),
781
+ ])
782
+ .then(([last, nxt]) => {
783
+ if (!alive) return
784
+ setLastTex(drawMuMatchTex(mkLast(last && !last.error ? last : null)))
785
+ setNextTex(drawMuMatchTex(mkNext(nxt && !nxt.error && !nxt.none ? nxt : null)))
786
+ })
787
+ .catch(() => { /* bảng chỉ hiện khi có dữ liệu */ })
788
+ return () => { alive = false }
789
+ }, [])
790
  return (
791
+ <group>
792
+ {/* V31: tách 2 bảng TRẬN GẦN NHẤT / TRẬN SẮP TỚI ra góc trái xa (khỏi cụm EPL)
793
+ — TRẬN GẦN NHẤT sâu hơn (-38), TRẬN SẮP TỚI gần hơn (-34.5) dàn theo tường
794
+ để không che bảng xếp hạng EPL và nhìn được toàn bộ nội dung. */}
795
+ <MuMatchBoard pos={[-38, 5.6, -44]} rot={0.5} tex={lastTex} />
796
+ <MuMatchBoard pos={[-33.5, 5.6, -49]} rot={0.42} tex={nextTex} />
797
  </group>
798
  )
799
  }
 
886
  TƯỜNG HUYỀN THOẠI — 3 bảng lớn quanh vòm + 10 chân dung
887
  ========================================================================= */
888
  const LEGEND_PANELS = [
889
+ { kicker: 'DI TÍCH LỊCH SỬ', title: 'Hang MU', sub: 'Nơi anh em fan Quỷ Đỏ tụ họp' },
890
  { kicker: 'MANCHESTER UNITED', title: 'Từ 1878', sub: 'Glory Glory Man United' },
891
  { kicker: 'TƯỜNG HUYỀN THOẠI', title: 'Thế hệ vàng', sub: 'Mười huyền thoại khoác áo đỏ' },
892
  ]
 
1089
  <meshBasicMaterial color="#1c1612" transparent opacity={0.45} />
1090
  </mesh>
1091
  <mesh position={[0, 0.01, -13]}>
1092
+ <circleGeometry args={[1.9, 20]} />
 
 
 
 
 
 
 
 
 
 
 
 
1093
  <meshBasicMaterial color="#ffd76a" />
1094
  </mesh>
1095
  </group>
 
1098
  }
1099
 
1100
  /* =========================================================================
1101
+ CÚP VÀNG TRUNG TÂM (trophy)
1102
  ========================================================================= */
1103
  function Trophy() {
 
1104
  return (
1105
+ <group position={[0, 0, 0]} rotation-y={0.5}>
1106
+ <mesh position={[0, 0.12, 0]} castShadow>
1107
+ <cylinderGeometry args={[0.85, 1.0, 0.24, 8]} />
1108
+ <meshStandardMaterial color="#5a4a2c" metalness={0.6} roughness={0.4} flatShading />
1109
  </mesh>
1110
+ <mesh position={[0, 0.34, 0]} castShadow>
1111
+ <cylinderGeometry args={[0.55, 0.7, 0.2, 8]} />
1112
+ <meshStandardMaterial color="#8a6a2c" metalness={0.7} roughness={0.35} flatShading />
1113
  </mesh>
1114
+ <mesh position={[0, 0.85, 0]} castShadow>
1115
+ <cylinderGeometry args={[0.42, 0.5, 0.85, 10]} />
1116
+ <meshStandardMaterial color="#c9a24e" metalness={0.85} roughness={0.25} flatShading />
1117
  </mesh>
1118
+ <mesh position={[0, 1.32, 0]} castShadow>
1119
+ <torusGeometry args={[0.5, 0.09, 8, 18]} />
1120
+ <meshStandardMaterial color="#c9a24e" metalness={0.85} roughness={0.25} flatShading />
1121
+ </mesh>
1122
+ <mesh position={[-0.42, 0.85, 0]} rotation-z={0.3}>
1123
+ <torusGeometry args={[0.26, 0.07, 8, 14, Math.PI]} />
1124
+ <meshStandardMaterial color="#c9a24e" metalness={0.85} roughness={0.25} flatShading />
1125
+ </mesh>
1126
+ <mesh position={[0.42, 0.85, 0]} rotation-z={-0.3}>
1127
+ <torusGeometry args={[0.26, 0.07, 8, 14, Math.PI]} />
1128
+ <meshStandardMaterial color="#c9a24e" metalness={0.85} roughness={0.25} flatShading />
1129
  </mesh>
1130
+ <mesh position={[0, 1.62, 0]} castShadow>
1131
+ <sphereGeometry args={[0.2, 14, 14]} />
1132
+ <meshStandardMaterial color="#c9a24e" metalness={0.85} roughness={0.25} flatShading />
1133
+ </mesh>
1134
+ <pointLight position={[0, 2.6, 0]} color="#ffd76a" intensity={18} distance={9} decay={1.6} />
1135
  </group>
1136
  )
1137
  }
1138
+
1139
+ /* =========================================================================
1140
+ BANNER MU TRÊN VÒM
1141
+ ========================================================================= */
1142
+ function makeBannerTex(text) {
1143
+ const c = document.createElement('canvas')
1144
+ c.width = 512; c.height = 128
1145
+ const g = c.getContext('2d')
1146
+ g.fillStyle = '#c8102e'; g.fillRect(0, 0, 512, 128)
1147
+ g.fillStyle = '#8f0f22'; g.fillRect(6, 6, 500, 116)
1148
+ g.strokeStyle = '#ffd76a'; g.lineWidth = 4; g.strokeRect(6, 6, 500, 116)
1149
+ g.fillStyle = '#ffffff'; g.font = '900 52px "Be Vietnam Pro", sans-serif'
1150
+ g.textAlign = 'center'; g.textBaseline = 'middle'
1151
+ g.fillText(text, 256, 66)
1152
+ const t = new THREE.CanvasTexture(c)
1153
+ t.colorSpace = THREE.SRGBColorSpace
1154
+ return t
1155
+ }
1156
  function CaveBanners() {
1157
+ const texA = useMemo(() => makeBannerTex('GLORY GLORY'), [])
1158
+ const texB = useMemo(() => makeBannerTex('MAN UNITED'), [])
1159
+ const texC = useMemo(() => makeBannerTex('MU FAN'), [])
1160
+ const conf = [
1161
+ { tex: texA, pos: [-14, 12.5, -24], rot: [0, 0.5, 0] },
1162
+ { tex: texB, pos: [16, 12.8, -30], rot: [0, -0.45, 0] },
1163
+ { tex: texC, pos: [0, 13.2, -8], rot: [0, 0, 0] },
1164
+ ]
 
 
 
 
 
 
 
 
1165
  return (
1166
  <group>
1167
+ {conf.map((c, i) => (
1168
+ <group key={i} position={c.pos} rotation={c.rot}>
1169
+ <mesh>
1170
+ <planeGeometry args={[6, 1.5]} />
1171
+ <meshBasicMaterial map={c.tex} transparent toneMapped={false} fog={false} />
 
 
 
 
1172
  </mesh>
1173
  </group>
1174
  ))}
1175
  </group>
1176
  )
1177
  }
1178
+
1179
+ /* =========================================================================
1180
+ ÁO ĐỎ MU TRƯNG BÀY — jersey #7 trong khung gỗ cạnh màn hình lớn
1181
+ ========================================================================= */
1182
  function _jerseyTex() {
1183
  if (typeof document === 'undefined') return null
1184
+ const c = document.createElement('canvas'); c.width = 512; c.height = 640
1185
  const g = c.getContext('2d')
1186
+ g.fillStyle = '#17120d'; g.fillRect(0, 0, 512, 640)
1187
+ g.fillStyle = '#241b12'; g.fillRect(26, 26, 460, 588)
1188
+ g.fillStyle = '#c8102e'
1189
+ g.beginPath(); g.moveTo(138, 168); g.lineTo(374, 168); g.lineTo(374, 468); g.lineTo(138, 468); g.closePath(); g.fill()
1190
+ g.beginPath(); g.moveTo(138, 168); g.lineTo(50, 118); g.lineTo(86, 332); g.lineTo(138, 298); g.closePath(); g.fill()
1191
+ g.beginPath(); g.moveTo(374, 168); g.lineTo(462, 118); g.lineTo(426, 332); g.lineTo(374, 298); g.closePath(); g.fill()
1192
+ g.fillStyle = '#7c0d20'
1193
+ g.beginPath(); g.arc(256, 172, 36, 0, Math.PI * 2); g.fill()
1194
+ g.fillStyle = '#ffffff'
1195
+ g.font = '800 200px Georgia, serif'; g.textAlign = 'center'; g.textBaseline = 'middle'
1196
+ g.fillText('7', 256, 368)
1197
+ g.fillStyle = '#ffe9c0'; g.font = '700 40px Georgia, serif'
1198
+ g.fillText('MANCHESTER UNITED', 256, 548)
1199
+ const t = new THREE.CanvasTexture(c)
1200
+ t.colorSpace = THREE.SRGBColorSpace
1201
+ t.anisotropy = 16
1202
  return t
1203
  }
1204
  function JerseyDisplay() {
1205
+ const [tex, setTex] = React.useState(null)
1206
+ React.useEffect(() => {
1207
+ let alive = true
1208
+ const t = _jerseyTex()
1209
+ if (alive && t) setTex(t)
1210
+ return () => { alive = false }
1211
+ }, [])
1212
  return (
1213
+ <group position={[27, 0, -45.5]} rotation={[0, -0.34, 0]}>
1214
+ <mesh position={[0, 0.425, -0.12]}>
1215
+ <boxGeometry args={[0.55, 0.85, 0.55]} />
1216
  <meshLambertMaterial color="#3d2a1a" flatShading />
1217
  </mesh>
1218
+ <mesh position={[0, 2.15, -0.1]}>
1219
+ <boxGeometry args={[2.7, 3.55, 0.16]} />
1220
+ <meshLambertMaterial color="#5a3b22" flatShading />
1221
  </mesh>
1222
+ {tex && (
1223
+ <mesh position={[0, 2.18, 0.04]}>
1224
+ <planeGeometry args={[2.35, 2.94]} />
1225
+ <meshBasicMaterial map={tex} transparent fog={false} toneMapped={false} />
1226
+ </mesh>
1227
+ )}
1228
  </group>
1229
  )
1230
  }
1231
 
1232
  /* =========================================================================
1233
+ SÂN NGOÀI CỬA HANG (+z) — sân, cây, đá, trời, nắng
1234
  ========================================================================= */
1235
+ function _makeSkyTex() {
1236
+ if (typeof document === 'undefined') return null
1237
+ const c = document.createElement('canvas'); c.width = 64; c.height = 256
1238
+ const g = c.getContext('2d')
1239
+ const gr = g.createLinearGradient(0, 0, 0, 256)
1240
+ gr.addColorStop(0, '#7fb2e0'); gr.addColorStop(0.55, '#cfe3f2'); gr.addColorStop(0.8, '#e8d9bd'); gr.addColorStop(1, '#d8c2a0')
1241
+ g.fillStyle = gr; g.fillRect(0, 0, 64, 256)
1242
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace
1243
+ return t
1244
+ }
1245
+ const _skyTexC = _makeSkyTex()
1246
  function SkyDome() {
1247
+ const tex = useMemo(() => _skyTexC, [])
1248
  return (
1249
+ <mesh position={[0, 20, 178]} rotation={[0, Math.PI, 0]} fog={false}>
1250
+ <planeGeometry args={[170, 96]} />
1251
+ <meshBasicMaterial map={tex} fog={false} toneMapped={false} depthWrite={false} />
1252
  </mesh>
1253
  )
1254
  }
1255
  function OutdoorGround() {
1256
  const geo = useMemo(() => {
1257
+ const m = new THREE.PlaneGeometry(170, 100, 70, 40)
1258
  m.rotateX(-Math.PI / 2)
1259
  const p = m.attributes.position
1260
  const cols = new Float32Array(p.count * 3)
1261
+ const cA = new THREE.Color('#8a7a5c'), cB = new THREE.Color('#6d5c42'), moss = new THREE.Color('#7d7a45'), tmp = new THREE.Color()
1262
  for (let i = 0; i < p.count; i++) {
1263
  const x = p.getX(i), z = p.getZ(i)
1264
+ p.setY(i, fbm3(x * 0.06, z * 0.06, 0, 21) * 1.1 - 0.3)
1265
+ tmp.copy(cA).lerp(cB, fbm3(x * 0.12, z * 0.12, 3, 22) * 0.5 + 0.25)
1266
+ tmp.lerp(moss, Math.max(0, fbm3(x * 0.08, 9, z * 0.08, 23)) * 0.35)
1267
  cols[i * 3] = tmp.r; cols[i * 3 + 1] = tmp.g; cols[i * 3 + 2] = tmp.b
1268
  }
1269
  m.setAttribute('color', new THREE.BufferAttribute(cols, 3))
 
1271
  return m
1272
  }, [])
1273
  return (
1274
+ <mesh geometry={geo} position={[0, 0, 126]} receiveShadow fog={false}>
1275
  <meshLambertMaterial vertexColors fog={false} />
1276
  </mesh>
1277
  )
1278
  }
1279
  function OutdoorPath() {
1280
  return (
1281
+ <mesh position={[0, 0.04, 112]} rotation={[-Math.PI / 2, 0, 0]} fog={false}>
1282
+ <planeGeometry args={[11, 86]} />
1283
+ <meshBasicMaterial color="#a89474" fog={false} transparent opacity={0.85} />
1284
  </mesh>
1285
  )
1286
  }
1287
  function OutdoorProps() {
1288
  const items = useMemo(() => {
1289
  const out = []
1290
+ const boulder = (x, z, s, seed) => {
1291
+ const geo = displaceAndColor(new THREE.IcosahedronGeometry(1, 1),
1292
+ { amp: 0.3, freq: 1.1, seed, base: '#9a8a6c', shade: '#77664c', dark: '#4c3f2e', warm: '#b3a284' })
1293
+ out.push({ kind: 'boulder', geo, x, z, s })
 
 
1294
  }
1295
+ const tree = (x, z, s, seed) => out.push({ kind: 'tree', x, z, s, seed })
1296
+ boulder(-8, 80, 1.6, 101); boulder(9, 82, 2.1, 102); boulder(-14, 86, 2.8, 103)
1297
+ boulder(15, 88, 2.4, 104); boulder(-6, 94, 1.2, 105); boulder(11, 96, 1.4, 106)
1298
+ boulder(-18, 100, 3.2, 107); boulder(19, 102, 3.0, 108)
1299
+ tree(-12, 88, 1.5, 201); tree(12, 90, 1.8, 202); tree(-16, 96, 2.1, 203); tree(16, 98, 2.0, 204)
1300
+ tree(-8, 104, 1.4, 205); tree(8, 108, 1.6, 206)
1301
  return out
1302
  }, [])
1303
  return (
1304
  <group>
1305
+ {items.map((it, i) => it.kind === 'boulder' ? (
1306
+ <mesh key={i} geometry={it.geo} position={[it.x, it.s * 0.35, it.z]} scale={[it.s, it.s * 0.85, it.s]} fog={false}>
1307
+ <meshLambertMaterial vertexColors flatShading fog={false} />
 
 
 
 
 
 
1308
  </mesh>
1309
  ) : (
1310
+ <group key={i} position={[it.x, 0, it.z]} scale={[it.s, it.s, it.s]} fog={false}>
1311
+ <mesh position={[0, 1.1, 0]} fog={false}>
1312
+ <cylinderGeometry args={[0.22, 0.3, 2.2, 6]} />
1313
+ <meshLambertMaterial color="#6b4a2c" flatShading fog={false} />
1314
+ </mesh>
1315
+ {[0, 1, 2].map((k) => (
1316
+ <mesh key={k} position={[Math.sin(k * 2.1) * 0.7, 2.6 + k * 0.55, Math.cos(k * 2.1) * 0.7]} fog={false}>
1317
+ <coneGeometry args={[1.35 - k * 0.25, 1.6, 7]} />
1318
+ <meshLambertMaterial color={k === 0 ? '#3f6b2e' : k === 1 ? '#4c7a38' : '#5a8a42'} flatShading fog={false} />
1319
+ </mesh>
1320
+ ))}
1321
+ </group>
1322
  ))}
1323
  </group>
1324
  )
1325
  }
 
 
 
 
1326
  function OutdoorLight() {
1327
  const tex = useMemo(() => {
1328
  const c = document.createElement('canvas'); c.width = c.height = 128
1329
  const g = c.getContext('2d')
1330
+ const gr = g.createRadialGradient(64, 64, 2, 64, 64, 62)
1331
+ gr.addColorStop(0, 'rgba(255,240,200,0.9)'); gr.addColorStop(0.5, 'rgba(255,214,140,0.35)'); gr.addColorStop(1, 'rgba(255,214,140,0)')
1332
  g.fillStyle = gr; g.fillRect(0, 0, 128, 128)
1333
  const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace
1334
  return t
 
1439
  }
1440
 
1441
  /* =========================================================================
1442
+ CỜ MU/GGMU — 2 hàng 2 bên lối ra (z=62 và z=74), thấy ngay khi ra khỏi hang
 
1443
  ========================================================================= */
1444
+ function makePennantTex(text) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1445
  if (typeof document === 'undefined') return null
1446
+ const c = document.createElement('canvas'); c.width = 128; c.height = 128
1447
  const g = c.getContext('2d')
1448
+ g.fillStyle = '#c8102e'; g.fillRect(0, 0, 128, 128)
1449
+ g.strokeStyle = '#ffd76a'; g.lineWidth = 6; g.strokeRect(4, 4, 120, 120)
1450
+ g.fillStyle = '#ffffff'; g.font = '700 42px "Be Vietnam Pro", sans-serif'
1451
+ g.textAlign = 'center'; g.textBaseline = 'middle'
1452
+ g.fillText(text, 64, 66)
1453
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1454
  return t
1455
  }
1456
  function OutdoorFlags() {
1457
+ const texM = useMemo(() => makePennantTex('MU'), [])
1458
+ const texG = useMemo(() => makePennantTex('GGMU'), [])
1459
+ const flags = [
1460
+ { x: -7, z: 62, tex: texM }, { x: 7, z: 62, tex: texG },
1461
+ { x: -11, z: 74, tex: texG }, { x: 11, z: 74, tex: texM },
1462
+ ]
1463
  return (
1464
  <group>
1465
  {flags.map((f, i) => (
 
1584
  }
1585
 
1586
  /* =========================================================================
1587
+ GIÁ TREO ÁO MU #7 — bên phải cửa hang
1588
  ========================================================================= */
1589
  function JerseyStand() {
1590
  const [tex, setTex] = React.useState(null)
 
1596
  }, [])
1597
  return (
1598
  <group position={[6.5, 0, 70]} rotation={[0, -1.05, 0]} fog={false}>
1599
+ <mesh position={[0, 1.3, 0]}>
 
1600
  <cylinderGeometry args={[0.07, 0.09, 2.6, 6]} />
1601
+ <meshLambertMaterial color="#4a3220" flatShading fog={false} />
1602
  </mesh>
1603
+ <mesh position={[0, 2.62, 0]}>
1604
  <sphereGeometry args={[0.1, 8, 8]} />
1605
+ <meshStandardMaterial color="#c9a24e" fog={false} />
1606
  </mesh>
1607
+ <mesh position={[0, 2.05, 0]} rotation-x={0.12}>
1608
  <planeGeometry args={[1.15, 1.45]} />
1609
  <meshBasicMaterial map={tex ?? null} transparent side={THREE.DoubleSide} toneMapped={false} fog={false} />
1610
  </mesh>
frontend/home3d.js CHANGED
@@ -293,8 +293,8 @@ function drawRedPlaque() {
293
  })
294
  n.textAlign = 'center'; n.textBaseline = 'alphabetic'
295
  n.fillStyle = '#f6f3ee'
296
- n.font = '800 128px Georgia, serif'; n.fillText('HANG TU TRÍ', 512, 470, 940)
297
- n.font = '800 150px Georgia, serif'; n.fillText('AI V.AI STUDIO', 512, 690, 940)
298
  const tex = new THREE.CanvasTexture(c)
299
  tex.colorSpace = THREE.SRGBColorSpace
300
  tex.anisotropy = 16
@@ -309,7 +309,7 @@ function StelePlate() {
309
  const [tex, setTex] = useState(null)
310
  useEffect(() => {
311
  let alive = true
312
- Promise.all([document.fonts.load('800 128px Georgia', 'HANG TU TRÍ').catch(() => 0), document.fonts.load('800 150px Georgia', 'AI V.AI STUDIO').catch(() => 0)]).then(() => {
313
  const t = drawRedPlaque()
314
  if (alive) setTex(t)
315
  })
@@ -352,7 +352,7 @@ function PostAndPlaque() {
352
  useEffect(() => {
353
  let alive = true
354
  drawRedPlaque()
355
- Promise.all([document.fonts.load('800 128px Georgia', 'HANG TU TRÍ').catch(() => 0), document.fonts.load('800 150px Georgia', 'AI V.AI STUDIO').catch(() => 0)]).then(() => {
356
  const t = drawRedPlaque()
357
  if (alive) setTex(t)
358
  })
@@ -429,51 +429,16 @@ function drawPennantTex(text) {
429
  })
430
  return t
431
  }
432
- /* Cờ Việt Nam — logo lấy từ poster_1794291583927.png (Space vaihome).
433
- MỘT lá cờ duy nhất, bên PHẢI (x>0). */
434
- const FLAG_POSTER_URL = 'https://huggingface.co/spaces/bep40/vaihome/resolve/main/public/poster_1794291583927.png'
435
- let _flagPosterImg = null
436
- function loadFlagPoster() {
437
- if (_flagPosterImg) return Promise.resolve(_flagPosterImg)
438
- return new Promise((resolve) => {
439
- const img = new Image()
440
- img.crossOrigin = 'anonymous'
441
- img.decoding = 'async'
442
- img.onload = () => { _flagPosterImg = img; resolve(img) }
443
- img.onerror = () => { _flagPosterImg = null; resolve(null) }
444
- img.src = FLAG_POSTER_URL
445
- })
446
- }
447
- function drawFlagTex() {
448
- if (typeof document === 'undefined') return null
449
- const c = document.createElement('canvas'); c.width = 256; c.height = 170
450
- const g = c.getContext('2d')
451
- g.fillStyle = '#da291c'; g.fillRect(0, 0, 256, 170)
452
- g.strokeStyle = '#ffcd00'; g.lineWidth = 8; g.strokeRect(4, 4, 248, 162)
453
- const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8
454
- loadFlagPoster().then((img) => {
455
- if (img) {
456
- g.drawImage(img, 0, 0, 256, 170)
457
- } else {
458
- g.fillStyle = '#ffcd00'
459
- g.beginPath()
460
- const cx = 128, cy = 85, R = 52, r = R * 0.382
461
- for (let i = 0; i < 10; i++) {
462
- const ang = -Math.PI / 2 + i * Math.PI / 5
463
- const rad = i % 2 === 0 ? R : r
464
- const px = cx + rad * Math.cos(ang), py = cy + rad * Math.sin(ang)
465
- i === 0 ? g.moveTo(px, py) : g.lineTo(px, py)
466
- }
467
- g.closePath(); g.fill()
468
- }
469
- t.needsUpdate = true
470
- })
471
- return t
472
- }
473
- /* Cờ VN: MỘT lá duy nhất bên PHẢI (x>0) — logo = poster từ Space vaihome. */
474
  function HomeFlags() {
475
- const tex = useMemo(() => drawFlagTex(), [])
476
- const flags = [{ x: 14.5, z: 7, tex }]
 
 
 
 
477
  return (
478
  <group>
479
  {flags.map((f, i) => (
@@ -500,35 +465,41 @@ function _jerseyTexHome() {
500
  if (typeof document === 'undefined') return null
501
  const c = document.createElement('canvas'); c.width = 512; c.height = 640
502
  const g = c.getContext('2d')
503
- // Nền bảng treo áo — tối giản, KHÔNG còn chữ MU / logo MU / số 7.
504
  g.fillStyle = '#17120d'; g.fillRect(0, 0, 512, 640)
505
  g.fillStyle = '#241b12'; g.fillRect(26, 26, 460, 588)
506
- // ÁO MÀU VÀNG — thân + 2 tay áo.
507
- g.fillStyle = '#f2c200'
508
  g.beginPath(); g.moveTo(138, 168); g.lineTo(374, 168); g.lineTo(374, 468); g.lineTo(138, 468); g.closePath(); g.fill()
509
  g.beginPath(); g.moveTo(138, 168); g.lineTo(50, 118); g.lineTo(86, 332); g.lineTo(138, 298); g.closePath(); g.fill()
510
  g.beginPath(); g.moveTo(374, 168); g.lineTo(462, 118); g.lineTo(426, 332); g.lineTo(374, 298); g.closePath(); g.fill()
511
- // Cổ áo
512
- g.fillStyle = '#c99e00'
513
  g.beginPath(); g.arc(256, 172, 36, 0, Math.PI * 2); g.fill()
 
 
 
514
  const t = new THREE.CanvasTexture(c)
515
  t.colorSpace = THREE.SRGBColorSpace
516
  t.anisotropy = 16
517
- // In FULL CỜ (poster VN) lên TOÀN BỘ thân áo — bỏ số 7, không còn logo/chữ MU.
518
- loadFlagPoster().then((img) => {
519
  if (!img) return
520
- const bx = 138, by = 168, bw = 236, bh = 300
 
521
  g.save()
522
- g.strokeStyle = '#ffcd00'; g.lineWidth = 6
523
- g.strokeRect(bx - 3, by - 3, bw + 6, bh + 6)
524
- g.drawImage(img, bx, by, bw, bh)
525
  g.restore()
 
 
 
 
526
  t.needsUpdate = true
527
  })
528
  return t
529
  }
530
- /* Cột treo áo số 7 (VÀNG) — CỘT nằm PHÍA SAU tấm bảng treo áo (z âm = sau),
531
- áo in full cờ, không còn chữ/logo MU. */
 
532
  function JerseyStandHome({ pos = [5.2, 0, 2.8], rot = -0.5 }) {
533
  const [tex, setTex] = useState(null)
534
  useEffect(() => {
@@ -539,16 +510,15 @@ function JerseyStandHome({ pos = [5.2, 0, 2.8], rot = -0.5 }) {
539
  }, [])
540
  return (
541
  <group position={pos} rotation={[0, rot, 0]}>
542
- {/* Cột VÀNG nằm SAU bảng treo áo (board ở z≈+0.1, cột ở z=-0.22) */}
543
- <mesh position={[0, 1.8, -0.22]} castShadow>
544
  <cylinderGeometry args={[0.09, 0.11, 3.6, 6]} />
545
- <meshStandardMaterial color="#f2c200" metalness={0.3} roughness={0.5} flatShading />
546
  </mesh>
547
- <mesh position={[0, 3.6, -0.22]}>
548
  <sphereGeometry args={[0.12, 8, 8]} />
549
- <meshStandardMaterial color="#ffcd00" metalness={0.3} roughness={0.5} />
550
  </mesh>
551
- <mesh position={[0, 2.75, 0.1]} rotation-x={0.1} castShadow>
552
  <planeGeometry args={[1.85, 2.35]} />
553
  <meshBasicMaterial map={tex ?? null} transparent side={THREE.DoubleSide} toneMapped={false} />
554
  </mesh>
@@ -606,39 +576,23 @@ function drawMuLastTexHome(d) {
606
  const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8
607
  return t
608
  }
609
- /* 📜 BẢNG THƠ HANG MU — thay bảng tỷ số ESPN (không còn gọi /api/mu/last).
610
- 4 dòng thơ nghiêng, nội dung trọn vẹn trong khung. */
611
- const MU_POEM_HOME = [
612
- 'Sáng đi thực tế, tối về hang.',
613
- 'Điện thoại, wifi đã sẵn sàng.',
614
- 'Vibe Code AI cần giới hạn.',
615
- 'Cuộc đời ứng dụng thật là sang',
616
- ]
617
- function drawMuPoemTexHome() {
618
- const c = document.createElement('canvas'); c.width = 840; c.height = 540
619
- const g = c.getContext('2d')
620
- const gr = g.createLinearGradient(0, 0, 0, 540)
621
- gr.addColorStop(0, '#3f0a16'); gr.addColorStop(0.55, '#26050d'); gr.addColorStop(1, '#120304')
622
- g.fillStyle = gr; g.fillRect(0, 0, 840, 540)
623
- g.strokeStyle = MU_RED; g.lineWidth = 8; g.strokeRect(10, 10, 820, 520)
624
- g.textAlign = 'center'; g.textBaseline = 'middle'
625
- g.fillStyle = '#c9a24e'; g.font = '800 52px Bitter, Georgia, serif'
626
- g.fillText('THƠ HANG MU', 420, 70)
627
- g.strokeStyle = 'rgba(201,162,78,0.6)'; g.lineWidth = 3
628
- g.beginPath(); g.moveTo(180, 110); g.lineTo(660, 110); g.stroke()
629
- g.font = 'italic 600 40px Georgia, "Times New Roman", serif'
630
- g.fillStyle = '#fff2c8'
631
- const y0 = 180, dy = 80
632
- MU_POEM_HOME.forEach((line, i) => {
633
- g.fillText(line, 420, y0 + i * dy, 740)
634
- })
635
- const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8
636
- return t
637
- }
638
  function MuLastBoardHome({ pos = [5.4, 0, 2.2], rot = -0.55 }) {
639
- const tex = useMemo(() => drawMuPoemTexHome(), [])
640
- /* Bảng thơ đứng riêng trên giá gỗ, đặt SÂU VÀO TRONG sân (giảm |x|, tăng z) để
641
- nhìn thấy trọn vẹn nội dung, không che lối vào hang. */
 
 
 
 
 
 
 
 
 
 
 
 
 
642
  return (
643
  <group position={pos} rotation={[0, rot, 0]}>
644
  <mesh position={[0, 2.3, -0.14]} castShadow>
@@ -707,12 +661,12 @@ function useLayout(m) {
707
  z≈2.8) — ngoài lối vào cửa hang (x∈[-5,5]), đối diện camera nên đọc được
708
  toàn bộ nội dung, không che bia đá (stele x≈-3.1) hay cột DI TÍCH (x≈5.7). */
709
  const JERSEY_POS = {
710
- mobile: [3.4, 0, 3.6],
711
- desktop: [5.2, 0, 3.6],
712
  }
713
  const SCORE_POS = {
714
- mobile: [-4.2, 0, 4.6],
715
- desktop: [-5.8, 0, 4.4],
716
  }
717
 
718
  export function HomeScene() {
 
293
  })
294
  n.textAlign = 'center'; n.textBaseline = 'alphabetic'
295
  n.fillStyle = '#f6f3ee'
296
+ n.font = '700 90px Georgia, serif'; n.fillText('DI TÍCH LỊCH SỬ', 512, 520)
297
+ n.font = '800 200px Georgia, serif'; n.fillText('HANG MU', 512, 700)
298
  const tex = new THREE.CanvasTexture(c)
299
  tex.colorSpace = THREE.SRGBColorSpace
300
  tex.anisotropy = 16
 
309
  const [tex, setTex] = useState(null)
310
  useEffect(() => {
311
  let alive = true
312
+ Promise.all([document.fonts.load('700 90px Georgia', 'DI TÍCH LỊCH SỬ').catch(() => 0), document.fonts.load('800 200px Georgia', 'HANG MU').catch(() => 0)]).then(() => {
313
  const t = drawRedPlaque()
314
  if (alive) setTex(t)
315
  })
 
352
  useEffect(() => {
353
  let alive = true
354
  drawRedPlaque()
355
+ Promise.all([document.fonts.load('700 90px Georgia', 'DI TÍCH LỊCH SỬ').catch(() => 0), document.fonts.load('800 200px Georgia', 'HANG MU').catch(() => 0)]).then(() => {
356
  const t = drawRedPlaque()
357
  if (alive) setTex(t)
358
  })
 
429
  })
430
  return t
431
  }
432
+ /* V32: cờ MU KHÔNG chắn cửa hang và NẰM NGOÀI KHUNG HÌNH — 4 cờ dạt ra 2 bên
433
+ XA cửa (x=±14.5 và x=±17, z≈7..11), ngoài phạm vi khung camera (~±12.5 tại
434
+ trường nhìn mobile mở rộng), nên không xuất hiện trước cửa hang ở bước 1. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
435
  function HomeFlags() {
436
+ const texM = useMemo(() => drawPennantTex('MU'), [])
437
+ const texG = useMemo(() => drawPennantTex('GGMU'), [])
438
+ const flags = [
439
+ { x: -14.5, z: 7, tex: texM }, { x: 14.5, z: 7, tex: texG },
440
+ { x: -17, z: 11, tex: texG }, { x: 17, z: 11, tex: texM },
441
+ ]
442
  return (
443
  <group>
444
  {flags.map((f, i) => (
 
465
  if (typeof document === 'undefined') return null
466
  const c = document.createElement('canvas'); c.width = 512; c.height = 640
467
  const g = c.getContext('2d')
 
468
  g.fillStyle = '#17120d'; g.fillRect(0, 0, 512, 640)
469
  g.fillStyle = '#241b12'; g.fillRect(26, 26, 460, 588)
470
+ g.fillStyle = '#c8102e'
 
471
  g.beginPath(); g.moveTo(138, 168); g.lineTo(374, 168); g.lineTo(374, 468); g.lineTo(138, 468); g.closePath(); g.fill()
472
  g.beginPath(); g.moveTo(138, 168); g.lineTo(50, 118); g.lineTo(86, 332); g.lineTo(138, 298); g.closePath(); g.fill()
473
  g.beginPath(); g.moveTo(374, 168); g.lineTo(462, 118); g.lineTo(426, 332); g.lineTo(374, 298); g.closePath(); g.fill()
474
+ g.fillStyle = '#7c0d20'
 
475
  g.beginPath(); g.arc(256, 172, 36, 0, Math.PI * 2); g.fill()
476
+ g.fillStyle = '#ffffff'
477
+ g.font = '800 220px Georgia, serif'; g.textAlign = 'center'; g.textBaseline = 'middle'
478
+ g.fillText('7', 256, 372)
479
  const t = new THREE.CanvasTexture(c)
480
  t.colorSpace = THREE.SRGBColorSpace
481
  t.anisotropy = 16
482
+ // Logo MU nhỏ phía trên số (nền trắng bo tròn) — nổi bật trên áo đỏ
483
+ loadPennantImg().then((img) => {
484
  if (!img) return
485
+ const s = 64 / Math.max(img.naturalWidth || img.width, img.naturalHeight || img.height)
486
+ const w = (img.naturalWidth || img.width) * s, h = (img.naturalHeight || img.height) * s
487
  g.save()
488
+ g.fillStyle = 'rgba(255,255,255,0.95)'
489
+ g.beginPath(); g.arc(256, 124, 36, 0, Math.PI * 2); g.fill()
490
+ g.drawImage(img, 256 - w / 2, 124 - h / 2, w, h)
491
  g.restore()
492
+ g.fillStyle = '#ffe9c0'; g.font = '700 44px Georgia, serif'
493
+ g.fillText('MANCHESTER UNITED', 256, 550)
494
+ g.fillStyle = '#ffffff'; g.font = '800 30px Bitter, Georgia, serif'
495
+ g.fillText('HANG MU', 256, 594)
496
  t.needsUpdate = true
497
  })
498
  return t
499
  }
500
+ /* V32: cột treo áo MU #7 — trong khung hình + ÁO TO HƠN (plane 1.85×2.35, cột cao
501
+ 3.6) để số 7 và chữ MANCHESTER UNITED đọc rõ ngay ở bước 1; đứng bên lề (không
502
+ che lối vào hang, không đè cột bia DI TÍCH LỊCH SỬ). */
503
  function JerseyStandHome({ pos = [5.2, 0, 2.8], rot = -0.5 }) {
504
  const [tex, setTex] = useState(null)
505
  useEffect(() => {
 
510
  }, [])
511
  return (
512
  <group position={pos} rotation={[0, rot, 0]}>
513
+ <mesh position={[0, 1.8, 0]} castShadow>
 
514
  <cylinderGeometry args={[0.09, 0.11, 3.6, 6]} />
515
+ <meshLambertMaterial color="#4a3220" flatShading />
516
  </mesh>
517
+ <mesh position={[0, 3.6, 0]}>
518
  <sphereGeometry args={[0.12, 8, 8]} />
519
+ <meshStandardMaterial color="#c9a24e" />
520
  </mesh>
521
+ <mesh position={[0, 2.75, 0]} rotation-x={0.1} castShadow>
522
  <planeGeometry args={[1.85, 2.35]} />
523
  <meshBasicMaterial map={tex ?? null} transparent side={THREE.DoubleSide} toneMapped={false} />
524
  </mesh>
 
576
  const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8
577
  return t
578
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
579
  function MuLastBoardHome({ pos = [5.4, 0, 2.2], rot = -0.55 }) {
580
+ const [tex, setTex] = useState(null)
581
+ useEffect(() => {
582
+ let alive = true
583
+ fetch('/api/mu/last', { cache: 'no-store' })
584
+ .then((r) => r.ok ? r.json() : Promise.reject(new Error('last ' + r.status)))
585
+ .then((d) => {
586
+ if (!alive) return
587
+ setTex(drawMuLastTexHome(d && !d.error ? d : null))
588
+ })
589
+ .catch(() => { if (alive) setTex(drawMuLastTexHome(null)) })
590
+ return () => { alive = false }
591
+ }, [])
592
+ if (!tex) return null
593
+ /* V32: bảng tỷ số TO HƠN (plane 6.5×4.15, khung 7×4.5) + đứng riêng trên giá —
594
+ đặt bên TRÁI sân trước (SCORE_POS) — không che lối vào cửa hang, không đè
595
+ bia đá, nhìn được toàn bộ nội dung. */
596
  return (
597
  <group position={pos} rotation={[0, rot, 0]}>
598
  <mesh position={[0, 2.3, -0.14]} castShadow>
 
661
  z≈2.8) — ngoài lối vào cửa hang (x∈[-5,5]), đối diện camera nên đọc được
662
  toàn bộ nội dung, không che bia đá (stele x≈-3.1) hay cột DI TÍCH (x≈5.7). */
663
  const JERSEY_POS = {
664
+ mobile: [3.9, 0, 3.0],
665
+ desktop: [6.2, 0, 3.0],
666
  }
667
  const SCORE_POS = {
668
+ mobile: [-5.3, 0, 2.9],
669
+ desktop: [-7.6, 0, 2.8],
670
  }
671
 
672
  export function HomeScene() {
frontend/images/vai-logo-carved.png DELETED
Binary file (44.9 kB)
 
frontend/images/vai-logo-carved.webp DELETED

Git LFS Details

  • SHA256: caa8ab4483e4951f5961e6759f987a8e8b38310756b3685f9d160cd453200104
  • Pointer size: 131 Bytes
  • Size of remote file: 105 kB
frontend/images/vai-logo-carved@2x.webp DELETED

Git LFS Details

  • SHA256: dafb443fabaf750a48823ee753742a8f51c4943a122a656efd3a174f5a8decb6
  • Pointer size: 131 Bytes
  • Size of remote file: 327 kB
frontend/images/vai-logo-stone.png DELETED
Binary file (40 kB)
 
frontend/images/vai-logo-stone.webp DELETED
Binary file (93.7 kB)
 
frontend/images/vai-logo-stone@2x.webp DELETED

Git LFS Details

  • SHA256: b0e7dc1ba3b931010375762b22745c5c3b878aa879ca3b9c54dce754a1aac309
  • Pointer size: 131 Bytes
  • Size of remote file: 298 kB
frontend/images/vai-logo.png DELETED

Git LFS Details

  • SHA256: 04279a970819ec9614042513d2411138082bb17a97a68fb55b1fd4c8f5cb24f0
  • Pointer size: 131 Bytes
  • Size of remote file: 418 kB
frontend/index.html CHANGED
@@ -42,7 +42,7 @@
42
  <meta name="twitter:image" content="/og-image.png" />
43
  <meta name="twitter:title" content="Hang MU — Di tích lịch sử của fan MU" />
44
  <meta
45
- property="og:description"
46
  content="Sân chơi 3D multiplayer do fan MU tự làm: vào hang, ra hang cùng anh em fan Quỷ Đỏ."
47
  />
48
 
@@ -81,17 +81,17 @@
81
  }
82
  </script>
83
 
84
- <!-- Cache-bust: đổi version mỗi bản deploy — buộc tải lại bản đã sửa -->
85
- <link rel="stylesheet" href="/styles/heritage.css?v=116" />
86
- <link rel="stylesheet" href="/styles/main.css?v=116" />
87
- <link rel="stylesheet" href="/styles/cavescreen.css?v=139" />
88
- <link rel="stylesheet" href="/styles/home.css?v=116" />
89
- <link rel="stylesheet" href="/styles/slab.css?v=116" />
90
- <link rel="stylesheet" href="/styles/playlist.css?v=116" />
91
  </head>
92
  <body>
93
  <div id="root"></div>
94
- <!-- Bundle v101: cache-bust đổi URL mỗi bản deploy — buộc tải lại bản đã sửa -->
95
- <script src="/static/app.bundle.js?v=116"></script>
96
  </body>
97
  </html>
 
42
  <meta name="twitter:image" content="/og-image.png" />
43
  <meta name="twitter:title" content="Hang MU — Di tích lịch sử của fan MU" />
44
  <meta
45
+ name="twitter:description"
46
  content="Sân chơi 3D multiplayer do fan MU tự làm: vào hang, ra hang cùng anh em fan Quỷ Đỏ."
47
  />
48
 
 
81
  }
82
  </script>
83
 
84
+ <!-- Đúng bộ chữ + design system của hangmu.online. Thêm ?v=35 để cache-bust CSS
85
+ giống bundle JS — tránh trình duyệt giữ phiên bản CSS cũ. -->
86
+ <link rel="stylesheet" href="/styles/heritage.css?v=35" />
87
+ <link rel="stylesheet" href="/styles/main.css?v=35" />
88
+ <link rel="stylesheet" href="/styles/cavescreen.css?v=35" />
89
+ <link rel="stylesheet" href="/styles/home.css?v=35" />
90
+ <link rel="stylesheet" href="/styles/slab.css?v=35" />
91
  </head>
92
  <body>
93
  <div id="root"></div>
94
+ <!-- Bundle v35: cache-bust đổi URL mỗi bản deploy — buộc tải lại bản đã sửa -->
95
+ <script src="/static/app.bundle.js?v=35"></script>
96
  </body>
97
  </html>
frontend/store.js CHANGED
@@ -105,7 +105,6 @@ export const useGame = create((set, get) => ({
105
  voice: makeVoice(),
106
  notice: makeNotice(),
107
  rage: makeRage(),
108
- christmas: makeChristmas(),
109
 
110
  set(partial) { set(partial) },
111
  }))
@@ -210,6 +209,7 @@ function makeRage() {
210
  set(p) { Object.assign(state, p); emit() },
211
  }
212
  }
 
213
  /* ---- hooks ----
214
  useSyncExternalStore(subscribe, getSnapshot) — phải truyền ĐÚNG 2 hàm.
215
  Trước đây gọi `useSync(c)` (thiếu getSnapshot) → React gọi getSnapshot()
@@ -399,7 +399,7 @@ function handleServer(data) {
399
  name: g.me?.name || 'Bạn',
400
  number: g.me?.number ?? null,
401
  pos: new THREE.Vector3(sp.x, sp.y, sp.z),
402
- rot: Math.PI, // V34: mới vào hang quay mặt VÀO TRONG (hướng -z, nhìn màn hình lớn/trung tâm)
403
  anim: 'idle',
404
  lastSeen: Date.now(),
405
  })
@@ -587,21 +587,6 @@ function handleServer(data) {
587
  break
588
  }
589
  case 'pong': break
590
- case 'christmas_decor': {
591
- /* Nguoi khac vua trang tri — them vao cay cua minh */
592
- const ch = g.christmas
593
- ch.addOrnament({
594
- kind: data.kind,
595
- x: data.x, y: data.y, z: data.z,
596
- color: data.color,
597
- by: data.player_id,
598
- })
599
- break
600
- }
601
- case 'christmas_ack': {
602
- /* Xac nhan da gui — khong can lam gi */
603
- break
604
- }
605
  default: break
606
  }
607
  }
 
105
  voice: makeVoice(),
106
  notice: makeNotice(),
107
  rage: makeRage(),
 
108
 
109
  set(partial) { set(partial) },
110
  }))
 
209
  set(p) { Object.assign(state, p); emit() },
210
  }
211
  }
212
+
213
  /* ---- hooks ----
214
  useSyncExternalStore(subscribe, getSnapshot) — phải truyền ĐÚNG 2 hàm.
215
  Trước đây gọi `useSync(c)` (thiếu getSnapshot) → React gọi getSnapshot()
 
399
  name: g.me?.name || 'Bạn',
400
  number: g.me?.number ?? null,
401
  pos: new THREE.Vector3(sp.x, sp.y, sp.z),
402
+ rot: 0,
403
  anim: 'idle',
404
  lastSeen: Date.now(),
405
  })
 
587
  break
588
  }
589
  case 'pong': break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
590
  default: break
591
  }
592
  }
frontend/styles/cavescreen.css CHANGED
The diff for this file is too large to render. See raw diff
 
frontend/styles/home.css CHANGED
@@ -74,7 +74,7 @@ html, body {
74
  position: relative;
75
  min-height: 100dvh;
76
  display: grid;
77
- grid-template-rows: 1fr auto auto;
78
  align-items: start;
79
  justify-items: center;
80
  gap: 10px;
@@ -84,11 +84,6 @@ html, body {
84
  radial-gradient(120% 90% at 50% 0%, #2b1d12 0%, #140f0c 70%),
85
  #120b08;
86
  }
87
- /* Khuôn hình: hàng 1 (1fr) là khoảng trống đàn hồi đẩy bảng bia XUỐNG DƯỚI;
88
- bảng bia (HANG TU TRÍ AI / AI V.AI STUDIO) nằm ngay TRÊN nhóm nút
89
- (Group Zalo + Cài đặt app + Thông báo). Dòng footer disclaimer đã bỏ. */
90
- .home-panel { grid-column: 1; grid-row: 2; }
91
- .home-links { grid-column: 1; grid-row: 3; align-self: end; }
92
  .home-scene {
93
  position: absolute;
94
  inset: 0;
@@ -239,11 +234,11 @@ html, body {
239
  gap: 8px;
240
  color: #fff;
241
  text-decoration: none;
242
- background: linear-gradient(#0068ff, #0052cc);
243
  border-radius: 999px;
244
  padding: 9px 16px;
245
  font: 700 .9rem var(--hm-f-body);
246
- box-shadow: inset 0 0 0 1px rgba(255,255,255,.4), 0 6px 18px -6px #0068ffcc;
247
  }
248
  .home-tele:hover { filter: brightness(1.08); }
249
  .home-install, .home-push { flex: none; }
@@ -271,6 +266,22 @@ html, body {
271
  }
272
  .pwa-glyph { flex: none; }
273
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
  /* ============ TALLY (đếm trong hang) ============ */
275
  .tally {
276
  display: inline-flex;
 
74
  position: relative;
75
  min-height: 100dvh;
76
  display: grid;
77
+ grid-template-rows: auto 1fr auto auto;
78
  align-items: start;
79
  justify-items: center;
80
  gap: 10px;
 
84
  radial-gradient(120% 90% at 50% 0%, #2b1d12 0%, #140f0c 70%),
85
  #120b08;
86
  }
 
 
 
 
 
87
  .home-scene {
88
  position: absolute;
89
  inset: 0;
 
234
  gap: 8px;
235
  color: #fff;
236
  text-decoration: none;
237
+ background: linear-gradient(#2aabee, #1b8bc2);
238
  border-radius: 999px;
239
  padding: 9px 16px;
240
  font: 700 .9rem var(--hm-f-body);
241
+ box-shadow: inset 0 0 0 1px rgba(255,255,255,.4), 0 6px 18px -6px #229ed9cc;
242
  }
243
  .home-tele:hover { filter: brightness(1.08); }
244
  .home-install, .home-push { flex: none; }
 
266
  }
267
  .pwa-glyph { flex: none; }
268
 
269
+ /* ============ HOME FOOTER ============ */
270
+ .home-footer {
271
+ z-index: 1;
272
+ text-align: center;
273
+ color: rgba(243,231,216,.55);
274
+ font-size: .78rem;
275
+ line-height: 1.5;
276
+ padding: 0 12px;
277
+ }
278
+ .home-footer .legal-link {
279
+ color: rgba(243,231,216,.75);
280
+ text-decoration: underline;
281
+ background: none; border: 0; cursor: pointer;
282
+ font: inherit;
283
+ }
284
+
285
  /* ============ TALLY (đếm trong hang) ============ */
286
  .tally {
287
  display: inline-flex;
frontend/styles/playlist.css DELETED
@@ -1,176 +0,0 @@
1
- /* =========================================================================
2
- V116 — CSS cho PLAYLIST MÀN HÌNH LỚN (nút mở/đóng danh sách video)
3
- -------------------------------------------------------------------------
4
- VÌ SAO CẦN FILE NÀY:
5
- Trước V116, BoardVideoOverlay render <div className="board-playbar">
6
- nhưng KHÔNG có một dòng CSS nào cho .board-playbar trong cả 5 file
7
- stylesheet được phục vụ (heritage, main, cavescreen, home, slab).
8
- Hệ quả: danh sách video LUÔN hiện, không style, đè lên màn hình 3D.
9
-
10
- V116 đổi thành: một NÚT .board-playbar-toggle, danh sách là PANEL ẨN chỉ
11
- hiện khi có class .is-open (React state playbarOpen trong app.js).
12
-
13
- LƯU Ý KIẾN TRÚC (quan trọng, đừng sửa lại):
14
- frontend/styles/* được COPY THẲNG từ source repo vào image runtime
15
- (`COPY frontend/styles ./frontend/styles`), KHÔNG đi qua build stage.
16
- Vì vậy CSS phải nằm ở FILE TRONG REPO (như file này), không được sinh
17
- ra lúc build — xem lại bài học v82.
18
- ========================================================================= */
19
-
20
- /* ---------------- NÚT MỞ / ĐÓNG ---------------- */
21
- .board-playbar-toggle {
22
- position: fixed;
23
- left: max(14px, env(safe-area-inset-left));
24
- bottom: max(14px, env(safe-area-inset-bottom));
25
- z-index: 900;
26
- display: inline-flex;
27
- align-items: center;
28
- gap: 7px;
29
- appearance: none;
30
- cursor: pointer;
31
- color: #fff4e6;
32
- background: linear-gradient(180deg, rgba(38, 24, 14, .96), rgba(20, 13, 8, .96));
33
- border: 1px solid rgba(236, 208, 140, .55);
34
- border-radius: 999px;
35
- padding: 9px 15px;
36
- font: 700 .8rem/1 "Be Vietnam Pro", system-ui, sans-serif;
37
- box-shadow: 0 8px 22px -10px #000c, inset 0 1px rgba(255, 255, 255, .09);
38
- transition: background .15s ease, transform .12s ease, border-color .15s ease;
39
- }
40
- .board-playbar-toggle:hover {
41
- background: linear-gradient(180deg, rgba(52, 33, 18, .98), rgba(28, 18, 11, .98));
42
- border-color: rgba(236, 208, 140, .9);
43
- }
44
- .board-playbar-toggle:active { transform: scale(.96); }
45
- .board-playbar-toggle:focus-visible {
46
- outline: 2px solid #ffd76a;
47
- outline-offset: 3px;
48
- }
49
- .board-playbar-toggle.is-active {
50
- border-color: #ffd76a;
51
- background: linear-gradient(180deg, rgba(200, 16, 46, .96), rgba(120, 8, 26, .96));
52
- }
53
- .board-playbar-toggle-label {
54
- white-space: nowrap;
55
- }
56
- /* trên máy nhỏ, chữ "Playlist" thu lại, chỉ còn icon cho gọn */
57
- @media (max-width: 420px) {
58
- .board-playbar-toggle { padding: 9px 12px; }
59
- .board-playbar-toggle-label { display: none; }
60
- }
61
-
62
- /* ---------------- PANEL DANH SÁCH (ẨN mặc định) ---------------- */
63
- .board-playbar {
64
- /* ẨN HOÀN TOÀN khi chưa bấm nút — đây chính là yêu cầu (5). */
65
- display: none;
66
- position: fixed;
67
- left: max(14px, env(safe-area-inset-left));
68
- /* nằm NGAY TRÊN nút, không đè joystick ở đáy màn hình */
69
- bottom: calc(max(14px, env(safe-area-inset-bottom)) + 52px);
70
- z-index: 899;
71
- width: min(340px, calc(100vw - 28px));
72
- max-height: min(52vh, 380px);
73
- overflow-y: auto;
74
- overscroll-behavior: contain;
75
- -webkit-overflow-scrolling: touch;
76
- padding: 10px;
77
- color: #efe9dd;
78
- background: rgba(14, 10, 8, .96);
79
- border: 1px solid rgba(236, 208, 140, .45);
80
- border-radius: 14px;
81
- box-shadow: 0 18px 50px -14px #000, inset 0 1px rgba(255, 255, 255, .06);
82
- -webkit-backdrop-filter: blur(8px);
83
- backdrop-filter: blur(8px);
84
- animation: board-playbar-in .16s ease-out both;
85
- }
86
- .board-playbar.is-open { display: block; }
87
-
88
- @keyframes board-playbar-in {
89
- from { opacity: 0; transform: translateY(8px); }
90
- to { opacity: 1; transform: translateY(0); }
91
- }
92
- @media (prefers-reduced-motion: reduce) {
93
- .board-playbar { animation: none; }
94
- }
95
-
96
- .board-playbar-label {
97
- display: block;
98
- margin: 0 0 8px 2px;
99
- color: #ffd76a;
100
- font: 800 .72rem/1.2 "Be Vietnam Pro", system-ui, sans-serif;
101
- letter-spacing: .06em;
102
- text-transform: uppercase;
103
- }
104
-
105
- /* ---------------- TỪNG THẺ VIDEO ---------------- */
106
- .board-playbar-btns {
107
- display: flex;
108
- flex-direction: column;
109
- gap: 7px;
110
- }
111
- .board-playbar-card {
112
- appearance: none;
113
- cursor: pointer;
114
- display: flex;
115
- align-items: center;
116
- gap: 9px;
117
- width: 100%;
118
- padding: 6px 8px;
119
- text-align: left;
120
- color: #efe9dd;
121
- background: rgba(255, 255, 255, .055);
122
- border: 1px solid rgba(236, 208, 140, .16);
123
- border-radius: 10px;
124
- font: 600 .78rem/1.3 "Be Vietnam Pro", system-ui, sans-serif;
125
- transition: background .14s ease, border-color .14s ease;
126
- }
127
- .board-playbar-card:hover {
128
- background: rgba(255, 255, 255, .11);
129
- border-color: rgba(236, 208, 140, .45);
130
- }
131
- .board-playbar-card:focus-visible {
132
- outline: 2px solid #ffd76a;
133
- outline-offset: 2px;
134
- }
135
- /* bài ĐANG phát — cùng tông vàng với bảng vàng điểm danh */
136
- .board-playbar-card.is-playing {
137
- background: rgba(255, 215, 106, .16);
138
- border-color: #ffd76a;
139
- }
140
- .board-playbar-card.is-playing .board-playbar-title { color: #fff6d8; }
141
-
142
- .board-playbar-thumb {
143
- flex: 0 0 auto;
144
- width: 64px;
145
- height: 36px;
146
- border-radius: 6px;
147
- background-color: rgba(0, 0, 0, .55);
148
- background-position: center;
149
- background-size: cover;
150
- background-repeat: no-repeat;
151
- display: inline-flex;
152
- align-items: center;
153
- justify-content: center;
154
- color: #ffd76a;
155
- font: 800 .8rem/1 "Be Vietnam Pro", system-ui, sans-serif;
156
- }
157
-
158
- .board-playbar-title {
159
- flex: 1 1 auto;
160
- min-width: 0;
161
- display: -webkit-box;
162
- -webkit-line-clamp: 2;
163
- -webkit-box-orient: vertical;
164
- overflow: hidden;
165
- color: #efe9dd;
166
- }
167
-
168
- /* ---------------- MÀN HÌNH NHỎ ---------------- */
169
- @media (max-width: 640px) {
170
- .board-playbar {
171
- width: min(300px, calc(100vw - 20px));
172
- max-height: 44vh;
173
- bottom: calc(max(14px, env(safe-area-inset-bottom)) + 110px);
174
- }
175
- .board-playbar-thumb { width: 56px; height: 32px; }
176
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v101.mjs DELETED
@@ -1,76 +0,0 @@
1
- /* patch_v101.mjs — FORCE REMOVE <LegendRing /> + <LegendWall /> + BUMP VERSION
2
- Chạy sau patch_v98, trước esbuild.
3
- Phiên bản 3: dùng string replace trực tiếp, không regex. */
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
-
7
- const ROOT = process.argv[2] || '.';
8
- let n = 0;
9
- const ok = (m) => { n++; console.log('[v101] OK: ' + m); };
10
- const warn = (m) => console.warn('[v101] WARN: ' + m);
11
- const read = (f) => fs.readFileSync(path.join(ROOT, f), 'utf8');
12
- const save = (f, s) => fs.writeFileSync(path.join(ROOT, f), s);
13
- const has = (f) => fs.existsSync(path.join(ROOT, f));
14
-
15
- const F_CAVE = 'frontend/cave3d.js';
16
-
17
- // === 1) GỠ <LegendRing /> — dùng string replace trực tiếp ===
18
- try {
19
- let s = read(F_CAVE);
20
- const before = s.length;
21
-
22
- // Thử nhiều cách xóa
23
- // Cách 1: xóa dòng " <LegendRing />\n"
24
- s = s.replace(' <LegendRing />\n', '');
25
- s = s.replace(' <LegendRing/>\n', '');
26
- s = s.replace(' <LegendRing />\r\n', '');
27
- s = s.replace(' <LegendRing/>\r\n', '');
28
- // Cách 2: xóa với indent khác
29
- s = s.replace(/\n\s*<LegendRing\s*\/>/g, '');
30
- // Cách 3: xóa mọi <LegendRing ... />
31
- s = s.replace(/<LegendRing[^>]*\/>/g, '');
32
- // Cách 4: xóa <LegendRing ...></LegendRing>
33
- s = s.replace(/<LegendRing[^>]*>[\s\S]*?<\/LegendRing>/g, '');
34
-
35
- if (s.length < before) { save(F_CAVE, s); ok('GỠ <LegendRing /> (giảm ' + (before - s.length) + ' bytes)'); }
36
- if (!read(F_CAVE).includes('LegendRing')) ok('Xác nhận: <LegendRing> đã xóa hoàn toàn');
37
- else warn('<LegendRing> VẪN CÒN!');
38
- } catch (e) { warn('LegendRing: ' + e.message); }
39
-
40
- // === 2) GỠ <LegendWall /> ===
41
- try {
42
- let s = read(F_CAVE);
43
- const before = s.length;
44
-
45
- s = s.replace(' <LegendWall />\n', '');
46
- s = s.replace(' <LegendWall/>\n', '');
47
- s = s.replace(' <LegendWall />\r\n', '');
48
- s = s.replace(' <LegendWall/>\r\n', '');
49
- s = s.replace(/\n\s*<LegendWall\s*\/>/g, '');
50
- s = s.replace(/<LegendWall[^>]*\/>/g, '');
51
- s = s.replace(/<LegendWall[^>]*>[\s\S]*?<\/LegendWall>/g, '');
52
-
53
- if (s.length < before) { save(F_CAVE, s); ok('GỠ <LegendWall /> (giảm ' + (before - s.length) + ' bytes)'); }
54
- if (!read(F_CAVE).includes('LegendWall')) ok('Xác nhận: <LegendWall> đã xóa hoàn toàn');
55
- else warn('<LegendWall> VẪN CÒN!');
56
- } catch (e) { warn('LegendWall: ' + e.message); }
57
-
58
- // === 3) BUMP VERSION → v101 + cache-bust ?v=101 ===
59
- try {
60
- const b = read('backend.py');
61
- const nb = b.replace(/VERSION_ID = "v\d+"/, 'VERSION_ID = "v101"');
62
- if (nb !== b) { save('backend.py', nb); ok('backend.py: VERSION_ID -> v101'); }
63
- else ok('backend.py: VERSION_ID đã là v101 (idem)');
64
- } catch (e) { warn('version: ' + e.message); }
65
-
66
- for (const ip of ['frontend/index.html', 'index.html']) {
67
- if (!has(ip)) continue;
68
- try {
69
- const h = read(ip);
70
- const nh = h.replace(/\?v=\d+/g, '?v=101');
71
- if (nh !== h) { save(ip, nh); ok(ip + ': cache-bust ?v=101'); }
72
- else ok(ip + ': cache-bust đã là ?v=101 (idem)');
73
- } catch (e) { warn(ip + ': ' + e.message); }
74
- }
75
-
76
- console.log('[v101] DONE: ' + n + ' muc');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v102.mjs DELETED
@@ -1,170 +0,0 @@
1
- /* patch_v102.mjs — DEFINITIVE FIX: xóa <LegendRing /> và <LegendWall />
2
- Chạy CUỐI CÙNG sau patch_v101, trước esbuild.
3
- Phiên bản 4: đọc file, tìm chính xác chuỗi, xóa, ghi lại. */
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
-
7
- const ROOT = process.argv[2] || '.';
8
- const read = (f) => fs.readFileSync(path.join(ROOT, f), 'utf8');
9
- const save = (f, s) => fs.writeFileSync(path.join(ROOT, f), s);
10
- const log = (m) => console.log('[v102] ' + m);
11
-
12
- const F_CAVE = 'frontend/cave3d.js';
13
-
14
- let s = read(F_CAVE);
15
- const origLen = s.length;
16
- log('File length before: ' + origLen);
17
-
18
- // === XÓA <LegendRing /> ===
19
- // Tìm tất cả vị trí
20
- let idx = 0;
21
- let removed = 0;
22
- while ((idx = s.indexOf('<LegendRing')) !== -1) {
23
- log('Found <LegendRing at offset ' + idx + ': ' + JSON.stringify(s.substring(idx, idx + 60)));
24
- // Tìm ký tự / hoặc > đóng thẻ
25
- let end = idx + 1;
26
- let depth = 0;
27
- let inQuote = false;
28
- let quoteChar = '';
29
- for (; end < s.length; end++) {
30
- const ch = s[end];
31
- if (inQuote) {
32
- if (ch === quoteChar && s[end-1] !== '\\') inQuote = false;
33
- } else {
34
- if (ch === '"' || ch === "'") { inQuote = true; quoteChar = ch; }
35
- else if (ch === '>') {
36
- // Check if self-closing (previous non-whitespace char is /)
37
- let prev = end - 1;
38
- while (prev > idx && (s[prev] === ' ' || s[prev] === '\t' || s[prev] === '\n' || s[prev] === '\r')) prev--;
39
- if (s[prev] === '/') {
40
- // Self-closing: <LegendRing ... />
41
- // Also remove trailing newline
42
- let removeEnd = end + 1;
43
- if (s[removeEnd] === '\r') removeEnd++;
44
- if (s[removeEnd] === '\n') removeEnd++;
45
- s = s.substring(0, idx) + s.substring(removeEnd);
46
- removed++;
47
- log('Removed self-closing <LegendRing />');
48
- break;
49
- } else {
50
- // Opening tag: <LegendRing ...>
51
- // Find matching </LegendRing>
52
- const closeIdx = s.indexOf('</LegendRing>', end + 1);
53
- if (closeIdx !== -1) {
54
- let removeEnd = closeIdx + '</LegendRing>'.length;
55
- if (s[removeEnd] === '\r') removeEnd++;
56
- if (s[removeEnd] === '\n') removeEnd++;
57
- s = s.substring(0, idx) + s.substring(removeEnd);
58
- removed++;
59
- log('Removed <LegendRing>...</LegendRing>');
60
- break;
61
- } else {
62
- // No closing tag found, skip past this tag
63
- end++;
64
- break;
65
- }
66
- }
67
- }
68
- }
69
- }
70
- if (end >= s.length) break;
71
- }
72
-
73
- if (removed > 0) {
74
- save(F_CAVE, s);
75
- log('Removed ' + removed + ' <LegendRing> occurrences');
76
- }
77
-
78
- // === XÓA <LegendWall /> ===
79
- idx = 0;
80
- removed = 0;
81
- while ((idx = s.indexOf('<LegendWall')) !== -1) {
82
- log('Found <LegendWall at offset ' + idx + ': ' + JSON.stringify(s.substring(idx, idx + 60)));
83
- let end = idx + 1;
84
- let depth = 0;
85
- let inQuote = false;
86
- let quoteChar = '';
87
- for (; end < s.length; end++) {
88
- const ch = s[end];
89
- if (inQuote) {
90
- if (ch === quoteChar && s[end-1] !== '\\') inQuote = false;
91
- } else {
92
- if (ch === '"' || ch === "'") { inQuote = true; quoteChar = ch; }
93
- else if (ch === '>') {
94
- let prev = end - 1;
95
- while (prev > idx && (s[prev] === ' ' || s[prev] === '\t' || s[prev] === '\n' || s[prev] === '\r')) prev--;
96
- if (s[prev] === '/') {
97
- let removeEnd = end + 1;
98
- if (s[removeEnd] === '\r') removeEnd++;
99
- if (s[removeEnd] === '\n') removeEnd++;
100
- s = s.substring(0, idx) + s.substring(removeEnd);
101
- removed++;
102
- log('Removed self-closing <LegendWall />');
103
- break;
104
- } else {
105
- const closeIdx = s.indexOf('</LegendWall>', end + 1);
106
- if (closeIdx !== -1) {
107
- let removeEnd = closeIdx + '</LegendWall>'.length;
108
- if (s[removeEnd] === '\r') removeEnd++;
109
- if (s[removeEnd] === '\n') removeEnd++;
110
- s = s.substring(0, idx) + s.substring(removeEnd);
111
- removed++;
112
- log('Removed <LegendWall>...</LegendWall>');
113
- break;
114
- } else {
115
- end++;
116
- break;
117
- }
118
- }
119
- }
120
- }
121
- }
122
- if (end >= s.length) break;
123
- }
124
-
125
- if (removed > 0) {
126
- save(F_CAVE, s);
127
- log('Removed ' + removed + ' <LegendWall> occurrences');
128
- }
129
-
130
- // === VERIFY ===
131
- s = read(F_CAVE);
132
- const hasRing = s.includes('LegendRing');
133
- const hasWall = s.includes('LegendWall');
134
- log('After patch: hasLegendRing=' + hasRing + ', hasLegendWall=' + hasWall);
135
- log('File length after: ' + s.length + ' (delta: ' + (origLen - s.length) + ' bytes)');
136
-
137
- if (!hasRing && !hasWall) {
138
- log('✅ SUCCESS: LegendRing and LegendWall completely removed');
139
- } else {
140
- log('❌ WARNING: LegendRing or LegendWall still present!');
141
- // Debug: show context
142
- if (hasRing) {
143
- const i = s.indexOf('<LegendRing');
144
- log('LegendRing context: ' + JSON.stringify(s.substring(Math.max(0, i-30), i + 80)));
145
- }
146
- if (hasWall) {
147
- const i = s.indexOf('<LegendWall');
148
- log('LegendWall context: ' + JSON.stringify(s.substring(Math.max(0, i-30), i + 80)));
149
- }
150
- }
151
-
152
- // === BUMP VERSION ===
153
- try {
154
- const b = read('backend.py');
155
- const nb = b.replace(/VERSION_ID = "v\d+"/, 'VERSION_ID = "v102"');
156
- if (nb !== b) { save('backend.py', nb); log('backend.py: VERSION_ID -> v102'); }
157
- else log('backend.py: VERSION_ID already v102');
158
- } catch (e) { log('version: ' + e.message); }
159
-
160
- for (const ip of ['frontend/index.html', 'index.html']) {
161
- if (!fs.existsSync(path.join(ROOT, ip))) continue;
162
- try {
163
- const h = read(ip);
164
- const nh = h.replace(/\?v=\d+/g, '?v=102');
165
- if (nh !== h) { save(ip, nh); log(ip + ': cache-bust ?v=102'); }
166
- else log(ip + ': cache-bust already ?v=102');
167
- } catch (e) { log(ip + ': ' + e.message); }
168
- }
169
-
170
- log('DONE');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v103.mjs DELETED
@@ -1,187 +0,0 @@
1
- /* patch_v103.mjs — BYTE-LEVEL FIX: xóa <LegendRing /> và <LegendWall />
2
- Chạy CUỐI CÙNG sau patch_v102, trước esbuild.
3
- Đọc file dưới dạng buffer, tìm byte chính xác, xóa, ghi lại. */
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
-
7
- const ROOT = process.argv[2] || '.';
8
- const log = (m) => console.log('[v103] ' + m);
9
-
10
- const F_CAVE = 'frontend/cave3d.js';
11
- const filePath = path.join(ROOT, F_CAVE);
12
-
13
- // Read as buffer
14
- const buf = fs.readFileSync(filePath);
15
- log('File size: ' + buf.length + ' bytes');
16
-
17
- // Convert to string (utf8)
18
- let s = buf.toString('utf8');
19
- const origLen = s.length;
20
-
21
- // === TÌM VÀ XÓA <LegendRing ===
22
- // Tìm tất cả vị trí
23
- let pos = 0;
24
- let count = 0;
25
- while (true) {
26
- const idx = s.indexOf('<LegendRing', pos);
27
- if (idx === -1) break;
28
- log('Found <LegendRing at char offset ' + idx + ': ' + JSON.stringify(s.substring(idx, idx + 70)));
29
-
30
- // Tìm > đóng thẻ, xử lý cả trường hợp có dấu / trước >
31
- let end = idx + 1;
32
- let inQuote = false;
33
- let quoteChar = '';
34
- let foundEnd = false;
35
- for (; end < s.length; end++) {
36
- const ch = s[end];
37
- if (inQuote) {
38
- if (ch === quoteChar && s[end - 1] !== '\\') inQuote = false;
39
- } else {
40
- if (ch === '"' || ch === "'") { inQuote = true; quoteChar = ch; }
41
- else if (ch === '>') {
42
- // Check nếu là self-closing (có / trước >, bỏ qua whitespace)
43
- let prev = end - 1;
44
- while (prev > idx && /\s/.test(s[prev])) prev--;
45
- if (s[prev] === '/') {
46
- // Self-closing: <LegendRing ... />
47
- let removeEnd = end + 1;
48
- // Xóa cả newline phía sau
49
- if (s[removeEnd] === '\r') removeEnd++;
50
- if (s[removeEnd] === '\n') removeEnd++;
51
- log('Self-closing at ' + idx + '..' + removeEnd + ', removing');
52
- s = s.substring(0, idx) + s.substring(removeEnd);
53
- count++;
54
- foundEnd = true;
55
- break;
56
- } else {
57
- // Opening tag: <LegendRing ...> — tìm </LegendRing>
58
- const closeIdx = s.indexOf('</LegendRing>', end + 1);
59
- if (closeIdx !== -1) {
60
- let removeEnd = closeIdx + '</LegendRing>'.length;
61
- if (s[removeEnd] === '\r') removeEnd++;
62
- if (s[removeEnd] === '\n') removeEnd++;
63
- log('Block at ' + idx + '..' + removeEnd + ', removing');
64
- s = s.substring(0, idx) + s.substring(removeEnd);
65
- count++;
66
- foundEnd = true;
67
- break;
68
- } else {
69
- // Không tìm thấy closing tag — bỏ qua
70
- log('No closing tag found for <LegendRing at ' + idx + ', skipping past opening tag');
71
- foundEnd = true;
72
- break;
73
- }
74
- }
75
- }
76
- }
77
- }
78
- if (!foundEnd) break;
79
- pos = idx; // Reset pos to check from same position after removal
80
- }
81
-
82
- if (count > 0) {
83
- fs.writeFileSync(filePath, s, 'utf8');
84
- log('Removed ' + count + ' <LegendRing> occurrences');
85
- }
86
-
87
- // === TÌM VÀ XÓA <LegendWall ===
88
- pos = 0;
89
- count = 0;
90
- while (true) {
91
- const idx = s.indexOf('<LegendWall', pos);
92
- if (idx === -1) break;
93
- log('Found <LegendWall at char offset ' + idx + ': ' + JSON.stringify(s.substring(idx, idx + 70)));
94
-
95
- let end = idx + 1;
96
- let inQuote = false;
97
- let quoteChar = '';
98
- let foundEnd = false;
99
- for (; end < s.length; end++) {
100
- const ch = s[end];
101
- if (inQuote) {
102
- if (ch === quoteChar && s[end - 1] !== '\\') inQuote = false;
103
- } else {
104
- if (ch === '"' || ch === "'") { inQuote = true; quoteChar = ch; }
105
- else if (ch === '>') {
106
- let prev = end - 1;
107
- while (prev > idx && /\s/.test(s[prev])) prev--;
108
- if (s[prev] === '/') {
109
- let removeEnd = end + 1;
110
- if (s[removeEnd] === '\r') removeEnd++;
111
- if (s[removeEnd] === '\n') removeEnd++;
112
- log('Self-closing at ' + idx + '..' + removeEnd + ', removing');
113
- s = s.substring(0, idx) + s.substring(removeEnd);
114
- count++;
115
- foundEnd = true;
116
- break;
117
- } else {
118
- const closeIdx = s.indexOf('</LegendWall>', end + 1);
119
- if (closeIdx !== -1) {
120
- let removeEnd = closeIdx + '</LegendWall>'.length;
121
- if (s[removeEnd] === '\r') removeEnd++;
122
- if (s[removeEnd] === '\n') removeEnd++;
123
- log('Block at ' + idx + '..' + removeEnd + ', removing');
124
- s = s.substring(0, idx) + s.substring(removeEnd);
125
- count++;
126
- foundEnd = true;
127
- break;
128
- } else {
129
- log('No closing tag found for <LegendWall at ' + idx + ', skipping past opening tag');
130
- foundEnd = true;
131
- break;
132
- }
133
- }
134
- }
135
- }
136
- }
137
- if (!foundEnd) break;
138
- pos = idx;
139
- }
140
-
141
- if (count > 0) {
142
- fs.writeFileSync(filePath, s, 'utf8');
143
- log('Removed ' + count + ' <LegendWall> occurrences');
144
- }
145
-
146
- // === VERIFY ===
147
- const final = fs.readFileSync(filePath, 'utf8');
148
- const hasRing = final.includes('LegendRing');
149
- const hasWall = final.includes('LegendWall');
150
- log('After: hasLegendRing=' + hasRing + ', hasLegendWall=' + hasWall);
151
- log('Char length: ' + origLen + ' -> ' + final.length + ' (delta: ' + (origLen - final.length) + ')');
152
-
153
- if (!hasRing && !hasWall) {
154
- log('✅ SUCCESS: LegendRing and LegendWall completely removed');
155
- } else {
156
- log('❌ WARNING: Still present!');
157
- // Show context
158
- if (hasRing) {
159
- const i = final.indexOf('<LegendRing');
160
- log('Ring context: ' + JSON.stringify(final.substring(Math.max(0, i-20), i + 60)));
161
- }
162
- if (hasWall) {
163
- const i = final.indexOf('<LegendWall');
164
- log('Wall context: ' + JSON.stringify(final.substring(Math.max(0, i-20), i + 60)));
165
- }
166
- }
167
-
168
- // === BUMP VERSION ===
169
- try {
170
- const b = fs.readFileSync(path.join(ROOT, 'backend.py'), 'utf8');
171
- const nb = b.replace(/VERSION_ID = "v\d+"/, 'VERSION_ID = "v103"');
172
- if (nb !== b) { fs.writeFileSync(path.join(ROOT, 'backend.py'), nb, 'utf8'); log('backend.py: VERSION_ID -> v103'); }
173
- else log('backend.py: VERSION_ID already v103');
174
- } catch (e) { log('version: ' + e.message); }
175
-
176
- for (const ip of ['frontend/index.html', 'index.html']) {
177
- const fp = path.join(ROOT, ip);
178
- if (!fs.existsSync(fp)) continue;
179
- try {
180
- const h = fs.readFileSync(fp, 'utf8');
181
- const nh = h.replace(/\?v=\d+/g, '?v=103');
182
- if (nh !== h) { fs.writeFileSync(fp, nh, 'utf8'); log(ip + ': cache-bust ?v=103'); }
183
- else log(ip + ': cache-bust already ?v=103');
184
- } catch (e) { log(ip + ': ' + e.message); }
185
- }
186
-
187
- log('DONE');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v108.mjs DELETED
@@ -1,6 +0,0 @@
1
- // V108: NO-OP. patch_v100 da lam tat ca 4 thay doi:
2
- // 1) Ao vang + logo V.AI STUDIO (yellowKitTex + isYellowKit)
3
- // 2) Tay gon + lich su (9 muc)
4
- // 3) Dung yen khong chay (moving guard)
5
- // File nay giu lai de Docker build khong fail khi goi node patch_v108.mjs.
6
- console.log('[V108] SKIP: patch_v100 da ap dung 4 thay doi (ao vang + tay gon + dung yen). Khong can lam gi them.')
 
 
 
 
 
 
 
patch_v109.mjs DELETED
@@ -1,324 +0,0 @@
1
- /* patch_v109.mjs — V109. Chay TRONG Docker build: SAU patch_v103.mjs, TRUOC esbuild.
2
- -------------------------------------------------------------------------
3
- (1) NHAN VAT: AO VANG + LOGO "V.AI STUDIO" SAU AO.
4
- patch_v98 de MAC DINH la ao DO MU:
5
- isMuKit = (p.kit == null) || color === '#c8102e' -> muKitTex() (do)
6
- isYellowKit = color === '#fdbd10' -> chi khi tu chon kit
7
- => mac dinh KHONG BAO GIO thay ao vang. V109: p.kit == null -> VANG.
8
- Logo KHONG the ve trong texture than ao: UV capsule trai u quanh CHU VI,
9
- nen mot hinh tron o "nua duoi canvas" thanh VANH quanh BUNG, khong phai
10
- sau lung. V109 dan MOT MAT PHANG rieng, dat CUNG CHO va CUNG PHIA voi
11
- "so ao sau lung" cua chinh repo nay (plane z = -0.31 trong PlayerAvatar,
12
- phia huong ve camera third-person), va GOP so ao + logo vao 1 texture de
13
- khong de len nhau.
14
-
15
- (2) TAY GON, LICH SU. patch_v98 thu vai 0.34 -> 0.285 trong khi ban kinh than
16
- ao = 0.30 nen tay LAN VAO THAN, mat ranh gioi tay/ao. V109 dat vai 0.335:
17
- o cao do ban kinh than ~0.27, tay r 0.058 => mep trong 0.277 sat vai, mep
18
- ngoai 0.393 lo ra ro rang. Bap tay / cang tay / ban tay thu nho them.
19
-
20
- (3) DUNG YEN = KHONG CO DONG TAC CHAY. patch_v98 chi dua vao p.anim. Nhung
21
- p.anim cua nguoi KHAC do server gui, va Movement chi goi Net.update khi
22
- pos/rot/anim DOI -> dung yen thi server KHONG gui lai 'idle' -> avatar ho
23
- dung yen van chay tay chan mai. V109 do DICH CHUYEN THAT cua p.pos moi
24
- khung hinh: <= 0.012 world => A = 0 => tay/chan ve 0, khong nhun.
25
- Dung cho ca minh va nguoi khac.
26
-
27
- (4) BO TAM BANG TRONG + 3 BONG DEN + MAI BAN NGUYET truoc bang ghe.
28
- Do la <VaiEntranceStele /> (patch_v91) dat [0,-0.7,-22] — NGAY TRUOC bang
29
- ghe (BENCHES: z = -37 .. -26.6) — co MAI VOM BAN NGUYET
30
- torusGeometry args={[W_/2 + 0.35, 0.34, 8, 24, Math.PI]} va 3 BONG DEN
31
- (2 sphere lamp hai ben + 1 pointLight hat mat bia). patch_v93/95 chi sua
32
- BIA NGOAI SAN (home3d.js) chu KHONG go cho mount trong hang -> no van nam
33
- do. V109 go han cho MOUNT <VaiEntranceStele />, giu lai dinh nghia
34
- component de khong vo tham chieu nao.
35
- KHONG dong toi <Board /> (man hinh lon phat video) — co guard rieng.
36
-
37
- AN TOAN: backup app.js + cave3d.js; sau khi sua thi VALIDATE bang chinh
38
- esbuild (loader jsx) + guard bundle markers. Neu bat ky loi -> RESTORE ban
39
- truoc va exit 0. Nghia la anchor lech KHONG BAO GIO lam sap Space.
40
- ------------------------------------------------------------------------- */
41
- import fs from 'node:fs'
42
- import path from 'node:path'
43
-
44
- const ROOT = process.argv[2] || '.'
45
- let n = 0
46
- const ok = (m) => { n++; console.log('[v109] OK: ' + m) }
47
- const warn = (m) => console.warn('[v109] WARN: ' + m)
48
- const P = (...a) => path.join(ROOT, ...a)
49
- const has = (f) => fs.existsSync(P(f))
50
- const read = (f) => fs.readFileSync(P(f), 'utf8')
51
- const save = (f, s) => fs.writeFileSync(P(f), s)
52
- const Q = String.fromCharCode(34)
53
-
54
- const BAK = {}
55
- for (const f of ['frontend/app.js', 'frontend/cave3d.js']) if (has(f)) BAK[f] = read(f)
56
-
57
- function cutFn(src, name) {
58
- const m = new RegExp('function\\s+' + name + '\\s*\\([^)]*\\)\\s*\\{').exec(src)
59
- if (!m) return null
60
- const start = src.indexOf('{', m.index)
61
- let d = 0
62
- for (let k = start; k < src.length; k++) {
63
- if (src[k] === '{') d++
64
- else if (src[k] === '}') { d--; if (d === 0) return [m.index, k + 1] }
65
- }
66
- return null
67
- }
68
-
69
- /* ============ 1) AO VANG MAC DINH + LOGO SAU AO ============ */
70
- try {
71
- const f = 'frontend/app.js'
72
- if (!has(f)) throw new Error('app.js missing')
73
- let s = read(f)
74
- let hit = 0
75
-
76
- const U1 = " const isMuKit = (p.kit == null) || color === '#c8102e'\n const isYellowKit = color === '#fdbd10'"
77
- const U1N = [
78
- ' /* V109: MAC DINH = AO VANG V.AI STUDIO (khong con ao do MU). */',
79
- " const isYellowKit = (p.kit == null) || color === '#fdbd10'",
80
- " const isMuKit = (p.kit != null) && color === '#c8102e'",
81
- ].join('\n')
82
- if (s.includes('V109: MAC DINH = AO VANG')) ok('app.js: mac dinh ao vang (idem)')
83
- else if (s.includes(U1)) { s = s.replace(U1, U1N); hit++; ok('app.js: MAC DINH -> AO VANG') }
84
- else warn('app.js: KHONG THAY khoi isMuKit/isYellowKit')
85
-
86
- const MAPO = 'map={isMuKit ? muKitTex() : (isYellowKit ? yellowKitTex() : null)}'
87
- const MAPN = 'map={isYellowKit ? yellowKitTex() : (isMuKit ? muKitTex() : null)}'
88
- if (s.includes(MAPO)) { s = s.split(MAPO).join(MAPN); hit++; ok('app.js: than ao -> yellowKitTex uu tien') }
89
- else if (s.includes(MAPN)) ok('app.js: than ao uu tien yellowKitTex (idem)')
90
- else warn('app.js: KHONG THAY map than ao')
91
-
92
- /* CHI doi color THAN AO (material co metalness={0.08}). Tay ao la material
93
- khac, KHONG co metalness — doi ca tay sang trang se lam tay bi trang. */
94
- const CO = "color={isMuKit ? '#c8102e' : (isYellowKit ? '#f5c518' : color)} roughness={0.72} metalness={0.08}"
95
- const CN = "color={isYellowKit ? '#ffffff' : (isMuKit ? '#c8102e' : color)} roughness={0.72} metalness={0.08}"
96
- if (s.includes(CO)) { s = s.split(CO).join(CN); hit++; ok('app.js: than ao color -> #ffffff (khong nhan doi mau)') }
97
- else if (s.includes(CN)) ok('app.js: than ao color da la #ffffff (idem)')
98
- else warn('app.js: KHONG THAY color than ao')
99
-
100
- if (s.includes('const _YKit = { _tex: null }')) {
101
- s = s.replace(/^[ \t]*const _YKit = \{ _tex: null \}[ \t]*\r?\n/gm, '')
102
- hit++
103
- ok('app.js: go khai bao _YKit cu (tranh trung lap const)')
104
- }
105
-
106
- const YK = [
107
- '/* V109: AO VANG V.AI STUDIO — texture than ao. Capsule UV: u trai quanh',
108
- ' CHU VI, v theo CHIEU CAO => CHI ve dai NGANG (co ao tren, gau ao duoi)',
109
- ' + van doc lap lai deu. Khong ve hinh tron / chu dat lech: se thanh vanh',
110
- ' quanh BUNG chu khong phai sau lung. Logo nam o backPlateTex (duoi). */',
111
- 'const _YKit = { _tex: null }',
112
- 'function yellowKitTex() {',
113
- ' if (_YKit._tex) return _YKit._tex',
114
- ' const c = document.createElement(' + Q + 'canvas' + Q + '); c.width = 256; c.height = 320',
115
- ' const g = c.getContext(' + Q + '2d' + Q + ')',
116
- ' const gr = g.createLinearGradient(0, 0, 0, 320)',
117
- ' gr.addColorStop(0, ' + Q + '#ffdf4f' + Q + '); gr.addColorStop(0.5, ' + Q + '#f5c518' + Q + '); gr.addColorStop(1, ' + Q + '#d9a800' + Q + ')',
118
- ' g.fillStyle = gr; g.fillRect(0, 0, 256, 320)',
119
- ' g.fillStyle = ' + Q + 'rgba(255,255,255,0.07)' + Q,
120
- ' for (let xi = 0; xi < 256; xi += 32) g.fillRect(xi, 0, 14, 320)',
121
- ' g.fillStyle = ' + Q + '#1f2937' + Q + '; g.fillRect(0, 0, 256, 26)',
122
- ' g.fillStyle = ' + Q + '#f7f4ec' + Q + '; g.fillRect(0, 26, 256, 7)',
123
- ' g.fillStyle = ' + Q + '#1f2937' + Q + '; g.fillRect(0, 306, 256, 14)',
124
- ' g.fillStyle = ' + Q + '#f7f4ec' + Q + '; g.fillRect(0, 298, 256, 7)',
125
- ' const t = new THREE.CanvasTexture(c)',
126
- ' t.colorSpace = THREE.SRGBColorSpace',
127
- ' t.anisotropy = 8; t.needsUpdate = true',
128
- ' _YKit._tex = t',
129
- ' return t',
130
- '}',
131
- '',
132
- '/* V109: MAT SAU AO — GOP "so ao" + logo "V.AI STUDIO" vao MOT texture de',
133
- ' khong de len nhau. Cung toa do z (-0.31) va cung phia voi plane so ao cu',
134
- ' trong PlayerAvatar (phia huong ve camera third-person). */',
135
- 'const _backTexCache = {}',
136
- 'function backPlateTex(number) {',
137
- ' const key = number == null ? ' + Q + 'none' + Q + ' : String(number)',
138
- ' if (_backTexCache[key]) return _backTexCache[key]',
139
- ' const c = document.createElement(' + Q + 'canvas' + Q + '); c.width = 256; c.height = 256',
140
- ' const g = c.getContext(' + Q + '2d' + Q + ')',
141
- ' g.clearRect(0, 0, 256, 256)',
142
- ' g.fillStyle = ' + Q + 'rgba(20,24,30,0.92)' + Q,
143
- ' g.beginPath()',
144
- ' if (g.roundRect) { g.roundRect(16, 16, 224, 224, 34); g.fill() }',
145
- ' else { g.rect(16, 16, 224, 224); g.fill() }',
146
- ' g.strokeStyle = ' + Q + '#ffe863' + Q + '; g.lineWidth = 7',
147
- ' g.beginPath()',
148
- ' if (g.roundRect) { g.roundRect(16, 16, 224, 224, 34); g.stroke() }',
149
- ' else { g.rect(16, 16, 224, 224); g.stroke() }',
150
- ' g.textAlign = ' + Q + 'center' + Q + '; g.textBaseline = ' + Q + 'middle' + Q,
151
- ' if (number != null && String(number) !== ' + Q + Q + ') {',
152
- ' g.font = ' + Q + '900 116px Arial, sans-serif' + Q,
153
- ' g.lineWidth = 12; g.strokeStyle = ' + Q + '#0b0f14' + Q,
154
- ' g.strokeText(String(number), 128, 104)',
155
- ' g.fillStyle = ' + Q + '#ffffff' + Q,
156
- ' g.fillText(String(number), 128, 104)',
157
- ' g.fillStyle = ' + Q + '#ffe863' + Q,
158
- ' g.font = ' + Q + '900 40px sans-serif' + Q,
159
- ' g.fillText(' + Q + 'V.AI' + Q + ', 128, 180)',
160
- ' g.fillStyle = ' + Q + '#f7f4ec' + Q,
161
- ' g.font = ' + Q + '800 20px sans-serif' + Q,
162
- ' g.fillText(' + Q + 'STUDIO' + Q + ', 128, 210)',
163
- ' } else {',
164
- ' g.fillStyle = ' + Q + '#ffe863' + Q,
165
- ' g.font = ' + Q + '900 76px sans-serif' + Q,
166
- ' g.fillText(' + Q + 'V.AI' + Q + ', 128, 108)',
167
- ' g.fillStyle = ' + Q + '#f7f4ec' + Q,
168
- ' g.font = ' + Q + '800 34px sans-serif' + Q,
169
- ' g.fillText(' + Q + 'STUDIO' + Q + ', 128, 162)',
170
- ' }',
171
- ' const t = new THREE.CanvasTexture(c)',
172
- ' t.colorSpace = THREE.SRGBColorSpace',
173
- ' t.anisotropy = 8; t.needsUpdate = true',
174
- ' _backTexCache[key] = t',
175
- ' return t',
176
- '}',
177
- '',
178
- ].join('\n')
179
-
180
- if (s.includes('function backPlateTex')) ok('app.js: yellowKitTex/backPlateTex (idem)')
181
- else {
182
- const cut = cutFn(s, 'yellowKitTex')
183
- if (!cut) throw new Error('KHONG THAY function yellowKitTex()')
184
- s = s.slice(0, cut[0]) + YK + s.slice(cut[1])
185
- hit++
186
- ok('app.js: yellowKitTex viet lai + them backPlateTex')
187
- }
188
-
189
- const NRE = /[ \t]*\{p\.number != null && \(\r?\n[ \t]*<mesh position=\{\[0, 1\.1, -0\.31\]\} rotation=\{\[0, 0\.1, 0\]\}>\r?\n[ \t]*<planeGeometry args=\{\[0\.5, 0\.5\]\} \/>\r?\n[ \t]*<meshBasicMaterial map=\{useNumTex\(p\.number\)\} transparent \/>\r?\n[ \t]*<\/mesh>\r?\n[ \t]*\)\}/
190
- const NN = [
191
- ' {/* V109: MAT SAU AO — logo "V.AI STUDIO" (+ so ao neu co) trong MOT',
192
- ' texture. Dung toa do va phia cua plane so ao cu (z=-0.31).',
193
- ' DoubleSide de nhin duoc ca khi camera xoay vong. */}',
194
- ' <mesh position={[0, 1.06, -0.315]} rotation={[0, 0.1, 0]}>',
195
- ' <planeGeometry args={[0.46, 0.46]} />',
196
- ' <meshBasicMaterial map={backPlateTex(p.number)} transparent',
197
- ' depthWrite={false} toneMapped={false} side={THREE.DoubleSide} />',
198
- ' </mesh>',
199
- ].join('\n')
200
- if (s.includes('map={backPlateTex(p.number)}')) ok('app.js: mat sau ao (idem)')
201
- else if (NRE.test(s)) { s = s.replace(NRE, NN); hit++; ok('app.js: mat sau ao -> logo + so ao') }
202
- else warn('app.js: KHONG THAY khoi {p.number != null && (...)}')
203
-
204
- let arm = 0
205
- for (const pr of [
206
- ['position={[-0.285, 1.3, 0]}', 'position={[-0.335, 1.3, 0]}'],
207
- ['position={[0.285, 1.3, 0]}', 'position={[0.335, 1.3, 0]}'],
208
- ['args={[0.062, 0.22, 4, 8]}', 'args={[0.058, 0.22, 4, 8]}'],
209
- ['args={[0.048, 0.2, 4, 8]}', 'args={[0.045, 0.2, 4, 8]}'],
210
- ['args={[0.05, 8, 8]}', 'args={[0.048, 8, 8]}'],
211
- ]) if (s.includes(pr[0])) { s = s.split(pr[0]).join(pr[1]); arm++ }
212
- if (arm) { hit++; ok('app.js: TAY gon — vai 0.335 + tay nho (' + arm + ' muc)') }
213
- else ok('app.js: tay da gon (idem)')
214
-
215
- const SOCK = '<meshStandardMaterial color={0xc8102e} roughness={0.8} />'
216
- if (s.includes(SOCK)) {
217
- s = s.split(SOCK).join('<meshStandardMaterial color={0xf2c200} roughness={0.8} />')
218
- hit++
219
- ok('app.js: tat -> vang cho dong bo voi ao')
220
- }
221
-
222
- if (hit) save(f, s)
223
- } catch (e) { warn('app.js: ' + String((e && e.message) || e)) }
224
-
225
- /* ============ 2) DUNG YEN = KHONG CHAY ============ */
226
- try {
227
- const f = 'frontend/app.js'
228
- let s = read(f)
229
- let hit = 0
230
-
231
- if (!s.includes('_vaiLastPos')) {
232
- const R = ' const bob = React.useRef(0)'
233
- if (!s.includes(R)) throw new Error('KHONG THAY const bob = React.useRef(0)')
234
- s = s.replace(R, R + '\n const _vaiLastPos = React.useRef(null)')
235
- hit++
236
- ok('app.js: them _vaiLastPos')
237
- } else ok('app.js: _vaiLastPos (idem)')
238
-
239
- const AO = "const A = p.anim === 'run' ? 14 : (p.anim === 'walk' ? 8 : 0)"
240
- const AN = [
241
- '/* V109: DUNG YEN = KHONG CHAY. Do DICH CHUYEN THAT cua p.pos thay vi tin',
242
- ' p.anim — server chi gui anim khi CO THAY DOI, nen nguoi dung yen khong',
243
- ' bao gio nhan lai idle va tay chan chay mai. */',
244
- ' const _vx = p.pos.x, _vz = p.pos.z',
245
- ' const _vp = _vaiLastPos.current',
246
- ' const _vMoved = !_vp || Math.hypot(_vx - _vp.x, _vz - _vp.z) > 0.012',
247
- ' _vaiLastPos.current = { x: _vx, z: _vz }',
248
- " const A = !_vMoved ? 0 : (p.anim === 'run' ? 14 : (p.anim === 'walk' ? 8 : 0))",
249
- ].join('\n')
250
- if (s.includes(AO)) { s = s.split(AO).join(AN); hit++; ok('app.js: DUNG YEN -> A=0') }
251
- else if (s.includes('const A = !_vMoved ? 0')) ok('app.js: guard dung yen (idem)')
252
- else warn('app.js: KHONG THAY dong tinh A')
253
-
254
- if (hit) save(f, s)
255
- } catch (e) { warn('app.js anim: ' + String((e && e.message) || e)) }
256
-
257
- /* ============ 3) BO TAM BANG TRONG + 3 BONG DEN + MAI BAN NGUYET ============ */
258
- try {
259
- const f = 'frontend/cave3d.js'
260
- if (!has(f)) throw new Error('cave3d.js missing')
261
- let s = read(f)
262
- const b = s.length
263
- s = s.replace(/^[ \t]*<VaiEntranceStele\b[^>]*?\/>[ \t]*\r?\n/gm, '')
264
- s = s.replace(/^[ \t]*<VaiEntranceStele\b[^>]*>[\s\S]*?<\/VaiEntranceStele>[ \t]*\r?\n/gm, '')
265
- if (s.length < b) { save(f, s); ok('cave3d: GO <VaiEntranceStele /> (' + (b - s.length) + 'B)') }
266
- else ok('cave3d: khong con cho mount VaiEntranceStele (idem)')
267
- } catch (e) { warn('cave3d stele: ' + String((e && e.message) || e)) }
268
-
269
- /* ============ 4) GUARD + VALIDATE BANG ESBUILD, loi thi RESTORE ============ */
270
- let restored = false
271
- try {
272
- const bad = []
273
- for (const sp of [
274
- ['frontend/app.js', ['function PlayerAvatar(', '<group ref={rootRef}', 'function yellowKitTex()', 'function backPlateTex(']],
275
- ['frontend/cave3d.js', ['export function CaveScene()', 'export const BOARD = {', '<Board />', 'function Benches(', 'function LegendRing(']],
276
- ]) {
277
- const f = sp[0]
278
- if (!has(f)) continue
279
- const t = read(f)
280
- for (const m of sp[1]) if (!t.includes(m)) bad.push(f + ' thieu: ' + m)
281
- }
282
- const app = read('frontend/app.js')
283
- const cave = read('frontend/cave3d.js')
284
- if ((app.match(/function yellowKitTex\(/g) || []).length !== 1) bad.push('app.js: yellowKitTex != 1 lan')
285
- if ((app.match(/const _YKit = /g) || []).length !== 1) bad.push('app.js: _YKit != 1 lan')
286
-
287
- /* Chi chan cho MOUNT (<VaiEntranceStele ... /> hoac >), KHONG chan dinh nghia
288
- "function VaiEntranceStele(" — ta co y giu lai dinh nghia. */
289
- if (/<VaiEntranceStele[\s/>]/.test(cave)) bad.push('cave3d: van con cho mount <VaiEntranceStele')
290
-
291
- if (bad.length) throw new Error('marker: ' + bad.join(' | '))
292
-
293
- const esbuild = await import('esbuild')
294
- for (const f of ['frontend/app.js', 'frontend/cave3d.js']) {
295
- if (!has(f)) continue
296
- try { await esbuild.transform(read(f), { loader: 'jsx', format: 'esm', target: 'es2020' }) }
297
- catch (err) { throw new Error(f + ' KHONG HOP LE: ' + String((err && err.message) || err).split('\n').slice(0, 3).join(' ')) }
298
- }
299
- ok('esbuild transform OK: app.js + cave3d.js hop le')
300
- } catch (e) {
301
- warn('VALIDATE THAT BAI: ' + String((e && e.message) || e))
302
- for (const f of Object.keys(BAK)) save(f, BAK[f])
303
- restored = true
304
- warn('DA RESTORE ve ban truoc V109 — giao dien cu, build van xanh')
305
- }
306
- if (restored) { console.log('[v109] SKIPPED (restored)'); process.exit(0) }
307
-
308
- /* ============ 5) VERSION + cache-bust ============ */
309
- try {
310
- if (has('backend.py')) {
311
- const b = read('backend.py')
312
- const nb = b.replace(/VERSION_ID = "v\d+"/, 'VERSION_ID = "v109"')
313
- if (nb !== b) { save('backend.py', nb); ok('backend.py: VERSION_ID -> v109') }
314
- }
315
- for (const ip of ['frontend/index.html', 'index.html']) {
316
- if (!has(ip)) continue
317
- const h = read(ip)
318
- const nh = h.replace(/\?v=\d+/g, '?v=109')
319
- if (nh !== h) { save(ip, nh); ok(ip + ': cache-bust -> ?v=109') }
320
- }
321
- } catch (e) { warn('version: ' + String((e && e.message) || e)) }
322
-
323
- console.log('[v109] DONE: ' + n + ' muc ap dung')
324
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v112.mjs DELETED
@@ -1,844 +0,0 @@
1
- /* patch_v112.mjs — V112. Chay TRONG Docker build: SAU patch_v109.mjs, TRUOC esbuild.
2
- =========================================================================
3
- HUONG NHAN VAT / CAMERA — chung minh TU CODE, khong phai doan:
4
-
5
- (1) NHAN VAT QUAY MAT VE +z:
6
- app.js, Movement loop:
7
- rot = Math.atan2(mx, mz)
8
- nx = pos.x + Math.sin(rot) * speed * 0.016
9
- nz = pos.z + Math.cos(rot) * speed * 0.016
10
- => huong "tien" cua nhan vat = (sin rot, cos rot) = +z khi rot = 0.
11
- => MAT huong +z, LUNG huong -z.
12
-
13
- (2) CAMERA O PHIA -z (sau lung):
14
- CameraRig: back = (sin(yaw), 0, cos(yaw)); ideal = target + back*dist
15
- camState.yaw = Math.PI (mac dinh) => back = (0, 0, -1)
16
- => camera dat o target + (0,0,-1)*9 = phia -z, nhin ve +z.
17
- => camera thay LUNG nhan vat. Khop (1).
18
-
19
- (3) XAC NHAN LOI CHU NGUOC:
20
- patch_v109 dat plane so ao + logo o z = -0.315, side = DoubleSide.
21
- Camera o -z nhin vao MAT SAU plane => chu lat nguoc. Dung loi user bao.
22
-
23
- (4) XAC NHAN LOI "KHONG CO MAT":
24
- plane mat goc o z = -0.215 (sau dau, phia camera) nhung material KHONG
25
- co DoubleSide (FrontSide, phap tuyen +z) => camera o -z nhin vao mat sau
26
- => bi cull => VO HINH. Ngoai ra toc goc thetaLength 0.72 PI phu kin tu
27
- dinh xuong QUA duong xich (129.6 do) o moi phi => trum kin ca mat.
28
-
29
- => KET LUAN: so ao / logo / ten (in tren LUNG ao) phai o -z, huong ra -z.
30
- Mat (truoc dau) phai o +z, huong ra +z.
31
-
32
- LOI 1 — CHU BI NGUOC (so ao + "V.AI STUDIO").
33
- => Thay plane phang + DoubleSide bang MAT CONG (cylinderGeometry mot cung
34
- tru) quanh theta = PI.
35
- CylinderGeometry: x = r*sin(theta), z = r*cos(theta)
36
- theta = PI => (0, -r) tuc -z ; phap tuyen huong ra ngoai (-z).
37
- UV: u tang theo theta, tu +x sang -x.
38
- Camera o -z nhin ve +z: right = cross(viewDir, up)
39
- = cross((0,0,1),(0,1,0)) = (-1,0,0) => screen-right = -x
40
- => x duong (u=0) nam ben TRAI khung hinh => chu doc DUNG chieu.
41
- Chi mot mat => khong the lat du xoay kieu gi.
42
-
43
- LOI 2 — KHONG CO MAT.
44
- => Mat = MAT CAU CAT (sphereGeometry) o +z.
45
- SphereGeometry: x = -r*cos(phi)*sin(th), y = r*cos(th),
46
- z = r*sin(phi)*sin(th)
47
- phi = 0.5*PI => +z . th do tu +Y xuong.
48
- Lay phi 0.28..0.72 PI (tam 0.5 PI) va th 0.34..0.64 PI.
49
- => TOC: doi tu cap 0.72 PI (trum kin mat, xuong qua duong xich) thanh cap
50
- 0.30 PI (54 do) chi phu DINH dau, chua lo chan may.
51
-
52
- NOI DUNG V112:
53
- (1) So ao + logo "V.AI STUDIO" tren LUNG ao — mat cong, doc dung chieu.
54
- (2) Bang ten nhan vat in tren LUNG ao, ngay TREN so — mat cong, doc dung.
55
- (3) Mat: long may + long trang + long den + diem sang + MUI + MIENG
56
- (cuoi / noi / chop mat).
57
- (4) CAO THAP CAN DOI: AVATAR_SCALE 1 -> 0.94, dau 0.25 -> 0.24.
58
- Cao 1.91 -> ~1.79 world. KHONG doi Y cua than/co/vai: capsule co chieu
59
- cao tong = length + 2*radius nen giam length khong ha duoc dinh than,
60
- chi lam dau lun vao than hoac ho ra co.
61
- (5) QUAN AO LICH SU: ao polo vang co co ao nau + vien trang + gau ao; quan
62
- nau dam (thay quan den bong); that lung + khoa kim loai; tat kem.
63
- (6) GIANG SINH: thay ngon lua (FirePit) va cup (Trophy) giua hang bang
64
- <ChristmasGrove />: cay thong lon co DEN NHAP NHAY, ngoi sao, bong trang
65
- tri, tat, qua; nguoi tuyet; ong gia Noel. Van giu anh sang am.
66
-
67
- BAN KINH MAT CONG — tinh theo hinh hoc that cua than ao:
68
- than = capsuleGeometry(0.30, 0.26) o y = 1.0
69
- => tong cao 0.26 + 2*0.30 = 0.86 => y 0.57 .. 1.43
70
- => tru y 0.87 .. 1.13, chop cau tam 1.13 ban kinh 0.30
71
- ban kinh than tai y : 0.99 -> 0.300 ; 1.21 -> 0.289
72
- => so ao r = 0.312 tai y = 0.99 (cach 0.012)
73
- ten r = 0.298 tai y = 1.21 (cach 0.009)
74
- Khong dat sat 0.300/0.289 (z-fight); khong dat xa (thanh tam bia lo lung —
75
- dung loi cua v109 voi plane phang rong 0.46 o z = -0.315).
76
-
77
- GUARD: chi dem DONG MOUNT JSX that (^[ \t]*<FirePit ...), vi comment trong
78
- chinh patch nay co nhac ten component. Dem tho se tu fail => tu restore.
79
-
80
- AN TOAN: backup + validate bang esbuild (loader jsx) + guard marker; loi thi
81
- RESTORE ca 2 file va exit 0 => khong bao gio lam sap Space.
82
- ========================================================================= */
83
- import fs from 'node:fs'
84
- import path from 'node:path'
85
-
86
- const ROOT = process.argv[2] || '.'
87
- let n = 0
88
- const ok = (m) => { n++; console.log('[v112] OK: ' + m) }
89
- const warn = (m) => console.warn('[v112] WARN: ' + m)
90
- const P = (...a) => path.join(ROOT, ...a)
91
- const has = (f) => fs.existsSync(P(f))
92
- const read = (f) => fs.readFileSync(P(f), 'utf8')
93
- const save = (f, s) => fs.writeFileSync(P(f), s)
94
-
95
- const BAK = {}
96
- for (const f of ['frontend/app.js', 'frontend/cave3d.js']) if (has(f)) BAK[f] = read(f)
97
-
98
- function cutFn(src, name) {
99
- const m = new RegExp('function\\s+' + name + '\\s*\\([^)]*\\)\\s*\\{').exec(src)
100
- if (!m) return null
101
- const start = src.indexOf('{', m.index)
102
- let d = 0
103
- for (let k = start; k < src.length; k++) {
104
- if (src[k] === '{') d++
105
- else if (src[k] === '}') { d--; if (d === 0) return [m.index, k + 1] }
106
- }
107
- return null
108
- }
109
-
110
- /* =====================================================================
111
- A) app.js — nhan vat
112
- ===================================================================== */
113
- try {
114
- const f = 'frontend/app.js'
115
- if (!has(f)) throw new Error('app.js missing')
116
- let s = read(f)
117
- let hit = 0
118
-
119
- /* ---------- A1. QUAN AO LICH SU: quan den -> nau dam ---------- */
120
- let pn = 0
121
- for (const pr of [
122
- ['<meshStandardMaterial color={0x14141f} roughness={0.85} />',
123
- '<meshStandardMaterial color={0x2b3a55} roughness={0.85} />'],
124
- ['<meshStandardMaterial color={0x14141f} roughness={0.8} metalness={0.1} />',
125
- '<meshStandardMaterial color={0x2b3a55} roughness={0.8} metalness={0.1} />'],
126
- ]) if (s.includes(pr[0])) { s = s.split(pr[0]).join(pr[1]); pn++ }
127
- if (pn) { hit++; ok('app.js: quan den -> nau dam (' + pn + ' muc, lich su hon)') }
128
- else if (s.includes('color={0x2b3a55}')) ok('app.js: quan nau dam (idem)')
129
- else warn('app.js: KHONG THAY mau quan 0x14141f')
130
-
131
- /* tat: v109 doi 0xc8102e -> 0xf2c200 ; V112 -> kem */
132
- if (s.includes('<meshStandardMaterial color={0xf2c200} roughness={0.8} />')) {
133
- s = s.split('<meshStandardMaterial color={0xf2c200} roughness={0.8} />')
134
- .join('<meshStandardMaterial color={0xf0ede6} roughness={0.85} />')
135
- hit++; ok('app.js: tat vang choi -> tat kem (lich su)')
136
- } else if (s.includes('color={0xf0ede6}')) ok('app.js: tat kem (idem)')
137
- else warn('app.js: KHONG THAY tat 0xf2c200')
138
-
139
- /* ---------- A2. THAT LUNG + KHOA KIM LOAI ----------
140
- y = 0.78 nam trong chop cau DUOI cua than ao (tam 0.87, r 0.30)
141
- => ban kinh than tai do = sqrt(0.30^2 - 0.09^2) = 0.2863
142
- dai rong 0.302 => cach 0.016, om sat ma khong z-fight.
143
- khoa o z = -0.301 (phia camera) nen nhin thay ro. */
144
- const HIPKEY = ' <meshStandardMaterial color={0x2b3a55} roughness={0.85} />\n </mesh>'
145
- const BELT = HIPKEY + [
146
- '',
147
- '',
148
- ' {/* V112: THAT LUNG + KHOA KIM LOAI — quan ao lich su hon. */}',
149
- ' <mesh position={[0, 0.78, 0]}>',
150
- ' <cylinderGeometry args={[0.302, 0.302, 0.085, 18]} />',
151
- ' <meshStandardMaterial color="#1b2436" roughness={0.6} metalness={0.25} />',
152
- ' </mesh>',
153
- ' <mesh position={[0, 0.78, -0.301]}>',
154
- ' <boxGeometry args={[0.11, 0.085, 0.03]} />',
155
- ' <meshStandardMaterial color="#c9a24e" roughness={0.35} metalness={0.8} />',
156
- ' </mesh>',
157
- ].join('\n')
158
- if (s.includes('V112: THAT LUNG')) ok('app.js: that lung (idem)')
159
- else if (s.includes(HIPKEY)) { s = s.replace(HIPKEY, BELT); hit++; ok('app.js: them that lung + khoa kim loai') }
160
- else warn('app.js: KHONG THAY khoi HONG de chen that lung')
161
-
162
- /* ---------- A3. TAY AO mau vai polo ---------- */
163
- const SLV = '<meshStandardMaterial color={color} roughness={0.72} />'
164
- if (s.includes(SLV)) {
165
- s = s.split(SLV).join("<meshStandardMaterial color={isYellowKit ? '#f5c518' : color} roughness={0.72} />")
166
- hit++; ok('app.js: tay ao -> vang polo (khong con mau tuy chon)')
167
- } else if (s.includes("isYellowKit ? '#f5c518' : color")) ok('app.js: tay ao vang polo (idem)')
168
- else warn('app.js: KHONG THAY tay ao color={color}')
169
-
170
- /* ---------- A4. CAO THAP CAN DOI ---------- */
171
- if (s.includes('const AVATAR_SCALE = 1\n')) {
172
- s = s.replace('const AVATAR_SCALE = 1\n', 'const AVATAR_SCALE = 0.94\n')
173
- hit++; ok('app.js: AVATAR_SCALE 1 -> 0.94 (cao 1.91 -> 1.79)')
174
- } else if (s.includes('const AVATAR_SCALE = 0.94')) ok('app.js: AVATAR_SCALE 0.94 (idem)')
175
- else warn('app.js: KHONG THAY const AVATAR_SCALE = 1')
176
-
177
- const HEADOLD = [
178
- ' <group ref={headRef} position={[0, 1.66, 0]}>',
179
- ' <mesh castShadow>',
180
- ' <sphereGeometry args={[0.25, 16, 16]} />',
181
- ' <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />',
182
- ' </mesh>',
183
- ].join('\n')
184
- const HEADNEW = [
185
- ' <group ref={headRef} position={[0, 1.66, 0]}>',
186
- ' <mesh castShadow>',
187
- ' <sphereGeometry args={[0.24, 22, 20]} />',
188
- ' <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />',
189
- ' </mesh>',
190
- ].join('\n')
191
- if (s.includes('args={[0.24, 22, 20]}')) ok('app.js: dau 0.24 (idem)')
192
- else if (s.includes(HEADOLD)) { s = s.replace(HEADOLD, HEADNEW); hit++; ok('app.js: dau 0.25 -> 0.24 (can doi hon voi than)') }
193
- else warn('app.js: KHONG THAY khoi DAU')
194
-
195
- /* ---------- A5. AO POLO VANG ---------- */
196
- if (s.includes('const _YKit = { _tex: null }')) {
197
- s = s.replace(/^[ \t]*const _YKit = \{ _tex: null \}[ \t]*\r?\n/gm, '')
198
- }
199
- const YK = `/* V112: AO POLO VANG V.AI STUDIO — lich su, gon gang.
200
- Capsule UV: u trai quanh CHU VI, v theo CHIEU CAO => CHI ve dai NGANG
201
- (co ao tren cung, vien trang, gau ao duoi). Ten + so ao la mat cong rieng. */
202
- const _YKit = { _tex: null }
203
- function yellowKitTex() {
204
- if (_YKit._tex) return _YKit._tex
205
- const c = document.createElement('canvas'); c.width = 256; c.height = 320
206
- const g = c.getContext('2d')
207
- const gr = g.createLinearGradient(0, 0, 0, 320)
208
- gr.addColorStop(0, '#ffe15a'); gr.addColorStop(0.55, '#f5c518'); gr.addColorStop(1, '#e0ad00')
209
- g.fillStyle = gr; g.fillRect(0, 0, 256, 320)
210
- g.fillStyle = 'rgba(255,255,255,0.06)'
211
- for (let xi = 0; xi < 256; xi += 32) g.fillRect(xi, 0, 10, 320)
212
- g.fillStyle = '#22304d'; g.fillRect(0, 0, 256, 34)
213
- g.fillStyle = '#f7f4ec'; g.fillRect(0, 34, 256, 6)
214
- g.fillStyle = 'rgba(255,255,255,0.30)'; g.fillRect(0, 40, 256, 3)
215
- g.fillStyle = '#f7f4ec'; g.fillRect(0, 296, 256, 6)
216
- g.fillStyle = '#22304d'; g.fillRect(0, 302, 256, 18)
217
- const t = new THREE.CanvasTexture(c)
218
- t.colorSpace = THREE.SRGBColorSpace
219
- t.anisotropy = 8; t.needsUpdate = true
220
- _YKit._tex = t
221
- return t
222
- }
223
- `
224
- if (s.includes('V112: AO POLO VANG')) ok('app.js: ao polo vang (idem)')
225
- else {
226
- const cut = cutFn(s, 'yellowKitTex')
227
- if (!cut) {
228
- const anchor = 'function PlayerAvatar({ id, p, isLocal }) {'
229
- if (!s.includes(anchor)) throw new Error('KHONG THAY yellowKitTex / PlayerAvatar')
230
- s = s.replace(anchor, YK + anchor); hit++; ok('app.js: them ao polo vang')
231
- } else { s = s.slice(0, cut[0]) + YK + s.slice(cut[1]); hit++; ok('app.js: ao polo vang (co ao + vien + gau)') }
232
- }
233
-
234
- /* ---------- A6. BANG TEN + SO AO: mat cong o -z (lung ao) ---------- */
235
- const TAG = `/* V112: BANG TEN + SO AO — MAT CONG (cat mot cung tru), KHONG DoubleSide.
236
- Camera third-person o local -z (CameraRig: back = (sin yaw, cos yaw) voi
237
- yaw = PI => camera o -z). CylinderGeometry: x = r*sin(t), z = r*cos(t);
238
- cung quanh t = PI => z < 0 (phia camera), phap tuyen huong ra ngoai.
239
- u tang theo t tu +x sang -x. Camera o -z nhin ve +z co screen-right = -x,
240
- nen x > 0 (u = 0) o ben TRAI khung hinh => chu doc DUNG chieu. */
241
- const _tagCache = {}
242
- function nameTagTex(name) {
243
- const key = 'n|' + String(name || '')
244
- if (_tagCache[key]) return _tagCache[key]
245
- const c = document.createElement('canvas'); c.width = 512; c.height = 128
246
- const g = c.getContext('2d')
247
- g.clearRect(0, 0, 512, 128)
248
- g.fillStyle = 'rgba(22,28,40,0.92)'
249
- g.beginPath()
250
- if (g.roundRect) { g.roundRect(8, 28, 496, 72, 16); g.fill() } else { g.rect(8, 28, 496, 72); g.fill() }
251
- g.strokeStyle = '#ffe863'; g.lineWidth = 5
252
- g.beginPath()
253
- if (g.roundRect) { g.roundRect(8, 28, 496, 72, 16); g.stroke() } else { g.rect(8, 28, 496, 72); g.stroke() }
254
- g.textAlign = 'center'; g.textBaseline = 'middle'
255
- let label = String(name || 'ANH EM')
256
- if (label.length > 16) label = label.slice(0, 15) + String.fromCharCode(8230)
257
- let fs = 52
258
- for (; fs > 20; fs -= 2) { g.font = '800 ' + fs + 'px sans-serif'; if (g.measureText(label).width < 440) break }
259
- g.fillStyle = '#ffffff'
260
- g.fillText(label, 256, 65)
261
- const t = new THREE.CanvasTexture(c)
262
- t.colorSpace = THREE.SRGBColorSpace
263
- t.anisotropy = 8; t.needsUpdate = true
264
- _tagCache[key] = t
265
- return t
266
- }
267
- /* Canvas 320x200 (ti le 1.6) khop cung tru rong r*1.7 = 0.53 x cao 0.33 =>
268
- chu so khong bi keo gian doc. */
269
- function backTagTex(number) {
270
- const key = 'b|' + String(number == null ? '' : number)
271
- if (_tagCache[key]) return _tagCache[key]
272
- const c = document.createElement('canvas'); c.width = 320; c.height = 200
273
- const g = c.getContext('2d')
274
- g.clearRect(0, 0, 320, 200)
275
- g.textAlign = 'center'; g.textBaseline = 'middle'
276
- const got = number != null && String(number) !== ''
277
- if (got) {
278
- g.font = '900 112px Arial, sans-serif'
279
- g.lineWidth = 14; g.strokeStyle = 'rgba(20,26,38,0.5)'
280
- g.strokeText(String(number), 160, 74)
281
- g.fillStyle = '#ffffff'
282
- g.fillText(String(number), 160, 74)
283
- }
284
- g.fillStyle = '#22304d'
285
- g.font = '900 40px sans-serif'
286
- g.fillText('V.AI', 160, got ? 148 : 82)
287
- g.fillStyle = 'rgba(34,48,77,0.92)'
288
- g.font = '800 24px sans-serif'
289
- g.fillText('STUDIO', 160, got ? 176 : 122)
290
- const t = new THREE.CanvasTexture(c)
291
- t.colorSpace = THREE.SRGBColorSpace
292
- t.anisotropy = 8; t.needsUpdate = true
293
- _tagCache[key] = t
294
- return t
295
- }
296
- `
297
- if (s.includes('function nameTagTex(')) ok('app.js: nameTagTex/backTagTex (idem)')
298
- else {
299
- const a1 = 'const _faceTexCache = {}'
300
- const a2 = 'function PlayerAvatar({ id, p, isLocal }) {'
301
- if (s.includes(a1)) { s = s.replace(a1, TAG + a1); hit++; ok('app.js: them nameTagTex + backTagTex') }
302
- else if (s.includes(a2)) { s = s.replace(a2, TAG + a2); hit++; ok('app.js: them nameTagTex + backTagTex') }
303
- else throw new Error('KHONG THAY anchor de chen nameTagTex')
304
- }
305
-
306
- const CONE = ` {/* V112: BANG TEN nhan vat in tren LUNG ao, ngay TREN so — mat cong
307
- quanh theta = PI (-z, phia camera). y = 1.21, ban kinh than 0.289
308
- => dat 0.298. */}
309
- <mesh position={[0, 1.21, 0]}>
310
- <cylinderGeometry args={[0.298, 0.298, 0.075, 24, 1, true, Math.PI - 0.52, 1.04]} />
311
- <meshBasicMaterial map={nameTagTex(p.name)} transparent
312
- depthWrite={false} toneMapped={false} fog={false} />
313
- </mesh>
314
- {/* V112: SO AO + "V.AI STUDIO" in tren LUNG ao — mat cong quanh theta = PI
315
- (-z). y = 0.99, ban kinh than dung 0.300 => dat 0.312.
316
- Chi mot mat huong ra ngoai nen KHONG the lat nguoc (khac plane phang
317
- + DoubleSide cua v109). */}
318
- <mesh position={[0, 0.99, 0]}>
319
- <cylinderGeometry args={[0.312, 0.312, 0.33, 24, 1, true, Math.PI - 0.85, 1.7]} />
320
- <meshBasicMaterial map={backTagTex(p.number)} transparent
321
- depthWrite={false} toneMapped={false} fog={false} />
322
- </mesh>
323
- `
324
- if (s.includes('V112: BANG TEN')) ok('app.js: 2 mat cong ten/so (idem)')
325
- else {
326
- let done = false
327
- const RE109 = /[ \t]*\{\/\* V109: MAT SAU AO[\s\S]*?<\/mesh>\r?\n/
328
- if (RE109.test(s)) { s = s.replace(RE109, CONE); done = true }
329
- if (!done) {
330
- const RE0 = /[ \t]*\{p\.number != null && \(\r?\n[ \t]*<mesh position=\{\[0, 1\.1, -0\.31\]\}[\s\S]*?\r?\n[ \t]*\)\}/
331
- if (RE0.test(s)) { s = s.replace(RE0, CONE); done = true }
332
- }
333
- if (!done) {
334
- const REN = /[ \t]*\{p\.number != null && \([\s\S]*?useNumTex\(p\.number\)[\s\S]*?\)\}/
335
- if (REN.test(s)) { s = s.replace(REN, CONE); done = true }
336
- }
337
- if (done) { hit++; ok('app.js: bang ten + so/logo tren lung (mat cong, het nguoc)') }
338
- else throw new Error('KHONG THAY khoi plane ten/so ao')
339
- }
340
-
341
- /* ---------- A7. MAT: mat cau cat o +z ----------
342
- Dau la cau r = 0.24. Dat mat cau cat r = 0.2455 (noi ra 0.0055, du de
343
- khong z-fight ma khong lo lung).
344
- SphereGeometry: z = r*sin(phi)*sin(th). phi 0.28..0.72 PI (tam 0.5 PI = +z)
345
- th 0.34..0.64 PI => y tu +0.118 den -0.105 so voi tam dau (vung mat). */
346
- const FACEMESH = ` {/* V112: MAT — mat CAU CAT o phia +z (TRUOC dau). Plane cu o z=-0.215
347
- huong +z nen camera o -z nhin vao MAT SAU => bi cull => vo hinh.
348
- Sphere: z = r*sin(phi)*sin(th); phi 0.28..0.72 PI (tam 0.5 PI = +z)
349
- => z > 0, phap tuyen huong +z => hien khi nhin tu truoc.
350
- r = 0.2455 (dau 0.24) => noi ra 0.0055, du chong z-fight. */}
351
- <mesh position={[0, 0.0, 0]}>
352
- <sphereGeometry args={[0.2455, 28, 20, Math.PI * 0.28, Math.PI * 0.44, Math.PI * 0.34, Math.PI * 0.30]} />
353
- <meshBasicMaterial map={makeFaceTex(Math.abs((id || 'x').charCodeAt(0) || 1), 'normal')} transparent depthWrite={false} toneMapped={false} fog={false} />
354
- </mesh>`
355
- if (s.includes('V112: MAT — mat CAU CAT')) ok('app.js: mat cau cat (idem)')
356
- else {
357
- const RE = /[ \t]*\{\/\* mặt: plane trước đầu[\s\S]*?<\/mesh>/
358
- const RE2 = /<mesh position=\{\[0, 0\.02, -0\.215\]\}>[\s\S]*?<\/mesh>/
359
- if (RE.test(s)) { s = s.replace(RE, FACEMESH); hit++; ok('app.js: mat -> cau cat +z (hien duoc)') }
360
- else if (RE2.test(s)) { s = s.replace(RE2, FACEMESH); hit++; ok('app.js: mat -> cau cat +z (hien duoc)') }
361
- else warn('app.js: KHONG THAY khoi mat dau')
362
- }
363
-
364
- /* ---------- A8. TOC ----------
365
- Goc: sphereGeometry(0.25, 16, 12, 0, 2PI, 0, 0.72PI) + scale [1.06,0.82,1.06]
366
- thetaLength 0.72 PI = 129.6 do tinh tu dinh => phu tu dinh xuong QUA
367
- duong xich o MOI phi => trum kin ca mat.
368
- V112: cap 0.30 PI = 54 do, chi phu DINH dau.
369
- r = 0.2465 x scaleXZ 1.035 = 0.2551 ; truc y 0.2465 + offset 0.015
370
- => dinh toc y = 0.2615 > dinh dau 0.24 (doi ra ngoai, dung).
371
- mep duoi toc y = 0.2465*cos(54 do) + 0.015 = 0.1599
372
- dinh mat y = 0.118 => chua 0.042 lam TRAN.
373
- Toc phu kin mat => vung da lo ra moi thay long may / mat / mui / mieng. */
374
- const HAIRNEW = [
375
- ' {/* V112: TOC — cap ngan tren DINH dau. Ban goc thetaLength 0.72 PI',
376
- ' phu tu dinh xuong qua duong xich o moi phi => trum kin ca mat.',
377
- ' 0.30 PI (54 do) => chi phu dinh, chua lo chan may / mat / mui. */}',
378
- ' <mesh castShadow position={[0, 0.015, 0]} scale={[1.035, 1.0, 1.035]}>',
379
- ' <sphereGeometry args={[0.2465, 20, 14, 0, Math.PI * 2, 0, Math.PI * 0.30]} />',
380
- ' <meshStandardMaterial color={0x1c1610} roughness={0.92} />',
381
- ' </mesh>',
382
- ].join('\n')
383
- const HAIRBLOCK = [
384
- ' {/* tóc đen ngắn kiểu cầu thủ */}',
385
- ' <mesh castShadow position={[0, 0.08, -0.01]} scale={[1.06, 0.82, 1.06]}>',
386
- ' <sphereGeometry args={[0.25, 16, 12, 0, Math.PI * 2, 0, Math.PI * 0.72]} />',
387
- ' <meshStandardMaterial color={0x1c1610} roughness={0.92} />',
388
- ' </mesh>',
389
- ].join('\n')
390
- if (s.includes('V112: TOC')) ok('app.js: toc cap ngan (idem)')
391
- else if (s.includes(HAIRBLOCK)) { s = s.replace(HAIRBLOCK, HAIRNEW); hit++; ok('app.js: toc cap ngan lai, lo mat') }
392
- else {
393
- const HR = /[ \t]*\{\/\* tóc đen ngắn kiểu cầu thủ \*\/\}\r?\n[ \t]*<mesh castShadow position=\{\[0, 0\.08, -0\.01\]\} scale=\{\[1\.06, 0\.82, 1\.06\]\}>[\s\S]*?<\/mesh>/
394
- if (HR.test(s)) { s = s.replace(HR, HAIRNEW); hit++; ok('app.js: toc cap ngan lai (regex)') }
395
- else {
396
- const H2 = '<sphereGeometry args={[0.25, 16, 12, 0, Math.PI * 2, 0, Math.PI * 0.72]} />'
397
- if (s.includes(H2)) {
398
- s = s.split(H2).join('<sphereGeometry args={[0.2465, 20, 14, 0, Math.PI * 2, 0, Math.PI * 0.30]} />')
399
- hit++; ok('app.js: toc cap ngan lai (fallback tham so)')
400
- } else warn('app.js: KHONG THAY toc')
401
- }
402
- }
403
-
404
- /* ---------- A9. KHUON MAT ----------
405
- Mat cau cat: rong cung = r * phiLength = 0.2455 * 0.44PI = 0.339
406
- cao cung = r * thetaLength = 0.2455 * 0.30PI = 0.2314
407
- => ti le 1.465, canvas 256 x 168 = 1.524 (gan nhat, khong keo gian ro). */
408
- if (s.includes('V112: KHUON MAT')) ok('app.js: makeFaceTex moi (idem)')
409
- else {
410
- const cut = cutFn(s, 'makeFaceTex')
411
- if (!cut) throw new Error('KHONG THAY makeFaceTex')
412
- let start = cut[0]
413
- const pre = s.slice(Math.max(0, start - 120), start)
414
- const mpre = /const _faceTexCache = \{\}\r?\n[ \t]*$/.exec(pre)
415
- if (mpre) start = start - mpre[0].length
416
- const FACE = `/* V112: KHUON MAT — long may + long trang + long den + diem sang +
417
- MUI + MIENG. Ban goc chi co 2 cham mat + 1 cung mieng, khong co mui.
418
- Canvas 256x168 (ti le 1.52) khop cung cau phi 0.44 PI x th 0.30 PI cua dau
419
- r 0.2455 (rong 0.339 x cao 0.231) => khong bi keo gian ro.
420
- Goc toa do o tam (128, 84); moi net nam trong y 20..150. */
421
- const _faceTexCache = {}
422
- function makeFaceTex(seed, mood) {
423
- const key = seed + '|' + mood
424
- if (_faceTexCache[key]) return _faceTexCache[key]
425
- const c = document.createElement('canvas'); c.width = 256; c.height = 168
426
- const g = c.getContext('2d')
427
- g.clearRect(0, 0, 256, 168)
428
- g.translate(128, 84)
429
- const ink = '#20150c'
430
- const rng = mulberry(seed * 1000 + 7)
431
- const dx = (rng() - 0.5) * 12
432
- const ey = -26 + (rng() - 0.5) * 6
433
- g.lineCap = 'round'
434
- /* LONG MAY */
435
- g.strokeStyle = ink; g.lineWidth = 7
436
- g.beginPath(); g.moveTo(-52 + dx, ey - 15); g.quadraticCurveTo(-35 + dx, ey - 23, -16 + dx, ey - 14); g.stroke()
437
- g.beginPath(); g.moveTo(16 + dx, ey - 14); g.quadraticCurveTo(35 + dx, ey - 23, 52 + dx, ey - 15); g.stroke()
438
- if (mood === 'blink') {
439
- g.strokeStyle = ink; g.lineWidth = 9
440
- g.beginPath(); g.moveTo(-44 + dx, ey); g.lineTo(-16 + dx, ey); g.stroke()
441
- g.beginPath(); g.moveTo(16 + dx, ey); g.lineTo(44 + dx, ey); g.stroke()
442
- } else {
443
- /* LONG TRANG */
444
- g.fillStyle = '#ffffff'
445
- g.beginPath(); g.ellipse(-30 + dx, ey, 13, 15, 0, 0, Math.PI * 2); g.fill()
446
- g.beginPath(); g.ellipse(30 + dx, ey, 13, 15, 0, 0, Math.PI * 2); g.fill()
447
- /* LONG DEN */
448
- g.fillStyle = '#2b1c10'
449
- g.beginPath(); g.arc(-28 + dx, ey + 1, 7.4, 0, Math.PI * 2); g.fill()
450
- g.beginPath(); g.arc(32 + dx, ey + 1, 7.4, 0, Math.PI * 2); g.fill()
451
- /* DIEM SANG */
452
- g.fillStyle = '#ffffff'
453
- g.beginPath(); g.arc(-30.8 + dx, ey - 2.4, 3.2, 0, Math.PI * 2); g.fill()
454
- g.beginPath(); g.arc(29.2 + dx, ey - 2.4, 3.2, 0, Math.PI * 2); g.fill()
455
- }
456
- /* MUI — net cong nhe */
457
- g.strokeStyle = 'rgba(154,99,68,0.9)'; g.lineWidth = 5
458
- g.beginPath(); g.moveTo(0 + dx, ey + 6); g.quadraticCurveTo(8 + dx, ey + 20, -3 + dx, ey + 23); g.stroke()
459
- /* MIENG */
460
- g.strokeStyle = ink; g.lineWidth = 8
461
- if (mood === 'talk') {
462
- g.fillStyle = '#5d2a22'
463
- g.beginPath(); g.ellipse(0 + dx, ey + 50, 13, 17, 0, 0, Math.PI * 2); g.fill()
464
- } else if (mood === 'happy') {
465
- g.beginPath(); g.arc(0 + dx, ey + 36, 23, 0.10 * Math.PI, 0.90 * Math.PI); g.stroke()
466
- } else {
467
- g.beginPath(); g.arc(0 + dx, ey + 40, 16, 0.16 * Math.PI, 0.84 * Math.PI); g.stroke()
468
- }
469
- const tex = new THREE.CanvasTexture(c)
470
- tex.colorSpace = THREE.SRGBColorSpace
471
- _faceTexCache[key] = tex
472
- return tex
473
- }
474
- `
475
- s = s.slice(0, start) + FACE + s.slice(cut[1])
476
- hit++; ok('app.js: mat co long may + long den + mui + mieng')
477
- }
478
-
479
- save(f, s)
480
- } catch (e) { warn('app.js: ' + String((e && e.message) || e)) }
481
-
482
- /* =====================================================================
483
- B) cave3d.js — GIANG SINH thay ngon lua + cup
484
- ===================================================================== */
485
- try {
486
- const f = 'frontend/cave3d.js'
487
- if (!has(f)) throw new Error('cave3d.js missing')
488
- let s = read(f)
489
- let hit = 0
490
-
491
- const XMAS = `/* =========================================================================
492
- V112: GIANG SINH GIUA HANG — thay ngon lua (FirePit) va cup (Trophy).
493
- Cay thong lon co DEN NHAP NHAY, ngoi sao, bong trang tri, tat, qua; nguoi
494
- tuyet; ong gia Noel. Giu anh sang am (FirePit cu intensity 100) de hang
495
- khong bi toi. Tat ca nam trong long ho (ban kinh ho CAVE.pitRadius = 7,
496
- mat ho -CAVE.pitDepth = -2.4) nen khong de len bac thang / bang ghe.
497
- ========================================================================= */
498
- function ChristmasGrove() {
499
- const pitY = -CAVE.pitDepth
500
- const bulbGroup = useRef(null)
501
- const treeRef = useRef(null)
502
- const rand = useMemo(() => mulberry(4242), [])
503
-
504
- /* Ban kinh tan cay tai do cao y (local cua cay). Tan = 5 hinh non xep tang,
505
- moi non cao 3.3 => nua chieu cao 1.65. Ban kinh giam tuyen tinh tu day
506
- (r0) len dinh (0): tai do cao y, t = (dinh - y) / 3.3. Lay MAX qua cac
507
- non vi be mat ngoai la non rong nhat. */
508
- const treeR = (y) => {
509
- let best = 0.05
510
- for (let i = 0; i < 5; i++) {
511
- const cy = 1.5 + i * 2.5
512
- const r0 = 4.7 - i * 0.88
513
- const t = (cy + 1.65 - y) / 3.3
514
- if (t > 0 && t <= 1) best = Math.max(best, r0 * t)
515
- }
516
- return best
517
- }
518
-
519
- /* DEN NHAP NHAY: xoan oc tu goc len ngon, bam sat mat tan */
520
- const bulbs = useMemo(() => {
521
- const out = []
522
- const N = 108
523
- for (let i = 0; i < N; i++) {
524
- const t = i / N
525
- const y = 0.95 + t * 12.1
526
- const r = treeR(y) + 0.13
527
- const a = i * 2.399963
528
- out.push({ x: Math.cos(a) * r, y, z: Math.sin(a) * r, c: i % 4 })
529
- }
530
- return out
531
- }, [rand])
532
-
533
- /* BONG TRANG TRI */
534
- const orbs = useMemo(() => {
535
- const out = []
536
- const pal = ['#e8262b', '#ffd447', '#f2f2f2', '#2f9be0']
537
- for (let i = 0; i < 28; i++) {
538
- const y = 1.5 + rand() * 11.0
539
- const r = treeR(y) + 0.15
540
- const a = rand() * Math.PI * 2
541
- out.push({ x: Math.cos(a) * r, y, z: Math.sin(a) * r, c: pal[i % pal.length], s: 0.15 + rand() * 0.11 })
542
- }
543
- return out
544
- }, [rand])
545
-
546
- /* QUA GIANG SINH quanh goc cay */
547
- const gifts = useMemo(() => {
548
- const out = []
549
- const pal = ['#c8102e', '#1f7a3d', '#2f6fa8', '#c9a24e']
550
- for (let i = 0; i < 15; i++) {
551
- const a = (i / 15) * Math.PI * 2 + rand() * 0.35
552
- const r = 4.5 + rand() * 1.2
553
- const w = 0.6 + rand() * 0.62
554
- const h = 0.48 + rand() * 0.5
555
- out.push({ x: Math.cos(a) * r, z: Math.sin(a) * r, w, h, d: 0.6 + rand() * 0.55, c: pal[i % pal.length], rot: rand() * 0.8 })
556
- }
557
- return out
558
- }, [rand])
559
-
560
- /* TAT GIANG SINH treo tren tan cay */
561
- const socks = useMemo(() => {
562
- const out = []
563
- for (let i = 0; i < 8; i++) {
564
- const y = 3.0 + (i % 4) * 1.6
565
- const r = treeR(y) + 0.12
566
- const a = -1.0 + i * 0.27
567
- out.push({ x: Math.cos(a) * r, y, z: Math.sin(a) * r })
568
- }
569
- return out
570
- }, [])
571
-
572
- useFrame(({ clock }) => {
573
- const t = clock.elapsedTime
574
- const grp = bulbGroup.current
575
- if (grp) {
576
- for (let i = 0; i < grp.children.length; i++) {
577
- const b = grp.children[i]
578
- if (!b.material) continue
579
- const on = Math.sin(t * 4.2 + i * 0.85) > -0.15
580
- b.material.opacity = on ? 1 : 0.1
581
- b.scale.setScalar(on ? 1 : 0.72)
582
- }
583
- }
584
- if (treeRef.current) treeRef.current.rotation.y = t * 0.045
585
- })
586
-
587
- const bulbCol = ['#ffe680', '#ff6a5c', '#7fe0ff', '#a8ff8f']
588
-
589
- return (
590
- <group>
591
- {/* CAY THONG */}
592
- <group position={[0, pitY, 0]}>
593
- <mesh position={[0, 0.6, 0]}>
594
- <cylinderGeometry args={[0.42, 0.62, 1.6, 10]} />
595
- <meshLambertMaterial color="#4a3220" flatShading />
596
- </mesh>
597
- <group ref={treeRef}>
598
- {[0, 1, 2, 3, 4].map((i) => (
599
- <mesh key={i} position={[0, 1.5 + i * 2.5, 0]} castShadow>
600
- <coneGeometry args={[4.7 - i * 0.88, 3.3, 14]} />
601
- <meshLambertMaterial color={i % 2 ? '#1d5c33' : '#164a29'} flatShading />
602
- </mesh>
603
- ))}
604
- <mesh position={[0, 13.55, 0]}>
605
- <octahedronGeometry args={[0.62, 0]} />
606
- <meshBasicMaterial color="#ffe14d" toneMapped={false} />
607
- </mesh>
608
- <group ref={bulbGroup}>
609
- {bulbs.map((b, i) => (
610
- <mesh key={i} position={[b.x, b.y, b.z]}>
611
- <sphereGeometry args={[0.135, 8, 6]} />
612
- <meshBasicMaterial color={bulbCol[b.c]} transparent toneMapped={false} depthWrite={false} />
613
- </mesh>
614
- ))}
615
- </group>
616
- {orbs.map((o, i) => (
617
- <mesh key={'o' + i} position={[o.x, o.y, o.z]}>
618
- <sphereGeometry args={[o.s, 10, 8]} />
619
- <meshStandardMaterial color={o.c} metalness={0.55} roughness={0.22} />
620
- </mesh>
621
- ))}
622
- {socks.map((k, i) => (
623
- <group key={'s' + i} position={[k.x, k.y, k.z]}>
624
- <mesh>
625
- <boxGeometry args={[0.3, 0.46, 0.08]} />
626
- <meshStandardMaterial color={i % 2 ? '#e8262b' : '#f2f2f2'} roughness={0.85} />
627
- </mesh>
628
- <mesh position={[0, -0.27, 0.03]}>
629
- <boxGeometry args={[0.3, 0.15, 0.15]} />
630
- <meshStandardMaterial color={i % 2 ? '#e8262b' : '#f2f2f2'} roughness={0.85} />
631
- </mesh>
632
- </group>
633
- ))}
634
- </group>
635
- </group>
636
-
637
- {/* QUA GIANG SINH quanh goc cay */}
638
- {gifts.map((gf, i) => (
639
- <group key={'g' + i} position={[gf.x, pitY + gf.h / 2, gf.z]} rotation-y={gf.rot}>
640
- <mesh castShadow>
641
- <boxGeometry args={[gf.w, gf.h, gf.d]} />
642
- <meshLambertMaterial color={gf.c} flatShading />
643
- </mesh>
644
- <mesh>
645
- <boxGeometry args={[gf.w + 0.02, gf.h * 0.16, gf.d + 0.02]} />
646
- <meshStandardMaterial color="#ffd447" metalness={0.4} roughness={0.45} />
647
- </mesh>
648
- <mesh>
649
- <boxGeometry args={[gf.w * 0.16, gf.h + 0.02, gf.d + 0.02]} />
650
- <meshStandardMaterial color="#ffd447" metalness={0.4} roughness={0.45} />
651
- </mesh>
652
- </group>
653
- ))}
654
-
655
- {/* NGUOI TUYET — 3 khoi cau + mat + mui + mu + khan quang */}
656
- <group position={[5.4, pitY, 1.3]} rotation-y={-2.35}>
657
- <mesh position={[0, 0.85, 0]} castShadow>
658
- <sphereGeometry args={[0.9, 16, 14]} />
659
- <meshStandardMaterial color="#f4f7fb" roughness={0.85} />
660
- </mesh>
661
- <mesh position={[0, 1.98, 0]} castShadow>
662
- <sphereGeometry args={[0.64, 16, 14]} />
663
- <meshStandardMaterial color="#f4f7fb" roughness={0.85} />
664
- </mesh>
665
- <mesh position={[0, 2.84, 0]} castShadow>
666
- <sphereGeometry args={[0.46, 16, 14]} />
667
- <meshStandardMaterial color="#f4f7fb" roughness={0.85} />
668
- </mesh>
669
- <mesh position={[-0.17, 2.94, -0.41]}>
670
- <sphereGeometry args={[0.07, 8, 8]} />
671
- <meshStandardMaterial color="#20242c" roughness={0.6} />
672
- </mesh>
673
- <mesh position={[0.17, 2.94, -0.41]}>
674
- <sphereGeometry args={[0.07, 8, 8]} />
675
- <meshStandardMaterial color="#20242c" roughness={0.6} />
676
- </mesh>
677
- <mesh position={[0, 2.84, -0.46]} rotation-x={Math.PI / 2}>
678
- <coneGeometry args={[0.085, 0.46, 8]} />
679
- <meshStandardMaterial color="#e07a1f" roughness={0.7} />
680
- </mesh>
681
- <mesh position={[0, 3.21, 0]}>
682
- <cylinderGeometry args={[0.32, 0.32, 0.46, 12]} />
683
- <meshStandardMaterial color="#20242c" roughness={0.8} />
684
- </mesh>
685
- <mesh position={[0, 3.0, 0]}>
686
- <cylinderGeometry args={[0.58, 0.58, 0.07, 14]} />
687
- <meshStandardMaterial color="#20242c" roughness={0.8} />
688
- </mesh>
689
- <mesh position={[0, 2.46, 0]}>
690
- <torusGeometry args={[0.52, 0.12, 8, 16]} />
691
- <meshStandardMaterial color="#c8102e" roughness={0.85} />
692
- </mesh>
693
- </group>
694
-
695
- {/* ONG GIA NOEL — than do + rau + mu do + bo long trang + mat + mui do */}
696
- <group position={[-5.4, pitY, 1.4]} rotation-y={2.3}>
697
- <mesh position={[0, 0.76, 0]} castShadow>
698
- <capsuleGeometry args={[0.64, 0.5, 6, 14]} />
699
- <meshStandardMaterial color="#c8102e" roughness={0.8} />
700
- </mesh>
701
- <mesh position={[0, 1.56, 0]}>
702
- <sphereGeometry args={[0.43, 16, 14]} />
703
- <meshStandardMaterial color="#f0c9a4" roughness={0.85} />
704
- </mesh>
705
- <mesh position={[0, 1.36, -0.19]}>
706
- <sphereGeometry args={[0.41, 14, 12]} />
707
- <meshStandardMaterial color="#f7f7f7" roughness={0.95} />
708
- </mesh>
709
- <mesh position={[0, 1.98, 0]}>
710
- <coneGeometry args={[0.39, 0.68, 12]} />
711
- <meshStandardMaterial color="#c8102e" roughness={0.8} />
712
- </mesh>
713
- <mesh position={[0, 2.29, 0]}>
714
- <sphereGeometry args={[0.115, 10, 8]} />
715
- <meshStandardMaterial color="#f7f7f7" roughness={0.95} />
716
- </mesh>
717
- <mesh position={[0, 1.78, 0]}>
718
- <cylinderGeometry args={[0.42, 0.42, 0.12, 14]} />
719
- <meshStandardMaterial color="#f7f7f7" roughness={0.95} />
720
- </mesh>
721
- <mesh position={[-0.145, 1.6, -0.37]}>
722
- <sphereGeometry args={[0.052, 8, 8]} />
723
- <meshStandardMaterial color="#20242c" />
724
- </mesh>
725
- <mesh position={[0.145, 1.6, -0.37]}>
726
- <sphereGeometry args={[0.052, 8, 8]} />
727
- <meshStandardMaterial color="#20242c" />
728
- </mesh>
729
- <mesh position={[0, 1.5, -0.41]}>
730
- <sphereGeometry args={[0.09, 10, 8]} />
731
- <meshStandardMaterial color="#d9614a" roughness={0.8} />
732
- </mesh>
733
- <mesh position={[0, 0.82, 0]}>
734
- <cylinderGeometry args={[0.68, 0.68, 0.16, 16]} />
735
- <meshStandardMaterial color="#20242c" roughness={0.8} />
736
- </mesh>
737
- {[-0.29, 0.29].map((bx) => (
738
- <mesh key={bx} position={[bx, 0.14, -0.06]}>
739
- <boxGeometry args={[0.31, 0.27, 0.52]} />
740
- <meshStandardMaterial color="#20242c" roughness={0.8} />
741
- </mesh>
742
- ))}
743
- </group>
744
-
745
- {/* ANH SANG am + mau (thay FirePit cu intensity 100, distance 52) */}
746
- <pointLight position={[0, pitY + 6, 0]} color="#ffd9a0" intensity={85} distance={54} decay={1.5} />
747
- <pointLight position={[0, pitY + 11, 0]} color="#ffe9c2" intensity={40} distance={40} decay={1.4} />
748
- <pointLight position={[5.4, pitY + 3, 1.3]} color="#dff0ff" intensity={16} distance={18} decay={1.7} />
749
- <pointLight position={[-5.4, pitY + 3, 1.4]} color="#ff7a5c" intensity={16} distance={18} decay={1.7} />
750
- </group>
751
- )
752
- }
753
-
754
- `
755
- if (s.includes('function ChristmasGrove(')) ok('cave3d: ChristmasGrove (idem)')
756
- else {
757
- const anchor = 'export function CaveScene()'
758
- if (!s.includes(anchor)) throw new Error('KHONG THAY export function CaveScene')
759
- s = s.replace(anchor, XMAS + anchor)
760
- hit++; ok('cave3d: them ChristmasGrove (cay thong + nguoi tuyet + Noel + qua)')
761
- }
762
-
763
- /* go mount ngon lua + cup: chi khop DONG MOUNT JSX that */
764
- const before = s.length
765
- s = s.replace(/^[ \t]*<FirePit\b[^>]*?\/>[ \t]*\r?\n/gm, '')
766
- s = s.replace(/^[ \t]*<Trophy\b[^>]*?\/>[ \t]*\r?\n/gm, '')
767
- if (s.length < before) { hit++; ok('cave3d: GO mount ngon lua + cup (' + (before - s.length) + 'B)') }
768
- else warn('cave3d: khong thay mount FirePit/Trophy de go')
769
-
770
- if (s.includes('<ChristmasGrove />')) ok('cave3d: ChristmasGrove da mount (idem)')
771
- else if (s.includes(' <Torches />')) {
772
- s = s.replace(' <Torches />', ' <Torches />\n <ChristmasGrove />')
773
- hit++; ok('cave3d: mount <ChristmasGrove /> giua hang')
774
- } else throw new Error('KHONG THAY <Torches /> de chen ChristmasGrove')
775
-
776
- save(f, s)
777
- } catch (e) { warn('cave3d: ' + String((e && e.message) || e)) }
778
-
779
- /* =====================================================================
780
- C) GUARD + VALIDATE, loi thi RESTORE
781
- ===================================================================== */
782
- let restored = false
783
- try {
784
- const bad = []
785
- for (const sp of [
786
- ['frontend/app.js', ['function PlayerAvatar(', '<group ref={rootRef}', 'function yellowKitTex()',
787
- 'function makeFaceTex(', 'function nameTagTex(', 'function backTagTex(',
788
- 'V112: BANG TEN', 'V112: MAT — mat CAU CAT', 'V112: KHUON MAT',
789
- 'V112: THAT LUNG', 'V112: TOC', 'const AVATAR_SCALE = 0.94']],
790
- ['frontend/cave3d.js', ['export function CaveScene()', 'export const BOARD = {', '<Board />',
791
- 'function ChristmasGrove(', 'function Benches(']],
792
- ]) {
793
- const f = sp[0]
794
- if (!has(f)) continue
795
- const t = read(f)
796
- for (const m of sp[1]) if (!t.includes(m)) bad.push(f + ' thieu: ' + m)
797
- }
798
- const app = read('frontend/app.js')
799
- const cave = read('frontend/cave3d.js')
800
- if ((app.match(/function makeFaceTex\(/g) || []).length !== 1) bad.push('app.js: makeFaceTex != 1')
801
- if ((app.match(/function yellowKitTex\(/g) || []).length !== 1) bad.push('app.js: yellowKitTex != 1')
802
- if ((app.match(/function nameTagTex\(/g) || []).length !== 1) bad.push('app.js: nameTagTex != 1')
803
- /* Chi dem DONG MOUNT that (^[ \t]*<FirePit ...). Dem tho se khop ca comment
804
- trong chinh patch nay va tu fail => tu restore. */
805
- if (/^[ \t]*<FirePit\b/m.test(cave)) bad.push('cave3d: van con mount FirePit')
806
- if (/^[ \t]*<Trophy\b/m.test(cave)) bad.push('cave3d: van con mount Trophy')
807
- if (!/^[ \t]*<ChristmasGrove\b/m.test(cave)) bad.push('cave3d: chua mount ChristmasGrove')
808
-
809
- if (bad.length) throw new Error('marker: ' + bad.join(' | '))
810
-
811
- const esbuild = await import('esbuild')
812
- for (const f of ['frontend/app.js', 'frontend/cave3d.js']) {
813
- if (!has(f)) continue
814
- try { await esbuild.transform(read(f), { loader: 'jsx', format: 'esm', target: 'es2020' }) }
815
- catch (err) { throw new Error(f + ' KHONG HOP LE: ' + String((err && err.message) || err).split('\n').slice(0, 3).join(' ')) }
816
- }
817
- ok('esbuild transform OK: app.js + cave3d.js hop le')
818
- } catch (e) {
819
- warn('VALIDATE THAT BAI: ' + String((e && e.message) || e))
820
- for (const f of Object.keys(BAK)) save(f, BAK[f])
821
- restored = true
822
- warn('DA RESTORE ve ban truoc V112 — giao dien cu, build van xanh')
823
- }
824
- if (restored) { console.log('[v112] SKIPPED (restored)'); process.exit(0) }
825
-
826
- /* =====================================================================
827
- D) VERSION + cache-bust
828
- ===================================================================== */
829
- try {
830
- if (has('backend.py')) {
831
- const b = read('backend.py')
832
- const nb = b.replace(/VERSION_ID = "v\d+"/, 'VERSION_ID = "v112"')
833
- if (nb !== b) { save('backend.py', nb); ok('backend.py: VERSION_ID -> v112') }
834
- }
835
- for (const ip of ['frontend/index.html', 'index.html']) {
836
- if (!has(ip)) continue
837
- const h = read(ip)
838
- const nh = h.replace(/\?v=\d+/g, '?v=112')
839
- if (nh !== h) { save(ip, nh); ok(ip + ': cache-bust -> ?v=112') }
840
- }
841
- } catch (e) { warn('version: ' + String((e && e.message) || e)) }
842
-
843
- console.log('[v112] DONE: ' + n + ' muc ap dung')
844
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v113.mjs DELETED
@@ -1,379 +0,0 @@
1
- /* patch_v113.mjs — V113. Chay TRONG Docker build: SAU patch_v112.mjs, TRUOC esbuild.
2
- =========================================================================
3
- SUA 3 LOI NGUOI DUNG BAO (da xac minh bang cach render that trong Chromium
4
- headless, dung dung chuoi patch cua Dockerfile):
5
-
6
- LOI 1 — "TAY LIEN LAC VOI THAN THE" (tay long, ho ra khoi vai).
7
- V109 doi vai tu 0.34 -> 0.335 va V112 thu nho ong tay (ban kinh 0.058).
8
- Nhung KHONG co chi tiet nao lap khe vai. Tinh theo hinh hoc that:
9
- than = capsuleGeometry(0.30, 0.34) o y = 1.0
10
- => tru y 0.83..1.17, chop cau tam 1.17 ban kinh 0.30
11
- tai y = 1.30 (tam nhom tay): ban kinh than = sqrt(0.30^2 - 0.13^2)
12
- = 0.2704
13
- tay o x = 0.335, ban kinh 0.058 => mep trong = 0.2770
14
- => khe 0.0066 o DUNG tam, va tai DINH ong tay (y = 1.468):
15
- ban kinh than = sqrt(0.09 - 0.0888) = 0.0346
16
- mep trong tay = 0.2770
17
- => HO 0.2424 — tay lo lung, dung hien tuong user thay.
18
- => V113: moi tay la MOT group xoay quanh KHOP VAI (±0.315, 1.30):
19
- + cau deltoid r 0.10 ngay tai tam xoay => lap kin khe vai o MOI goc
20
- xoay (vi tam cau trung tam xoay nen khong bao gio tach)
21
- + ong tay dai hon (0.18) + cang tay + ban tay noi lien
22
- Kiem chung so: khoang cach tu (0.315, 1.30) toi MAT capsule than
23
- = sqrt(0.315^2 + 0.13^2) - 0.30 = 0.3407 - 0.30 = 0.0407
24
- 0.0407 < 0.062 (ban kinh ong tay) => ong tay da an vao than
25
- 0.0407 < 0.10 (ban kinh deltoid) => vai kin, khong ho
26
- Va o dinh ong tay (y = 1.30 + 0.027): mep trong = 0.315 - 0.062 = 0.253
27
- < 0.2704 (ban kinh than) => van an vao than.
28
-
29
- LOI 2 — "SO VA LOGO VAN CON IN NGƯOC" (so ao + V.AI STUDIO bi lat).
30
- Ban dang chay van con dung plane phang cua V109:
31
- <mesh position={[0, 1.06, -0.315]} rotation={[0, 0.1, 0]}>
32
- <planeGeometry args={[0.46, 0.46]} />
33
- <meshBasicMaterial ... side={THREE.DoubleSide} />
34
- </mesh>
35
- Plane mac dinh huong +z; camera third-person nam o local -z
36
- (CameraRig: back = (sin yaw, cos yaw), yaw = PI => (0,0,-1)) nen no nhin
37
- vao MAT SAU cua plane => moi net lat nguoc. DoubleSide chi lam no HIEN,
38
- khong lam no DOC DUNG.
39
- Vi sao khoi mat cong cua V112 khong duoc chen: guard cua V112 la
40
- if (s.includes('V112: BANG TEN')) ...
41
- nhung chinh comment trong khoi TAG ma V112 vua chen cung chua chuoi
42
- 'V112: BANG TEN' => guard tu khop voi comment cua no => BO QUA buoc chen
43
- mat cong, va plane phang V109 o lai. (Da xac nhan tren bundle that:
44
- co backPlateTex + DoubleSide plane, KHONG co nameTagTex/backTagTex.)
45
- => V113 GO HAN plane phang + DoubleSide va dung MAT CONG mot mat
46
- (cylinderGeometry mot cung tru, openEnded) — chi mot phia huong ra
47
- ngoai nen KHONG THE lat du xoay camera kieu gi.
48
-
49
- Huong doc — chung minh bang so (da kiem chung bang THREE that):
50
- CylinderGeometry: x = r*sin(t), z = r*cos(t); u tang theo t.
51
- cung quanh t = PI => u=0 o x=+0.217, u=1 o x=-0.217 (z<0)
52
- camera o -z nhin ve +z: right = viewDir x up = (0,0,1)x(0,1,0)
53
- = (-1,0,0) => screen-right = -x
54
- => u=0 (x=+0.217) nam ben TRAI khung hinh, u tang trai -> phai
55
- => chu doc DUNG chieu. (Plane phang + DoubleSide thi nguoc lai.)
56
-
57
- Ban kinh — tinh theo ban kinh that cua than de khong z-fight / lo lung:
58
- so ao: y 0.87..1.17, than = tru thang r = 0.300 => dat r = 0.314
59
- (cach 0.014) ; cung 2*0.764 rad => dai 0.480 ; cao 0.30
60
- => ti le 1.60 = canvas 320x200 (khong keo gian).
61
- V112 dat r = 0.312 nhung KHONG kiem tra: tai gau ao (duoi cung)
62
- ban kinh than > 0.312 => bi cat cut. V113 tinh lai theo tung dai y.
63
-
64
- LOI 3 — "BANG TEN NHAN VAT CHUA THAY IN LEN MAT TRUOC CUA AO".
65
- V112 chi in ten o LUNG (va con bi guard chan nen khong he duoc chen).
66
- => V113 them BANG TEN o MAT TRUOC ao (nguc), mat cong quanh t = 0 (+z):
67
- CylinderGeometry cung quanh t = 0 => u=0 o x=-0.178, u=1 o x=+0.178.
68
- Camera o +z nhin ve -z: right = (0,0,-1)x(0,1,0) = (+1,0,0)
69
- => screen-right = +x => u tang trai -> phai => chu doc DUNG chieu.
70
- Dai y 1.13..1.23, than r tu 0.300 (y 1.13) den 0.294 (y 1.23)
71
- => dat r = 0.312 (cach 0.012..0.018) ; cao 0.10
72
- cung 2*0.62 rad => dai 0.387 => ti le 3.87 = canvas 512x132.
73
-
74
- TAT CA deu idempotent + co guard: chay lai lan 2 khong nhan doi, va neu
75
- bat ky anchor nao khong khop thi RESTORE ca 2 file + exit 0 => khong bao
76
- gio lam sap build.
77
- ========================================================================= */
78
- import fs from 'node:fs'
79
- import path from 'node:path'
80
-
81
- const ROOT = process.argv[2] || '.'
82
- let n = 0
83
- const ok = (m) => { n++; console.log('[v113] OK: ' + m) }
84
- const warn = (m) => console.warn('[v113] WARN: ' + m)
85
- const P = (...a) => path.join(ROOT, ...a)
86
- const has = (f) => fs.existsSync(P(f))
87
- const read = (f) => fs.readFileSync(P(f), 'utf8')
88
- const save = (f, s) => fs.writeFileSync(P(f), s)
89
-
90
- const BAK = {}
91
- for (const f of ['frontend/app.js', 'frontend/cave3d.js']) if (has(f)) BAK[f] = read(f)
92
-
93
- /* ---------------------------------------------------------------------
94
- Cat mot phan tu JSX <mesh ...> ... </mesh> (ke ca comment ngan ngay tren)
95
- neu noi dung cua no co chua mot trong cac marker cho truoc.
96
- --------------------------------------------------------------------- */
97
- function cutMeshByMarker(src, markers) {
98
- const re = /[ \t]*<mesh\b[^>]*>[\s\S]{0,900}?<\/mesh>[ \t]*\r?\n/g
99
- let out = src
100
- let cuts = 0
101
- const spans = []
102
- let m
103
- while ((m = re.exec(src))) {
104
- /* CHI cat mesh CŨ: plane phang (planeGeometry). Mat cong moi cua V113 dung
105
- cylinderGeometry va CUNG chua marker texture — neu khong loai tru thi
106
- chay lai lan 2 se tu xoa chinh no (idempotency). */
107
- if (m[0].includes('planeGeometry') &&
108
- !m[0].includes('cylinderGeometry') &&
109
- markers.some((k) => m[0].includes(k))) spans.push([m.index, m.index + m[0].length])
110
- }
111
- for (let i = spans.length - 1; i >= 0; i--) {
112
- out = out.slice(0, spans[i][0]) + out.slice(spans[i][1])
113
- cuts++
114
- }
115
- return [out, cuts]
116
- }
117
-
118
- /* =====================================================================
119
- A) app.js
120
- ===================================================================== */
121
- let fatal = null
122
- try {
123
- const f = 'frontend/app.js'
124
- if (!has(f)) throw new Error('app.js missing')
125
- let s = read(f)
126
-
127
- /* ---------- A1. GO plane phang + DoubleSide (nguon loi chu nguoc) ---------- */
128
- /* 1a. Khoi V109 co comment ro rang */
129
- const RE_V109 = /[ \t]*\{\/\* V109: MAT SAU AO[\s\S]*?<meshBasicMaterial map=\{backPlateTex\(p\.number\)\}[\s\S]*?<\/mesh>[ \t]*\r?\n/
130
- if (RE_V109.test(s)) {
131
- s = s.replace(RE_V109, '')
132
- ok('app.js: GO plane phang V109 (DoubleSide) — nguon loi chu bi nguoc')
133
- } else {
134
- /* 1b. Khong con comment (esbuild/variant khac) — cat theo marker texture */
135
- const [cut, k] = cutMeshByMarker(s, ['backPlateTex(', 'backTagTex(', 'nameTagTex('])
136
- if (k) { s = cut; ok('app.js: GO ' + k + ' mesh ten/so/logo cu (theo marker texture)') }
137
- else ok('app.js: khong con mesh ten/so/logo cu (idem)')
138
- }
139
-
140
- /* ---------- A2. Ham texture BANG TEN MAT TRUOC ---------- */
141
- const FN = `/* V113: BANG TEN NHAN VAT — in o MAT TRUOC ao (nguc).
142
- Canvas 512x132 (ti le 3.88) khop cung tru r 0.312, cao 0.10, cung 2*0.62
143
- rad => dai 0.387 => ti le 0.387/0.10 = 3.87. Khong bi keo gian ro.
144
- Nen navy dam + vien kem + chu trang: tren ao vang doc ro nhat. */
145
- const _frontNameCache = {}
146
- function frontNameTex(name) {
147
- const key = 'f|' + String(name == null ? '' : name)
148
- if (_frontNameCache[key]) return _frontNameCache[key]
149
- const c = document.createElement('canvas'); c.width = 512; c.height = 132
150
- const g = c.getContext('2d')
151
- g.clearRect(0, 0, 512, 132)
152
- g.fillStyle = 'rgba(26,34,52,0.94)'
153
- if (g.roundRect) { g.beginPath(); g.roundRect(6, 10, 500, 112, 18); g.fill() }
154
- else g.fillRect(6, 10, 500, 112)
155
- g.strokeStyle = '#f7f4ec'; g.lineWidth = 5
156
- if (g.roundRect) { g.beginPath(); g.roundRect(6, 10, 500, 112, 18); g.stroke() }
157
- else g.strokeRect(6, 10, 500, 112)
158
- g.textAlign = 'center'; g.textBaseline = 'middle'
159
- let label = String(name == null ? '' : name).trim() || 'ANH EM'
160
- if (label.length > 14) label = label.slice(0, 13) + String.fromCharCode(8230)
161
- let fs = 62
162
- for (; fs > 20; fs -= 2) {
163
- g.font = '800 ' + fs + 'px "Be Vietnam Pro", Arial, sans-serif'
164
- if (g.measureText(label).width < 460) break
165
- }
166
- g.fillStyle = '#ffffff'
167
- g.fillText(label, 256, 68)
168
- const t = new THREE.CanvasTexture(c)
169
- t.colorSpace = THREE.SRGBColorSpace
170
- t.anisotropy = 8; t.needsUpdate = true
171
- _frontNameCache[key] = t
172
- return t
173
- }
174
- `
175
- if (s.includes('function frontNameTex(')) ok('app.js: frontNameTex (idem)')
176
- else {
177
- const anchor = 'function PlayerAvatar({ id, p, isLocal }) {'
178
- if (!s.includes(anchor)) throw new Error('KHONG THAY PlayerAvatar de chen frontNameTex')
179
- s = s.replace(anchor, FN + anchor)
180
- ok('app.js: them frontNameTex (bang ten mat truoc)')
181
- }
182
-
183
- /* ---------- A3. TAY: KHOP VAI LIEN THAN ---------- */
184
- /* Cat CA HAI nhom tay cu (armL/armR) bang cach tim dung group ref */
185
- function cutGroupByRef(src, refName) {
186
- const re = new RegExp('[ \\t]*<group ref=\\{' + refName + '\\}[\\s\\S]*?</group>[ \\t]*\\r?\\n')
187
- const sp = []
188
- let m
189
- const reG = new RegExp(re.source, 'g')
190
- while ((m = reG.exec(src))) sp.push([m.index, m.index + m[0].length])
191
- if (!sp.length) return [src, 0]
192
- let out = src
193
- for (let i = sp.length - 1; i >= 0; i--) out = out.slice(0, sp[i][0]) + out.slice(sp[i][1])
194
- return [out, sp.length]
195
- }
196
-
197
- const armMesh = (side) => {
198
- const sx = side === 'L' ? -0.315 : 0.315
199
- return [
200
- ' {/* V113: TAY ' + side + ' — KHOP VAI LIEN THAN. Group xoay quanh',
201
- ' diem vai (' + sx + ', 1.30). Cau deltoid r 0.10 dat DUNG tam xoay nen',
202
- ' lap kin khe vai o moi goc dung dua (tam cau khong doi khi xoay).',
203
- ' Kiem chung: cach tu tam vai toi mat capsule than (R 0.30)',
204
- ' = sqrt(0.315^2 + 0.13^2) - 0.30 = 0.0407',
205
- ' 0.0407 < 0.062 (ban kinh ong tay) => ong tay an vao than',
206
- ' 0.0407 < 0.10 (ban kinh deltoid) => khong the ho vai. */}',
207
- ' <group ref={arm' + side + '} position={[' + sx + ', 1.3, 0]}>',
208
- ' <mesh castShadow>',
209
- ' <sphereGeometry args={[0.1, 16, 12]} />',
210
- " <meshStandardMaterial color={isYellowKit ? '#f5c518' : (isMuKit ? '#c8102e' : color)} roughness={0.72} />",
211
- ' </mesh>',
212
- ' <mesh castShadow position={[0, -0.125, 0]}>',
213
- ' <capsuleGeometry args={[0.062, 0.18, 4, 10]} />',
214
- " <meshStandardMaterial color={isYellowKit ? '#f5c518' : (isMuKit ? '#c8102e' : color)} roughness={0.72} />",
215
- ' </mesh>',
216
- ' <mesh castShadow position={[0, -0.387, 0]}>',
217
- ' <capsuleGeometry args={[0.05, 0.17, 4, 10]} />',
218
- ' <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />',
219
- ' </mesh>',
220
- ' <mesh castShadow position={[0, -0.552, 0]}>',
221
- ' <sphereGeometry args={[0.056, 12, 10]} />',
222
- ' <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />',
223
- ' </mesh>',
224
- ' </group>',
225
- '',
226
- ].join('\n')
227
- }
228
-
229
- if (s.includes('cylinderGeometry') && s.includes('capsuleGeometry args={[0.062, 0.18, 4, 10]}')) {
230
- ok('app.js: tay khop vai (idem)')
231
- } else {
232
- let cutL = 0, cutR = 0
233
- const anchorCHAN = /[ \t]*\{\/\* CH[^]*?\*\/\}[ \t]*\r?\n/
234
- const mCh = anchorCHAN.exec(s)
235
- if (!mCh) throw new Error('KHONG THAY comment CHAN de lam diem chen tay')
236
- ;[s, cutL] = cutGroupByRef(s, 'armL')
237
- ;[s, cutR] = cutGroupByRef(s, 'armR')
238
- const mCh2 = anchorCHAN.exec(s)
239
- if (!mCh2) throw new Error('KHONG THAY comment CHAN sau khi go tay cu')
240
- if (!cutL || !cutR) throw new Error('KHONG cat duoc nhom tay cu (armL=' + cutL + ', armR=' + cutR + ')')
241
- s = s.slice(0, mCh2.index) + armMesh('L') + armMesh('R') + s.slice(mCh2.index)
242
- ok('app.js: TAY dung lai — deltoid + ong tay dai + cang tay + ban tay (go ' + (cutL + cutR) + ' nhom cu)')
243
- }
244
-
245
- /* ---------- A4. SO AO + LOGO o LUNG: MAT CONG mot mat ---------- */
246
- const BACK = [
247
- ' {/* V113: SO AO + LOGO "V.AI STUDIO" — MAT CONG mot mat (cung tru).',
248
- ' Plane phang + DoubleSide cua V109 lam chu bi lat: camera third-person',
249
- ' o local -z nhin vao MAT SAU plane. Mat cong chi co MOT phia huong ra',
250
- ' ngoai nen khong the lat.',
251
- ' Huong doc: CylinderGeometry x = r*sin(t), z = r*cos(t), u tang theo t;',
252
- ' cung quanh t = PI => u=0 o x=+0.217. Camera o -z nhin +z co',
253
- ' screen-right = viewDir x up = (0,0,1)x(0,1,0) = (-1,0,0) => screen-right',
254
- ' = -x => x duong (u=0) o ben TRAI => chu doc DUNG chieu.',
255
- ' Ban kinh: dai y 0.87..1.17 nam trong TRU THANG cua than',
256
- ' (capsule r 0.30, tru 0.83..1.17) => ban kinh than = 0.300 hang so',
257
- ' => dat 0.314 (cach 0.014, khong z-fight / khong lo lung).',
258
- ' Cung 2*0.764 rad => dai 0.480 ; cao 0.30 => ti le 1.60 = canvas 320x200. */}',
259
- ' <mesh position={[0, 1.02, 0]}>',
260
- ' <cylinderGeometry args={[0.314, 0.314, 0.3, 32, 1, true, Math.PI - 0.764, 1.528]} />',
261
- ' <meshBasicMaterial map={backPlateTex(p.number)} transparent',
262
- ' depthWrite={false} toneMapped={false} fog={false} />',
263
- ' </mesh>',
264
- '',
265
- ].join('\n')
266
-
267
- const BACK_SIG = 'cylinderGeometry args={[0.314, 0.314, 0.3, 32, 1, true, Math.PI - 0.764, 1.528]}'
268
- if (s.includes(BACK_SIG)) ok('app.js: so ao + logo mat cong (idem)')
269
- else {
270
- /* chen ngay sau khoa that lung (anchor on dinh, khong phu thuoc khoi plane da go) */
271
- const KEYB = /[ \t]*<mesh position=\{\[0, 0\.78, -0\.301\]\}>[\s\S]*?<\/mesh>[ \t]*\r?\n/
272
- if (KEYB.test(s)) {
273
- s = s.replace(KEYB, (m0) => m0 + '\n' + BACK)
274
- ok('app.js: SO AO + logo -> mat cong quanh t = PI (het nguoc)')
275
- } else throw new Error('KHONG THAY khoa that lung de chen so ao')
276
- }
277
-
278
- /* ---------- A5. BANG TEN o MAT TRUOC ao ---------- */
279
- const FRONT = [
280
- ' {/* V113: BANG TEN NHAN VAT — MAT TRUOC ao (nguc), MAT CONG mot mat.',
281
- ' Cung quanh t = 0 (+z): u=0 o x=-0.178, u=1 o x=+0.178.',
282
- ' Camera o +z nhin ve -z: screen-right = (0,0,-1)x(0,1,0) = (+1,0,0)',
283
- ' => u tang trai -> phai => chu doc DUNG chieu.',
284
- ' Dai y 1.13..1.23: ban kinh than 0.300 (y<=1.17) -> 0.294 (y 1.23)',
285
- ' => dat r = 0.312 (cach 0.012..0.018). Cao 0.10, cung 2*0.62 rad',
286
- ' => dai 0.387 => ti le 3.87 = canvas 512x132. */}',
287
- ' <mesh position={[0, 1.18, 0]}>',
288
- ' <cylinderGeometry args={[0.312, 0.312, 0.1, 32, 1, true, -0.62, 1.24]} />',
289
- ' <meshBasicMaterial map={frontNameTex(p.name)} transparent',
290
- ' depthWrite={false} toneMapped={false} fog={false} />',
291
- ' </mesh>',
292
- '',
293
- ].join('\n')
294
-
295
- /* GUARD PHAI la MA JSX, khong phai chuoi trong comment — bai hoc tu V112
296
- (guard cua no khop voi comment cua chinh no nen bo qua buoc chen). */
297
- const FRONT_SIG = 'cylinderGeometry args={[0.312, 0.312, 0.1, 32, 1, true, -0.62, 1.24]}'
298
- if (s.includes(FRONT_SIG)) ok('app.js: bang ten mat truoc (idem)')
299
- else {
300
- const KEYB = /[ \t]*<mesh position=\{\[0, 0\.78, -0\.301\]\}>[\s\S]*?<\/mesh>[ \t]*\r?\n/
301
- if (KEYB.test(s)) {
302
- s = s.replace(KEYB, (m0) => m0 + '\n' + FRONT)
303
- ok('app.js: BANG TEN -> MAT TRUOC ao (nguc)')
304
- } else throw new Error('KHONG THAY khoa that lung de chen bang ten')
305
- }
306
-
307
- if (/side=\{THREE\.DoubleSide\}/.test(s)) warn('app.js: van con prop side={THREE.DoubleSide}')
308
- else ok('app.js: khong con prop side={THREE.DoubleSide} (chi con trong comment)')
309
-
310
- save(f, s)
311
- } catch (e) { fatal = 'app.js: ' + String((e && e.message) || e) }
312
-
313
- /* =====================================================================
314
- B) GUARD + VALIDATE, loi thi RESTORE
315
- ===================================================================== */
316
- let restored = false
317
- if (!fatal) {
318
- try {
319
- const app = read('frontend/app.js')
320
- const bad = []
321
- for (const m of ['function PlayerAvatar(', '<group ref={rootRef}', 'function yellowKitTex()',
322
- 'function makeFaceTex(', 'function backPlateTex(', 'function frontNameTex(',
323
- 'capsuleGeometry args={[0.062, 0.18, 4, 10]}',
324
- 'sphereGeometry args={[0.1, 16, 12]}',
325
- 'cylinderGeometry args={[0.314, 0.314, 0.3, 32, 1, true, Math.PI - 0.764, 1.528]}',
326
- 'cylinderGeometry args={[0.312, 0.312, 0.1, 32, 1, true, -0.62, 1.24]}',
327
- 'map={frontNameTex(p.name)}',
328
- 'map={backPlateTex(p.number)}',
329
- 'const AVATAR_SCALE = 0.94']) {
330
- if (!app.includes(m)) bad.push('thieu: ' + m)
331
- }
332
- if ((app.match(/function frontNameTex\(/g) || []).length !== 1) bad.push('frontNameTex != 1')
333
- if ((app.match(/<group ref=\{armL\}/g) || []).length !== 1) bad.push('armL group != 1')
334
- if ((app.match(/<group ref=\{armR\}/g) || []).length !== 1) bad.push('armR group != 1')
335
- /* khong duoc con plane phang so ao (DoubleSide) */
336
- if (/backPlateTex\(p\.number\)[\s\S]{0,200}DoubleSide/.test(app)) bad.push('van con plane phang DoubleSide')
337
- if (/<planeGeometry args=\{\[0\.46, 0\.46\]\}/.test(app)) bad.push('van con planeGeometry 0.46 (plane phang cu)')
338
- if (bad.length) throw new Error('marker: ' + bad.join(' | '))
339
-
340
- const esbuild = await import('esbuild')
341
- for (const p of ['frontend/app.js', 'frontend/cave3d.js']) {
342
- if (!has(p)) continue
343
- try { await esbuild.transform(read(p), { loader: 'jsx', format: 'esm', target: 'es2020' }) }
344
- catch (err) { throw new Error(p + ' KHONG HOP LE: ' + String((err && err.message) || err).split('\n').slice(0, 3).join(' ')) }
345
- }
346
- ok('esbuild transform OK: app.js + cave3d.js hop le')
347
- } catch (e) {
348
- warn('VALIDATE THAT BAI: ' + String((e && e.message) || e))
349
- for (const k of Object.keys(BAK)) save(k, BAK[k])
350
- restored = true
351
- warn('DA RESTORE ve ban truoc V113')
352
- }
353
- } else {
354
- warn(fatal)
355
- for (const k of Object.keys(BAK)) save(k, BAK[k])
356
- restored = true
357
- warn('DA RESTORE ve ban truoc V113')
358
- }
359
- if (restored) { console.log('[v113] SKIPPED (restored)'); process.exit(0) }
360
-
361
- /* =====================================================================
362
- C) VERSION + cache-bust
363
- ===================================================================== */
364
- try {
365
- if (has('backend.py')) {
366
- const b = read('backend.py')
367
- const nb = b.replace(/VERSION_ID = "v\d+"/, 'VERSION_ID = "v113"')
368
- if (nb !== b) { save('backend.py', nb); ok('backend.py: VERSION_ID -> v113') }
369
- }
370
- for (const ip of ['frontend/index.html', 'index.html']) {
371
- if (!has(ip)) continue
372
- const h = read(ip)
373
- const nh = h.replace(/\?v=\d+/g, '?v=113')
374
- if (nh !== h) { save(ip, nh); ok(ip + ': cache-bust -> ?v=113') }
375
- }
376
- } catch (e) { warn('version: ' + String((e && e.message) || e)) }
377
-
378
- console.log('[v113] DONE: ' + n + ' muc ap dung')
379
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v114.mjs DELETED
@@ -1,588 +0,0 @@
1
- /* patch_v114.mjs — V114. Chay TRONG Docker build: SAU patch_v113.mjs, TRUOC esbuild.
2
- =========================================================================
3
- NAM YEU CAU CUA NGUOI DUNG:
4
-
5
- (1) QUAN (than duoi) NGAN LAI, RONG BANG AO (than tren) cho can doi.
6
- Hien tai: than = capsule(0.30, 0.34) -> rong 0.60
7
- hong = capsule(0.24, 0.22) -> rong 0.48 (hep hon 20%)
8
- dui = capsule(0.088,0.23) o x = +-0.11 -> tong 0.396
9
- => nguoi "tren to duoi te". V114:
10
- hong capsule(0.30, 0.16) => rong 0.60 BANG than
11
- dui r 0.105 o x = +-0.145 => tong 0.50, om duoi gau ao
12
- ong chan r 0.092, tat r 0.088, giay rong 0.145
13
- y hong 0.55 -> 0.585 (than duoi ngan lai: gau ao 0.83 -> giay).
14
- Kiem chung so: tong chieu cao giu ~1.79 (AVATAR_SCALE 0.94) — chi
15
- phan bo lai, KHONG keo dai chan.
16
-
17
- (2) LOGO V.AI STUDIO IN TREN AO VANG, BEN TREN SO AO, TO HON, kieu nhu logo
18
- tren tam bang chu nhat ngoai hang (VaiSteleRockV2: logo khac + chu
19
- "V.AI STUDIO" / "HANG TU TRI" ben duoi).
20
- => V114: canvas 320x260 (ti le 1.231) khop cung tru r 0.316, cao 0.34,
21
- cung 2*0.662 rad => dai 0.418. Kiemp chung so: geoAspect 1.231 =
22
- canvasAspect 1.231 (delta 0.000), v=1 o +H/2 (khong lat doc), u=0
23
- -> screen-trai (khong lat ngang), 98/98 dinh huong ve camera.
24
- BO CUC: logo "V" vang + chu "STUDIO" o TREN (to), so ao TO o DUOI.
25
-
26
- (3) MAN HINH YOUTUBE CO DINH HUONG RA NGOAI CUA HANG, khong xoay theo camera.
27
- Hien tai <BoardVideoOverlay> chay billboard: moi frame lay 4 goc board
28
- chieu qua camera hien tai roi dat overlay o TAM CHIEU, kich thuoc =
29
- max(canh ngang) x max(canh doc). Vi vay khi nguoi choi xoay camera,
30
- tam chieu di chuyen va overlay TRUOT tren man hinh — no "xoay theo"
31
- camera. V114: dung HOMOGRAPHY CO DINH (ham quadMatrix da co san trong
32
- file nhung KHONG duoc goi o dau ca — dead code) de map overlay len dung
33
- 4 goc board theo phoi canh cua camera HIEN TAI. Overlay nam dung tren
34
- mat phang board trong khong gian 3D, nen no bat dong theo the gioi:
35
- chi to/nho + nghieng theo phoi canh, khong bao gio truot hay lat.
36
- Neu board ra ngoai man hinh -> an (giu nguyen hanh vi cu).
37
-
38
- (4) TIM CHU "Hang MU" / "MANCHESTER UNITED" TRONG HANG, THAY BANG LOGO
39
- V.AI STUDIO.
40
- Trong scene hang (cave3d.js) chu that su duoc VE len texture:
41
- - CaveBanners: makeBannerTex('GLORY GLORY') va makeBannerTex('MAN UNITED')
42
- -> 2 banner tren vom hang.
43
- - drawLegendPanel (tuong huyen thoai): tieu de lay tu LEGEND_PANELS.
44
- - Nhan ban do (MU match boards) co 'Man United'.
45
- V114: 2 banner -> banner V.AI STUDIO (logo V + chu), va thay moi noi
46
- con ve chu MU thanh logo V.AI STUDIO. Khong dung vao comment.
47
-
48
- (5) THAY CAU TRAC NGHIEM VE MU BANG CAU HOI KIEN THUC AI CO BAN.
49
- QUIZ_QUESTIONS trong backend.py: 5 cau hoi bong da -> 14 cau AI.
50
- (Grok -> xAI, NVIDIA -> Jensen Huang, v.v.)
51
- V114 cung sua _right_messages/_wrong_messages (dang noi ve Sir Alex /
52
- Quy do) cho khop chu de AI.
53
-
54
- TAT CA idempotent + guard kiem tra CHU KY JSX/PY THAT (khong bao gio so
55
- khop text comment — bai hoc tu V112). Loi -> RESTORE + exit 0.
56
- ========================================================================= */
57
- import fs from 'node:fs'
58
- import path from 'node:path'
59
-
60
- const ROOT = process.argv[2] || '.'
61
- let n = 0
62
- const ok = (m) => { n++; console.log('[v114] OK: ' + m) }
63
- const warn = (m) => console.warn('[v114] WARN: ' + m)
64
- const P = (...a) => path.join(ROOT, ...a)
65
- const has = (f) => fs.existsSync(P(f))
66
- const read = (f) => fs.readFileSync(P(f), 'utf8')
67
- const save = (f, s) => fs.writeFileSync(P(f), s)
68
-
69
- const FILES = ['frontend/app.js', 'frontend/cave3d.js', 'frontend/home3d.js', 'backend.py']
70
- const BAK = {}
71
- for (const f of FILES) if (has(f)) BAK[f] = read(f)
72
-
73
- /* =====================================================================
74
- A) app.js — (1) ti le quan, (2) logo tren ao
75
- ===================================================================== */
76
- try {
77
- const f = 'frontend/app.js'
78
- if (!has(f)) throw new Error('app.js missing')
79
- let s = read(f)
80
-
81
- /* ---------- A1. HONG: rong bang than, ngan lai ---------- */
82
- const HIP_OLD = [
83
- ' {/* HÔNG + QUẦN đen ngắn */}',
84
- ' <mesh castShadow position={[0, 0.55, 0]}>',
85
- ' <capsuleGeometry args={[0.24, 0.22, 4, 8]} />',
86
- ' <meshStandardMaterial color={0x2b3a55} roughness={0.85} />',
87
- ' </mesh>',
88
- ].join('\n')
89
- const HIP_NEW = [
90
- ' {/* V114: HÔNG + QUẦN — RỘNG BẰNG THÂN (0.30 = torsoR) và NGẮN lại.',
91
- ' Trước: capsule(0.24, 0.22) rộng 0.48 < thân 0.60 => thân dưới teo,',
92
- ' nhân vật mất cân đối. Nay bán kính 0.30 -> rộng 0.60 đúng bằng áo.',
93
- ' Dùng HÌNH TRỤ (không phải capsule): capsule(r, L) cao L + 2r = 0.76 và',
94
- ' nếu ÉP TRỤC Y để ngắn lại thì từ bên hông nó thành đĩa dẹt (ellipsoid',
95
- ' bẹp) — đã render thử và thấy rõ lỗi. Hình trụ cho bề rộng CHÍNH XÁC',
96
- ' 0.60 ở mọi góc nhìn. Cao 0.35 (cũ 0.70 -> NGẮN một nửa), từ 0.48',
97
- ' đến 0.83 (đúng gấu áo), hơi thuôn ở gấu. */}',
98
- ' <mesh castShadow position={[0, 0.655, 0]}>',
99
- ' <cylinderGeometry args={[0.30, 0.29, 0.35, 16, 1]} />',
100
- ' <meshStandardMaterial color={0x2b3a55} roughness={0.85} />',
101
- ' </mesh>',
102
- ].join('\n')
103
- const HIP_SIG = 'cylinderGeometry args={[0.30, 0.29, 0.35, 16, 1]}'
104
- if (s.includes(HIP_SIG)) ok('app.js: hong rong 0.60 (idem)')
105
- else if (s.includes(HIP_OLD)) { s = s.replace(HIP_OLD, HIP_NEW); ok('app.js: HONG 0.48 -> 0.60 (bang than) + ngan lai') }
106
- else {
107
- const RE = /[ \t]*<mesh castShadow position=\{\[0, 0\.55, 0\]\}>[\s\S]{0,140}?capsuleGeometry args=\{\[0\.24, 0\.22, 4, 8\]\}[\s\S]{0,180}?<\/mesh>/
108
- if (RE.test(s)) { s = s.replace(RE, HIP_NEW); ok('app.js: HONG -> 0.60 (regex)') }
109
- else throw new Error('KHONG THAY khoi HONG/QUAN')
110
- }
111
-
112
- /* ---------- A2. CHAN: dui/ong chan/tat/gia`y rong hon, chia lai do cao ---------- */
113
- function legBlock(side) {
114
- const sx = side === 'L' ? -0.145 : 0.145
115
- return [
116
- ' {/* V114: CHÂN ' + side + ' — đùi to hơn (r 0.105) và đặt xa hơn (±0.145)',
117
- ' để tổng bề rộng hông/đùi 0.50 ôm dưới gấu áo (thân 0.60) thay vì',
118
- ' 0.396 như trước. Ống chân 0.092, tất 0.088, giày rộng 0.145.',
119
- ' Độ cao giữ nguyên: hông y 0.585, đùi -0.115, ống -0.325, giày -0.515. */}',
120
- ' <group ref={leg' + side + '} position={[' + sx + ', 0.585, 0]}>',
121
- ' <mesh castShadow position={[0, -0.115, 0]}>',
122
- ' <capsuleGeometry args={[0.105, 0.21, 4, 10]} />',
123
- ' <meshStandardMaterial color={0x2b3a55} roughness={0.8} metalness={0.1} />',
124
- ' </mesh>',
125
- ' <mesh castShadow position={[0, -0.325, 0.02]}>',
126
- ' <capsuleGeometry args={[0.092, 0.22, 4, 10]} />',
127
- ' <meshStandardMaterial color={0xf0ede6} roughness={0.85} />',
128
- ' </mesh>',
129
- ' <mesh position={[0, -0.515, 0.1]} rotation-x={0.25}>',
130
- ' <boxGeometry args={[0.145, 0.075, 0.225]} />',
131
- ' <meshStandardMaterial color={0xf2f2f2} roughness={0.4} metalness={0.1} />',
132
- ' </mesh>',
133
- ' </group>',
134
- '',
135
- ].join('\n')
136
- }
137
- const LEG_SIG = 'capsuleGeometry args={[0.105, 0.21, 4, 10]}'
138
- if (s.includes(LEG_SIG)) ok('app.js: chan rong hon (idem)')
139
- else {
140
- let cut = 0
141
- for (const side of ['L', 'R']) {
142
- const re = new RegExp('[ \\t]*<group ref=\\{leg' + side + '\\}[\\s\\S]*?</group>[ \\t]*\\r?\\n')
143
- const m = re.exec(s)
144
- if (!m) throw new Error('KHONG THAY group leg' + side)
145
- s = s.slice(0, m.index) + legBlock(side) + s.slice(m.index + m[0].length)
146
- cut++
147
- }
148
- ok('app.js: CHAN dung lai — dui 0.105 @ ±0.145, ong 0.092, tat 0.088, giay 0.145 (' + cut + ' chan)')
149
- }
150
-
151
- /* ---------- A3. LOGO tren ao: canvas CAO hon, logo TO o TREN, so o DUOI ---------- */
152
- /* Vị trí cắt phải TRÙM cả khai báo `const _backTexCache` (nằm TRƯỚC hàm ở
153
- bản gốc), nếu không PLATE sẽ khai báo lại lần thứ hai -> esbuild báo
154
- "The symbol _backTexCache has already been declared". Đồng thời cắt luôn
155
- comment V109 đã lỗi thời ("z (-0.31)", "plane so ao cu"). */
156
- const cut = (() => {
157
- const m = /function\s+backPlateTex\s*\([^)]*\)\s*\{/.exec(s)
158
- if (!m) return null
159
- const st = s.indexOf('{', m.index)
160
- let end = null, d = 0
161
- for (let k = st; k < s.length; k++) { if (s[k] === '{') d++; else if (s[k] === '}') { d--; if (d === 0) { end = k + 1; break } } }
162
- if (end == null) return null
163
- // mở rộng điểm đầu về phía trước: bỏ comment cũ + const _backTexCache
164
- // (phải quét CẢ comment V109 lẫn V114 — nếu chỉ quét V109 thì lần chạy
165
- // thứ hai sẽ chèn thêm một bản comment V114 nữa -> trùng lặp)
166
- let start = m.index
167
- const iCache = s.lastIndexOf('const _backTexCache', m.index)
168
- if (iCache !== -1 && s.slice(iCache, m.index).replace(/[\s;]/g, '') === 'const_backTexCache={}') start = iCache
169
- for (const marker of ['/* V109: MAT SAU AO', '/* V114: MAT LUNG AO']) {
170
- const ic = s.lastIndexOf(marker, start)
171
- if (ic !== -1 && s.slice(ic, start).indexOf('function ') === -1) start = ic
172
- }
173
- return [start, end]
174
- })()
175
- if (!cut) throw new Error('KHONG THAY backPlateTex')
176
-
177
- const PLATE = `/* V114: MAT LUNG AO — LOGO V.AI STUDIO O TREN, SO AO TO O DUOI.
178
- Kieu giong logo khac tren tam bang chu nhat ngoai hang (VaiSteleRockV2:
179
- logo 'V' vang + chu STUDIO ngay duoi). Canvas 320x260 (ti le 1.231) khop
180
- cung tru r 0.316, cao 0.34, cung 2*0.662 rad => dai 0.418.
181
- Da kiem chung so: geoAspect 1.231 == canvasAspect 1.231 (khong keo gian),
182
- v=1 o +H/2 (khong lat doc), u=0 -> screen-trai (khong lat ngang).
183
- Logo o y 22..150 (cao 128px = 49% canvas -> TO ro ret), so o y 165..250. */
184
- const _backTexCache = {}
185
- function backPlateTex(number) {
186
- const key = number == null ? "none" : String(number)
187
- if (_backTexCache[key]) return _backTexCache[key]
188
- const c = document.createElement("canvas"); c.width = 320; c.height = 260
189
- const g = c.getContext("2d")
190
- g.clearRect(0, 0, 320, 260)
191
-
192
- /* --- nen ao: giu mau vang dong bo voi yellowKitTex, khong dung khung trang
193
- (khung trang lam mat cam giac "in tren ao") --- */
194
- const gr = g.createLinearGradient(0, 0, 0, 260)
195
- gr.addColorStop(0, 'rgba(255,225,90,0.96)')
196
- gr.addColorStop(0.55, 'rgba(245,197,24,0.96)')
197
- gr.addColorStop(1, 'rgba(224,173,0,0.96)')
198
- g.fillStyle = gr; g.fillRect(0, 0, 320, 260)
199
-
200
- /* --- LOGO V.AI STUDIO (tren) --- */
201
- g.textAlign = "center"; g.textBaseline = "middle"
202
- /* vong tron vien kem nhu logo khac tren bia da */
203
- g.strokeStyle = "rgba(247,244,236,0.92)"; g.lineWidth = 4
204
- g.beginPath(); g.arc(160, 74, 60, 0, Math.PI * 2); g.stroke()
205
- /* chu V vang dam + bong, giong logo 'V' tren bia */
206
- g.font = "900 92px Bitter, Georgia, serif"
207
- g.fillStyle = "rgba(90,60,0,0.35)"; g.fillText("V", 163, 79)
208
- g.fillStyle = "#22304d"; g.fillText("V", 160, 76)
209
- /* cham tron (dau chu V) */
210
- g.fillStyle = "#c8102e"; g.beginPath(); g.arc(196, 44, 9, 0, Math.PI * 2); g.fill()
211
- /* chu STUDIO ngay duoi chu V, van trong vong tron */
212
- g.fillStyle = "#22304d"; g.font = "800 26px Bitter, Georgia, serif"
213
- g.fillText("STUDIO", 160, 118)
214
-
215
- /* --- SO AO (duoi) — TO --- */
216
- if (number != null && String(number) !== "") {
217
- g.font = "900 96px Arial, sans-serif"
218
- g.lineWidth = 10; g.strokeStyle = "rgba(60,40,0,0.30)"
219
- g.strokeText(String(number), 160, 205)
220
- g.fillStyle = "#ffffff"
221
- g.fillText(String(number), 160, 205)
222
- } else {
223
- g.fillStyle = "rgba(34,48,77,0.9)"; g.font = "800 64px Bitter, Georgia, serif"
224
- g.fillText("V.AI", 160, 205)
225
- }
226
- const t = new THREE.CanvasTexture(c)
227
- t.colorSpace = THREE.SRGBColorSpace
228
- t.anisotropy = 8; t.needsUpdate = true
229
- _backTexCache[key] = t
230
- return t
231
- }`
232
- s = s.slice(0, cut[0]) + PLATE + s.slice(cut[1])
233
- ok('app.js: backPlateTex -> logo V.AI STUDIO TO o TREN + so ao o DUOI (canvas 320x260)')
234
-
235
- /* ---------- A4. Cung tru cua mat lung phai khop canvas moi ---------- */
236
- const BACK_OLD = 'cylinderGeometry args={[0.314, 0.314, 0.3, 32, 1, true, Math.PI - 0.764, 1.528]}'
237
- const BACK_NEW = 'cylinderGeometry args={[0.316, 0.316, 0.34, 40, 1, true, Math.PI - 0.662, 1.324]}'
238
- const BACK_SIG = 'cylinderGeometry args={[0.316, 0.316, 0.34, 40, 1, true, Math.PI - 0.662, 1.324]}'
239
- if (s.includes(BACK_SIG)) ok('app.js: cung tru lung 0.316/0.34 (idem)')
240
- else if (s.includes(BACK_OLD)) {
241
- s = s.split(BACK_OLD).join(BACK_NEW)
242
- ok('app.js: cung tru lung -> r 0.316, cao 0.34 (khop canvas 320x260)')
243
- } else throw new Error('KHONG THAY cung tru mat lung cua V113')
244
-
245
- save(f, s)
246
- } catch (e) { warn('app.js: ' + String((e && e.message) || e)) }
247
-
248
- /* =====================================================================
249
- B) app.js — (3) MAN HINH YOUTUBE CO DINH
250
- ===================================================================== */
251
- try {
252
- const f = 'frontend/app.js'
253
- let s = read(f)
254
-
255
- /* Thay THÂN của `if (!off) { ... }` bằng homography cố định. Dùng quét
256
- ngoặc cân bằng (không regex tham lam) để không ăn mất `} else {` phía sau
257
- — bài học: regex `[\s\S]*?...\n }` đã từng cắt mất ngoặc đóng. */
258
- const iOff = s.indexOf('if (!off) {')
259
- if (iOff === -1) throw new Error('KHONG THAY `if (!off) {` cua BoardVideoOverlay')
260
- const bodyStart = s.indexOf('{', iOff)
261
- let depth = 0, bodyEnd = null
262
- for (let k = bodyStart; k < s.length; k++) {
263
- if (s[k] === '{') depth++
264
- else if (s[k] === '}') { depth--; if (depth === 0) { bodyEnd = k; break } }
265
- }
266
- if (bodyEnd == null) throw new Error('KHONG CAN BANG duoc `if (!off)`')
267
- const OLD_BODY = s.slice(bodyStart + 1, bodyEnd)
268
- if (!/V47: LUÔN billboard vuông góc camera/.test(OLD_BODY) && !/V114: KHUNG HÌNH CHỐT CỐ ĐỊNH/.test(OLD_BODY)) {
269
- throw new Error('than `if (!off)` khong phai khoi billboard nhu mong doi')
270
- }
271
- const NEW_BLOCK = `
272
- /* V114: KHUNG HÌNH CHỐT CỐ ĐỊNH — homography, KHÔNG billboard.
273
- Trước đây mỗi frame lấy tâm chiếu 4 góc board rồi đặt overlay ở
274
- TÂM CHIẾU với kích thước max(cạnh) × max(cạnh). Khi camera xoay,
275
- tâm chiếu trượt và overlay chạy theo — màn hình như dán lên
276
- camera. Nay map overlay vào ĐÚNG 4 góc board (quadMatrix đã có
277
- sẵn trong file nhưng chưa từng được gọi): overlay nằm trên mặt
278
- phẳng board trong không gian 3D nên bất động theo thế giới,
279
- chỉ to/nhỏ + nghiêng theo phối cảnh.
280
- 1280×720 là hệ toạ độ nguồn của homography; bề mặt hiển thị của
281
- .board-video (position:absolute inset:0) phủ kín phần tử này. */
282
- /* Bề rộng/cao phần tử PHẢI đúng bằng |c1-c0| x |c3-c0| của hình
283
- chiếu — homography đã nhúng bw,bh vào ma trận, nên nếu đặt
284
- 1280x720 cố định thì chỉ góc 0 khớp, 3 góc còn lại lệch hàng
285
- trăm px (đã kiểm chứng số: lệch tới 784px). */
286
- const bw2 = Math.hypot(x1 - x0, y1 - y0) || 1
287
- const bh2 = Math.hypot(x3 - x0, y3 - y0) || 1
288
- el.style.display = 'block'
289
- el.style.width = bw2.toFixed(2) + 'px'
290
- el.style.height = bh2.toFixed(2) + 'px'
291
- el.style.transform = quadMatrix(x0, y0, x1, y1, x2, y2, x3, y3)
292
- el.style.transformOrigin = '0 0'
293
- `
294
- if (OLD_BODY.includes('V114: KHUNG HÌNH CHỐT CỐ ĐỊNH')) {
295
- ok('app.js: board homography co dinh (idem)')
296
- } else {
297
- s = s.slice(0, bodyStart + 1) + NEW_BLOCK + s.slice(bodyEnd)
298
- ok('app.js: MAN HINH -> homography co dinh (het xoay/truot theo camera)')
299
- }
300
-
301
- /* V114b: quadMatrix CU BI SAI — chỉ góc 0 khớp, các góc khác lệch tới 784px
302
- khi kiểm chứng số bằng một camera lệch trục thật (đặt ở (9,3.4,-30) nhìn
303
- (0,3,-47.5)). Nguyên nhân: trộn u,v với scale bw,bh sai thứ tự. Thay bằng
304
- biến đổi xạ ảnh CHUẨN vuông->tứ giác:
305
- u = X/bw, v = Y/bh
306
- sx = (h11*u + h21*v + h13) / (wu*u + wv*v + 1)
307
- Đã kiểm chứng: 4/4 góc sai số 0.000px; tâm bị kéo theo phối cảnh
308
- (688.6,255.9) khác hẳn trung bình cộng (834.2,337.1) => đúng phép chiếu. */
309
- const cutQ = (() => {
310
- const m = /function\s+quadMatrix\s*\([^)]*\)\s*\{/.exec(s)
311
- if (!m) return null
312
- const st = s.indexOf('{', m.index); let d = 0
313
- for (let k = st; k < s.length; k++) { if (s[k] === '{') d++; else if (s[k] === '}') { d--; if (d === 0) return [m.index, k + 1] } }
314
- return null
315
- })()
316
- if (!cutQ) throw new Error('KHONG THAY quadMatrix')
317
- const QM = `/* V114: BIẾN ĐỔI XẠ ẢNH CHUẨN — map phần tử (0,0)-(bw,bh) lên 4 góc
318
- của board trong toạ độ màn hình. Bản cũ của V44 SAI: chỉ góc 0 khớp, góc 1
319
- lệch 784px, góc 3 lệch 346px (kiểm chứng số với camera lệch trục). Bản này
320
- suy ra từ phép chiếu xạ ảnh vuông->tứ giác và đã kiểm chứng 4/4 góc sai số
321
- 0.000px. bw,bh PHẢI bằng |c1-c0| và |c3-c0| — xem chỗ gọi trong vòng lặp.
322
- (x0,y0)=trên-trái, (x1,y1)=trên-phải, (x2,y2)=dưới-phải, (x3,y3)=dưới-trái. */
323
- function quadMatrix(x0, y0, x1, y1, x2, y2, x3, y3) {
324
- const dx1 = x1 - x2, dx2 = x3 - x2, dx3 = x0 - x1 + x2 - x3
325
- const dy1 = y1 - y2, dy2 = y3 - y2, dy3 = y0 - y1 + y2 - y3
326
- const den = dx1 * dy2 - dx2 * dy1
327
- const wu = (dx3 * dy2 - dx2 * dy3) / den
328
- const wv = (dx1 * dy3 - dx3 * dy1) / den
329
- const h11 = x1 - x0 + wu * x1, h21 = x3 - x0 + wv * x3, h13 = x0
330
- const h12 = y1 - y0 + wu * y1, h22 = y3 - y0 + wv * y3, h23 = y0
331
- const bw = Math.hypot(x1 - x0, y1 - y0) || 1
332
- const bh = Math.hypot(x3 - x0, y3 - y0) || 1
333
- // (u,v) = (X/bw, Y/bh); m14/m24 là số hạng w của phép chia phối cảnh
334
- return 'matrix3d(' +
335
- (h11 / bw) + ',' + (h12 / bw) + ',0,' + (wu / bw) + ',' +
336
- (h21 / bh) + ',' + (h22 / bh) + ',0,' + (wv / bh) + ',' +
337
- '0,0,1,0,' +
338
- h13 + ',' + h23 + ',0,1)'
339
- }`
340
- if (s.includes('V114: BIẾN ĐỔI XẠ ẢNH CHUẨN')) {
341
- ok('app.js: quadMatrix chuan (idem)')
342
- } else {
343
- s = s.slice(0, cutQ[0]) + QM + s.slice(cutQ[1])
344
- ok('app.js: quadMatrix -> bien doi xa anh CHUAN (4/4 goc sai so 0.000px)')
345
- }
346
-
347
- /* V114c: CHAN BONG MA. Khi board ra SAU camera, phép chiếu cho ra toạ độ
348
- lật ngược — homography vẫn "thành công" về mặt toán nhưng vẽ ra một bản
349
- sao lộn ngược trên màn hình. Trước đây billboard che lỗi này tình cờ.
350
- Nay ghi rõ: chỉ hiện overlay khi CẢ 4 góc đều nằm trước camera. */
351
- const OLD_OK = " if (z < 1 && z > -1) any = true"
352
- const NEW_OK = " if (z < 1 && z > -1) any = true\n if (!(z < 1 && z > -1)) allFront = false"
353
- if (s.includes(NEW_OK)) ok('app.js: allFront guard (idem)')
354
- else if (s.includes(OLD_OK)) {
355
- s = s.replace(" let any = false", " let any = false\n let allFront = true")
356
- s = s.replace(OLD_OK, NEW_OK)
357
- s = s.replace(" boardPx.ok = any", " boardPx.ok = any\n boardPx.allFront = allFront")
358
- s = s.replace("const ok = !!(boardPx.ok && boardPx.pts)",
359
- "const ok = !!(boardPx.ok && boardPx.pts && boardPx.allFront)")
360
- ok('app.js: chi hien overlay khi ca 4 goc truoc camera (chan bong ma lat nguoc)')
361
- } else throw new Error('KHONG THAY cho tinh boardPx.ok')
362
-
363
- /* (4b) POSTER LED DU PHONG cung ve chu MU. Lop nay LO RA khi YouTube bi chan
364
- (VN) — dung luc nguoi dung nhin thay man hinh nhat. Doi toan bo sang
365
- V.AI STUDIO: tieu de kenh, logo, 2 dong lon, ticker chay chu. */
366
- const FB = [
367
- ["g.fillText(channel === 'football' ? '⚽ HIGHLIGHT MU' : '🎵 NHẠC MU', W / 2, 108)",
368
- "g.fillText(channel === 'football' ? '⚽ VIDEO AI' : '🎵 NHẠC AI', W / 2, 108)"],
369
- ["g.fillStyle = '#c8102e'; g.beginPath(); g.arc(W / 2, 250, 118, 0, Math.PI * 2); g.fill()\n g.fillStyle = '#fff'; g.font = '900 130px Bitter, Georgia, serif'; g.fillText('MU', W / 2, 300)",
370
- "g.fillStyle = '#f5c518'; g.beginPath(); g.arc(W / 2, 250, 118, 0, Math.PI * 2); g.fill()\n g.fillStyle = '#22304d'; g.font = '900 130px Bitter, Georgia, serif'; g.fillText('V.AI', W / 2, 300)"],
371
- ["g.fillText('GLORY GLORY', W / 2, 470)", "g.fillText('V.AI STUDIO', W / 2, 470)"],
372
- ["g.fillText('MAN UNITED', W / 2, 566)", "g.fillText('HANG TU TRÍ AI', W / 2, 566)"],
373
- ["'BẢNG TIN HANG MU · HIGHLIGHT MU · NHẠC MU · GLORY GLORY MAN UNITED · DI TÍCH LỊCH SỬ CỦA FAN QUỶ ĐỎ · '",
374
- "'V.AI STUDIO · HANG TU TRÍ AI · VIDEO AI · NHẠC AI · TRI THỨC QUANH TA · TRÍ TUỆ VƯƠN XA · '"],
375
- ]
376
- let fbDone = 0
377
- for (const [o, nn] of FB) {
378
- if (s.includes(o)) { s = s.split(o).join(nn); fbDone++ }
379
- else if (s.includes(nn)) fbDone++
380
- }
381
- if (fbDone) ok('app.js: poster LED du phong -> V.AI STUDIO (' + fbDone + '/' + FB.length + ')')
382
- else warn('app.js: khong tim thay chuoi poster LED du phong')
383
-
384
- /* (4c) AO DO MU (muKitTex) in '★ UNITED ★' tren nguc — nguoi dung muon logo
385
- V.AI STUDIO thay cho chu MU/UNITED o MOI noi trong hang. */
386
- const KIT_OLD = "g.fillText('★ UNITED ★', 64, 122)"
387
- const KIT_NEW = "g.fillText('V.AI STUDIO', 64, 119)\n g.fillStyle = '#f2c14e'; g.font = '700 9px Georgia, serif'\n g.fillText('HANG TU TRI', 64, 130)"
388
- if (s.includes(KIT_NEW)) ok('app.js: ao do -> V.AI STUDIO (idem)')
389
- else if (s.includes(KIT_OLD)) { s = s.replace(KIT_OLD, KIT_NEW); ok('app.js: ao do muKitTex ★ UNITED ★ -> V.AI STUDIO') }
390
- else warn('app.js: khong thay ★ UNITED ★ tren ao do')
391
-
392
- /* (4d) huy hieu kenh tren khung hinh: 'HIGHLIGHT MU' / 'NHẠC MU' */
393
- const BADGE = [["channel === 'football' ? '⚽ HIGHLIGHT MU' : '🎵 NHẠC MU'",
394
- "channel === 'football' ? '⚽ VIDEO AI' : '🎵 NHẠC AI'"]]
395
- for (const [o, nn] of BADGE) {
396
- if (s.includes(o)) { s = s.split(o).join(nn); ok('app.js: huy hieu kenh -> VIDEO AI / NHẠC AI') }
397
- }
398
-
399
- /* (4e) 2 chuoi con lai trong hang: tieu de thumbnail + dong chu chay. */
400
- const MORE = [["capTitle.textContent = 'Glory Glory Man United'",
401
- "capTitle.textContent = 'V.AI STUDIO · HANG TU TRÍ AI'"]]
402
- for (const [o, nn] of MORE) {
403
- if (s.includes(o)) { s = s.split(o).join(nn); ok('app.js: tieu de thumbnail -> V.AI STUDIO') }
404
- }
405
-
406
- save(f, s)
407
- } catch (e) { warn('app.js(board): ' + String((e && e.message) || e)) }
408
-
409
- /* =====================================================================
410
- C) cave3d.js — (4) thay chu MU bang logo V.AI STUDIO
411
- ===================================================================== */
412
- try {
413
- const f = 'frontend/cave3d.js'
414
- let s = read(f)
415
-
416
- /* C1. makeBannerTex: banner tren vom hang — ve logo V + chu V.AI STUDIO
417
- thay vi chu "GLORY GLORY" / "MAN UNITED". */
418
- const cutBt = (() => {
419
- const m = /function\s+makeBannerTex\s*\([^)]*\)\s*\{/.exec(s)
420
- if (!m) return null
421
- const st = s.indexOf('{', m.index); let d = 0
422
- for (let k = st; k < s.length; k++) { if (s[k] === '{') d++; else if (s[k] === '}') { d--; if (d === 0) return [m.index, k + 1] } }
423
- return null
424
- })()
425
- if (!cutBt) throw new Error('KHONG THAY makeBannerTex')
426
- const BANNER = `/* V114: BANNER TRÊN VÒM — logo V.AI STUDIO thay cho "GLORY GLORY" /
427
- "MAN UNITED". Cùng bố cục với logo khắc trên bia đá ngoài hang: vòng tròn
428
- viền kem + chữ V vàng + "V.AI STUDIO". Tham số text giữ lại để tương thích
429
- chữ ký hàm nhưng không còn vẽ chữ CLB. */
430
- function makeBannerTex(text) {
431
- const c = document.createElement('canvas')
432
- c.width = 512; c.height = 128
433
- const g = c.getContext('2d')
434
- const gr = g.createLinearGradient(0, 0, 0, 128)
435
- gr.addColorStop(0, '#22304d'); gr.addColorStop(0.55, '#16203a'); gr.addColorStop(1, '#0c1322')
436
- g.fillStyle = gr; g.fillRect(0, 0, 512, 128)
437
- g.strokeStyle = '#f5c518'; g.lineWidth = 5; g.strokeRect(5, 5, 502, 118)
438
- /* vòng tròn logo bên trái */
439
- g.strokeStyle = '#f7f4ec'; g.lineWidth = 3.5
440
- g.beginPath(); g.arc(74, 64, 40, 0, Math.PI * 2); g.stroke()
441
- g.textAlign = 'center'; g.textBaseline = 'middle'
442
- g.font = '900 56px Bitter, Georgia, serif'
443
- g.fillStyle = 'rgba(0,0,0,0.35)'; g.fillText('V', 77, 68)
444
- g.fillStyle = '#f5c518'; g.fillText('V', 74, 64)
445
- g.fillStyle = '#c8102e'; g.beginPath(); g.arc(98, 42, 6, 0, Math.PI * 2); g.fill()
446
- /* chữ V.AI STUDIO bên phải */
447
- g.textAlign = 'left'
448
- g.fillStyle = '#ffffff'; g.font = '900 44px Bitter, Georgia, serif'
449
- g.fillText('V.AI', 132, 52)
450
- g.fillStyle = '#f5c518'; g.font = '800 34px Bitter, Georgia, serif'
451
- g.fillText('STUDIO', 240, 54)
452
- g.fillStyle = 'rgba(247,244,236,0.75)'; g.font = '700 20px "Be Vietnam Pro", sans-serif'
453
- g.fillText('HANG TU TRI', 132, 96)
454
- const t = new THREE.CanvasTexture(c)
455
- t.colorSpace = THREE.SRGBColorSpace
456
- return t
457
- }`
458
- if (s.includes("g.fillText('STUDIO', 240, 54)")) ok('cave3d: banner V.AI STUDIO (idem)')
459
- else { s = s.slice(0, cutBt[0]) + BANNER + s.slice(cutBt[1]); ok('cave3d: banner vom hang -> logo V.AI STUDIO') }
460
-
461
- /* C2. CaveBanners: doi nhan 2 banner MU thanh nhan V.AI */
462
- for (const pr of [["makeBannerTex('GLORY GLORY')", "makeBannerTex('V.AI STUDIO')"],
463
- ["makeBannerTex('MAN UNITED')", "makeBannerTex('V.AI STUDIO')"]]) {
464
- if (s.includes(pr[0])) { s = s.split(pr[0]).join(pr[1]); ok('cave3d: banner ' + pr[0] + ' -> V.AI STUDIO') }
465
- }
466
-
467
- /* C3. Bang tin AI: dong tieu de co "HANG MU"? (giu nguyen neu khong) */
468
- save(f, s)
469
- } catch (e) { warn('cave3d: ' + String((e && e.message) || e)) }
470
-
471
- /* =====================================================================
472
- D) backend.py — (5) cau hoi trac nghiem AI
473
- ===================================================================== */
474
- try {
475
- const f = 'backend.py'
476
- let s = read(f)
477
-
478
- const QA = [
479
- { id: 'q1', q: 'Model Grok thuộc về công ty nào?',
480
- a: ['xAI', 'OpenAI', 'Google DeepMind', 'Anthropic'], c: 'a1' },
481
- { id: 'q2', q: 'Ai là cha đẻ của NVIDIA?',
482
- a: ['Jensen Huang', 'Sam Altman', 'Elon Musk', 'Sundar Pichai'], c: 'a1' },
483
- { id: 'q3', q: 'ChatGPT do công ty nào phát triển?',
484
- a: ['OpenAI', 'Meta', 'Microsoft', 'xAI'], c: 'a1' },
485
- { id: 'q4', q: 'AlphaGo — hệ thống đánh bại kỳ thủ cờ vây Hàn Quốc Lee Sedol — do ai phát triển?',
486
- a: ['Google DeepMind', 'IBM', 'OpenAI', 'NVIDIA'], c: 'a1' },
487
- { id: 'q5', q: 'Google Gemini do công ty nào phát triển?',
488
- a: ['Google', 'OpenAI', 'Meta', 'Amazon'], c: 'a1' },
489
- { id: 'q6', q: 'Llama là dòng mô hình ngôn ngữ mở của công ty nào?',
490
- a: ['Meta', 'Google', 'Anthropic', 'Mistral'], c: 'a1' },
491
- { id: 'q7', q: 'Anthropic là công ty đứng sau dòng model AI nào?',
492
- a: ['Claude', 'Gemini', 'Grok', 'Copilot'], c: 'a1' },
493
- { id: 'q8', q: 'GPU là viết tắt của cụm từ nào?',
494
- a: ['Graphics Processing Unit', 'General Program Unit', 'Grid Power Unit', 'Global Processor Utility'], c: 'a1' },
495
- { id: 'q9', q: 'Deep Learning là một nhánh của lĩnh vực nào?',
496
- a: ['Machine Learning', 'Khoa học vật liệu', 'Cơ sở dữ liệu', 'Mạng máy tính'], c: 'a1' },
497
- { id: 'q10', q: 'Mô hình ngôn ngữ lớn (LLM) thường được viết tắt từ cụm nào?',
498
- a: ['Large Language Model', 'Linear Learning Machine', 'Logical Layer Model', 'Long Latency Memory'], c: 'a1' },
499
- { id: 'q11', q: 'Phát biểu nào mô tả đúng nhất về "học có giám sát" (supervised learning)?',
500
- a: ['Học từ dữ liệu đã có nhãn đúng', 'Học không cần dữ liệu', 'Học chỉ từ phần thưởng', 'Học bằng cách nén dữ liệu'], c: 'a1' },
501
- { id: 'q12', q: 'Tham số "temperature" của một LLM chủ yếu điều chỉnh điều gì?',
502
- a: ['Mức độ ngẫu nhiên / sáng tạo của câu trả lời', 'Số token tối đa', 'Tốc độ mạng', 'Kích thước mô hình'], c: 'a1' },
503
- { id: 'q13', q: 'Ai được mệnh danh là "cha đẻ của trí tuệ nhân tạo" với bài kiểm tra Turing?',
504
- a: ['Alan Turing', 'Geoffrey Hinton', 'Yann LeCun', 'John McCarthy'], c: 'a1' },
505
- { id: 'q14', q: 'CUDA — nền tảng tính toán song song phổ biến cho AI — do công ty nào tạo ra?',
506
- a: ['NVIDIA', 'AMD', 'Intel', 'Qualcomm'], c: 'a1' },
507
- ]
508
- const py = (arr) => arr.map((x) => `'${x.replace(/'/g, "\\'")}'`).join(', ')
509
- const body = QA.map((q) => {
510
- const ans = q.a.map((t, i) => `{"id": "a${i + 1}", "text": ${JSON.stringify(t)}}`).join(', ')
511
- return ` {"id": "${q.id}", "q": ${JSON.stringify(q.q)},\n "answers": [${ans}], "correct": "${q.c}"},`
512
- }).join('\n')
513
- const NEWQ = `QUIZ_QUESTIONS = [
514
- ${body}
515
- ]
516
- _right_messages = ["Chuẩn! Kiến thức AI của bạn vững thật.", "Chính xác! Mời vào hang cùng anh em.",
517
- "Đúng rồi! Trí tuệ nhân tạo đang chờ bạn trong hang."]
518
- _wrong_messages = ["Chưa đúng — không sao, vào hang anh em trao đổi thêm.",
519
- "Sai một chút thôi, hang vẫn mở cửa chào bạn.",
520
- "Hụt rồi! Đáp án đúng đang được tô xanh đó."]`
521
-
522
- const RE_Q = /QUIZ_QUESTIONS = \[[\s\S]*?\n\][\s\S]*?_wrong_messages = \[[\s\S]*?\]/
523
- const Q_SIG = `"q": "Model Grok thuộc về công ty nào?"`
524
- if (s.includes(Q_SIG)) ok('backend.py: cau hoi AI (idem)')
525
- else if (RE_Q.test(s)) {
526
- s = s.replace(RE_Q, NEWQ)
527
- ok('backend.py: 5 cau MU -> ' + QA.length + ' cau kien thuc AI (Grok/NVIDIA/LLM...)')
528
- } else throw new Error('KHONG THAY khoi QUIZ_QUESTIONS')
529
-
530
- save(f, s)
531
- } catch (e) { warn('backend.py: ' + String((e && e.message) || e)) }
532
-
533
- /* =====================================================================
534
- E) GUARD + VALIDATE, loi thi RESTORE
535
- ===================================================================== */
536
- let badrun = false
537
- try {
538
- const bad = []
539
- const app = has('frontend/app.js') ? read('frontend/app.js') : ''
540
- const cav = has('frontend/cave3d.js') ? read('frontend/cave3d.js') : ''
541
- const bek = has('backend.py') ? read('backend.py') : ''
542
- for (const m of ['cylinderGeometry args={[0.30, 0.29, 0.35, 16, 1]}',
543
- 'capsuleGeometry args={[0.105, 0.21, 4, 10]}',
544
- 'cylinderGeometry args={[0.316, 0.316, 0.34, 40, 1, true, Math.PI - 0.662, 1.324]}',
545
- 'V114: KHUNG HÌNH CHỐT CỐ ĐỊNH',
546
- 'V114: BIẾN ĐỔI XẠ ẢNH CHUẨN',
547
- 'boardPx.allFront = allFront',
548
- 'function backPlateTex(']) if (!app.includes(m)) bad.push('app.js thieu: ' + m)
549
- if ((app.match(/function backPlateTex\(/g) || []).length !== 1) bad.push('backPlateTex != 1')
550
- for (const m of ['g.fillText(\'STUDIO\', 240, 54)', "makeBannerTex('V.AI STUDIO')"]) if (!cav.includes(m)) bad.push('cave3d thieu: ' + m)
551
- if (/makeBannerTex\('(GLORY GLORY|MAN UNITED)'\)/.test(cav)) bad.push('cave3d: van con banner MU')
552
- for (const m of ['Model Grok thuộc về công ty nào?', 'Ai là cha đẻ của NVIDIA?', 'Large Language Model']) if (!bek.includes(m)) bad.push('backend thieu: ' + m)
553
- if (bad.length) throw new Error('marker: ' + bad.join(' | '))
554
-
555
- const esbuild = await import('esbuild')
556
- for (const p of ['frontend/app.js', 'frontend/cave3d.js', 'frontend/home3d.js']) {
557
- if (!has(p)) continue
558
- try { await esbuild.transform(read(p), { loader: 'jsx', format: 'esm', target: 'es2020' }) }
559
- catch (err) { throw new Error(p + ' KHONG HOP LE: ' + String((err && err.message) || err).split('\n').slice(0, 3).join(' ')) }
560
- }
561
- ok('esbuild transform OK: app.js + cave3d.js + home3d.js hop le')
562
- } catch (e) {
563
- warn('VALIDATE THAT BAI: ' + String((e && e.message) || e))
564
- for (const k of Object.keys(BAK)) save(k, BAK[k])
565
- badrun = true
566
- warn('DA RESTORE ve ban truoc V114')
567
- }
568
- if (badrun) { console.log('[v114] SKIPPED (restored)'); process.exit(0) }
569
-
570
- /* =====================================================================
571
- F) VERSION + cache-bust
572
- ===================================================================== */
573
- try {
574
- if (has('backend.py')) {
575
- const b = read('backend.py')
576
- const nb = b.replace(/VERSION_ID = "v\d+"/, 'VERSION_ID = "v114"')
577
- if (nb !== b) { save('backend.py', nb); ok('backend.py: VERSION_ID -> v114') }
578
- }
579
- for (const ip of ['frontend/index.html', 'index.html']) {
580
- if (!has(ip)) continue
581
- const h = read(ip)
582
- const nh = h.replace(/\?v=\d+/g, '?v=114')
583
- if (nh !== h) { save(ip, nh); ok(ip + ': cache-bust -> ?v=114') }
584
- }
585
- } catch (e) { warn('version: ' + String((e && e.message) || e)) }
586
-
587
- console.log('[v114] DONE: ' + n + ' muc ap dung')
588
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v115.mjs DELETED
@@ -1,437 +0,0 @@
1
- /* patch_v115.mjs — V115. Chay TRONG Docker build, SAU patch_v114.mjs, TRUOC esbuild.
2
- =========================================================================
3
- SUA 3 LOI NGUOI DUNG VAN CON THAY sau v114:
4
- (1) "TAY LIEN LAC VOI THAN THE"
5
- (2) "SO VA LOGO VAN CON IN NGƯOC TREN AO"
6
- (3) "BANG TEN NHAN VAT CHUA THAY IN LEN MAT TRC CUA AO"
7
-
8
- ---------------------------------------------------------------------
9
- HE TOA DO — TINH TU NGUON, KHONG DOAN
10
- ---------------------------------------------------------------------
11
- Avatar QUAY MAT VE +z (rot = atan2(mx, mz)). Bang chung trong source:
12
- v112 ghi ro "face ... curved cap on +z", tuc MAT o phia +z.
13
-
14
- CameraRig (nguon goc, khong patch nao doi):
15
- const back = new THREE.Vector3(Math.sin(yaw), 0, Math.cos(yaw))
16
- ideal = target + back * dist ; yaw mac dinh = Math.PI
17
- => back = (0, 0, -1) => CAMERA NAM O LOCAL -z
18
- => Camera mac dinh NHIN VAO LUNG nhan vat (phia -z). Nguoi choi co the
19
- keo chuot de quay camera (rot.current doi) nen van xem duoc mat truoc.
20
-
21
- VI TRI DAT (giong ao dau that):
22
- - SO AO + LOGO V.AI STUDIO : LUNG = z AM (phia camera mac dinh)
23
- - BANG TEN NHAN VAT : NGUC = z DUONG (mat truoc ao, dung yEU cau 3)
24
-
25
- ---------------------------------------------------------------------
26
- VI SAO "IN NGUOC" (loi 2) — va V115 khac gi
27
- ---------------------------------------------------------------------
28
- Plane mac dinh co phap tuyen +z; chu ve tren canvas doc DUNG khi nhin tu
29
- phia +z (tuc tu phia TRUOC mat phang, huong nguoc chieu phap tuyen... noi
30
- chinh xac: meshBasicMaterial hien texture theo huong phap tuyen, va u tang
31
- theo +x nen tu phia +z chu doc trai->phai DUNG).
32
-
33
- Plane SO AO goc nam o z=-0.31 (phia camera) NHUNG KHONG XOAY => phap tuyen
34
- van +z, tuc huong RA XA camera. Camera o -z nhin vao MAT SAU cua plane =>
35
- moi net bi lat nguoc. Do chinh la loi (2). V109 "sua" bang DoubleSide —
36
- SAI: DoubleSide chi lam plane HIEN ra khi nhin tu sau, KHONG lam no doc
37
- dung. V112/V113/V114 thay bang cylinderGeometry mot cung va lap luan
38
- "u=0 nam ben trai" qua chuoi x = r*sin(t), z = r*cos(t) => screen-right;
39
- chuoi 4-5 buoc, sai dau o MOT buoc la lat ca so lan logo — dung nhu nguoi
40
- dung bao 3 lan lien.
41
-
42
- V115 dung PLANE + PHEP XOAY, thu khong the sai:
43
- lung (z=-0.306): XOAY PI quanh Y => phap tuyen thanh -z => huong ve
44
- camera => ta nhin MAT TRUOC plane => chu DUNG.
45
- nguc (z=+0.300): KHONG XOAY => phap tuyen +z => huong ra truoc
46
- mat => nguoi doi dien doc DUNG.
47
- Khong co u, khong co t, khong co sin/cos.
48
-
49
- ---------------------------------------------------------------------
50
- (1) TAY: nhom xoay quanh khop vai, cau deltoid dat DUNG tam xoay. Vi tam
51
- cau khong doi khi group xoay, khe vai kin o MOI goc dung dua:
52
- vai = (+-0.30, 1.30) ; tru than r 0.30 (capsule 0.30/0.34)
53
- mat than cach tam vai = sqrt(0.30^2 + 0.13^2) - 0.30 = 0.0407
54
- deltoid r 0.105 > 0.0407 => cau an sau vao than, khong the ho.
55
- ong tay r 0.068 tai y 1.16..1.44: mep trong 0.232 < 0.299 (ban kinh
56
- than tai y 1.16) => an vao than, khong con khe.
57
-
58
- ---------------------------------------------------------------------
59
- CACH LAM — KHONG PHU THUOC BAN DANG CHAY
60
- ---------------------------------------------------------------------
61
- a) go TRON bieu thuc JSX `{p.number != null && ( <mesh useNumTex> )}`
62
- cua ban goc (plane so ao phang). Quet ngoac CAN BANG, kiem tra noi
63
- dung THAT SU chua useNumTex(, va an CA dau `}` dong;
64
- b) go moi <mesh> LA con con tham chieu texture danh dau cu
65
- (backPlateTex( / frontNameTex( / backTagTex( / nameTagTex( ).
66
- CHI mesh la — KHONG BAO GIO cat <group>, vi <group ref={rootRef}>
67
- CHUA toan bo nhan vat nen cat no se xoa sach nhan vat;
68
- c) go 2 <group ref={armL}> va <group ref={armR}>;
69
- d) chen khoi MOI truoc <group ref={headRef} — anchor co tu ban goc va
70
- duoc useFrame dung nen moi patch deu giu lai.
71
- Chay duoc du ban dang chay la V109, V112, V113 hay V114; chay lai lan 2
72
- khong nhan doi.
73
-
74
- GUARD: chi esbuild (cu phap) + 4 dieu kien ve chinh khoi V115 la HARD
75
- FAIL (restore). Moi kiem tra "phong thu" khac chi WARN — vi mot guard
76
- khop nham se lam patch tu restore va ban cu duoc deploy, dung tinh trang
77
- da lam v113/v114 "khong co tac dung" ma nguoi dung bao 3 lan.
78
- ========================================================================= */
79
- import fs from 'node:fs'
80
- import path from 'node:path'
81
-
82
- const ROOT = process.argv[2] || '.'
83
- let n = 0
84
- const ok = (m) => { n++; console.log('[v115] OK: ' + m) }
85
- const warn = (m) => console.warn('[v115] WARN: ' + m)
86
- const P = (...a) => path.join(ROOT, ...a)
87
- const has = (f) => fs.existsSync(P(f))
88
- const read = (f) => fs.readFileSync(P(f), 'utf8')
89
- const save = (f, s) => fs.writeFileSync(P(f), s)
90
-
91
- const FILES = ['frontend/app.js', 'frontend/cave3d.js', 'frontend/home3d.js', 'backend.py']
92
- const BAK = {}
93
- for (const f of FILES) if (has(f)) BAK[f] = read(f)
94
-
95
- /* Cat cac <mesh> ... </mesh> LA (leaf) co chua marker. Chi mesh, khong group. */
96
- function leafMeshSpans(src, markers) {
97
- const spans = []
98
- const re = /<mesh\b/g
99
- let m
100
- while ((m = re.exec(src))) {
101
- const openEnd = src.indexOf('>', m.index)
102
- if (openEnd === -1) break
103
- if (src[openEnd - 1] === '/') { re.lastIndex = openEnd + 1; continue }
104
- let depth = 1
105
- let closeAt = -1
106
- const scan = /<(\/?)mesh\b/g
107
- scan.lastIndex = openEnd + 1
108
- let s2
109
- while ((s2 = scan.exec(src))) {
110
- if (s2[1] === '/') {
111
- depth--
112
- if (depth === 0) { closeAt = src.indexOf('>', s2.index); break }
113
- } else depth++
114
- }
115
- if (closeAt === -1) { re.lastIndex = openEnd + 1; continue }
116
- const body = src.slice(m.index, closeAt + 1)
117
- if (markers.some((k) => body.includes(k))) spans.push([m.index, closeAt + 1])
118
- re.lastIndex = openEnd + 1
119
- }
120
- if (!spans.length) return []
121
- const kept = spans.filter((sp) => !spans.some((o) =>
122
- (o[0] !== sp[0] || o[1] !== sp[1]) && o[0] <= sp[0] && o[1] >= sp[1]))
123
- const uniq = []
124
- for (const sp of kept) if (!uniq.some((u) => u[0] === sp[0] && u[1] === sp[1])) uniq.push(sp)
125
- return uniq
126
- }
127
-
128
- function applyCuts(src, spans) {
129
- if (!spans.length) return src
130
- const sorted = spans.slice().sort((a, b) => a[0] - b[0])
131
- const merged = []
132
- for (const sp of sorted) {
133
- if (merged.length && sp[0] <= merged[merged.length - 1][1]) {
134
- merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], sp[1])
135
- } else merged.push([sp[0], sp[1]])
136
- }
137
- let out = src
138
- for (let i = merged.length - 1; i >= 0; i--) out = out.slice(0, merged[i][0]) + out.slice(merged[i][1])
139
- return out
140
- }
141
-
142
- /* =====================================================================
143
- A) app.js
144
- ===================================================================== */
145
- let fatal = null
146
- try {
147
- const f = 'frontend/app.js'
148
- if (!has(f)) throw new Error('app.js missing')
149
- let s = read(f)
150
-
151
- /* ---------- A0. Texture MOI. Ten rieng _v115* nen KHONG BAO GIO trung
152
- khai bao voi backPlateTex/frontNameTex cu du chung con hay khong. ---------- */
153
- const FNS = [
154
- '/* V115: TEXTURE DANH DAU — ve TRONG SUOT (clearRect, khong to nen) de mau',
155
- ' ao lo ra, giong chu that in tren vai. Chu TRANG vien NAVY doc duoc tren',
156
- ' ca ao vang lan ao do. */',
157
- 'const _v115TexCache = {}',
158
- 'function _v115BackTex(number) {',
159
- ' const key = "b|" + (number == null ? "-" : String(number))',
160
- ' if (_v115TexCache[key]) return _v115TexCache[key]',
161
- ' const c = document.createElement("canvas"); c.width = 320; c.height = 300',
162
- ' const g = c.getContext("2d")',
163
- ' g.clearRect(0, 0, 320, 300)',
164
- ' g.textAlign = "center"; g.textBaseline = "middle"',
165
- ' g.strokeStyle = "rgba(34,48,77,0.55)"; g.lineWidth = 5',
166
- ' g.beginPath(); g.arc(160, 84, 62, 0, Math.PI * 2); g.stroke()',
167
- ' g.lineWidth = 11; g.strokeStyle = "rgba(34,48,77,0.85)"; g.fillStyle = "#ffffff"',
168
- ' g.font = "900 94px Bitter, Georgia, serif"',
169
- ' g.strokeText("V", 160, 86); g.fillText("V", 160, 86)',
170
- ' g.font = "800 27px Bitter, Georgia, serif"',
171
- ' g.strokeText("STUDIO", 160, 140); g.fillText("STUDIO", 160, 140)',
172
- ' if (number != null && String(number) !== "") {',
173
- ' g.font = "900 110px Arial, sans-serif"',
174
- ' g.lineWidth = 13; g.strokeStyle = "rgba(34,48,77,0.85)"; g.fillStyle = "#ffffff"',
175
- ' g.strokeText(String(number), 160, 236); g.fillText(String(number), 160, 236)',
176
- ' }',
177
- ' const t = new THREE.CanvasTexture(c)',
178
- ' t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8; t.needsUpdate = true',
179
- ' _v115TexCache[key] = t',
180
- ' return t',
181
- '}',
182
- 'function _v115NameTex(name) {',
183
- ' const key = "n|" + (name == null ? "" : String(name))',
184
- ' if (_v115TexCache[key]) return _v115TexCache[key]',
185
- ' const c = document.createElement("canvas"); c.width = 512; c.height = 132',
186
- ' const g = c.getContext("2d")',
187
- ' g.clearRect(0, 0, 512, 132)',
188
- ' g.fillStyle = "rgba(20,28,45,0.92)"',
189
- ' if (g.roundRect) { g.beginPath(); g.roundRect(4, 8, 504, 116, 16); g.fill() }',
190
- ' else g.fillRect(4, 8, 504, 116)',
191
- ' g.strokeStyle = "#f7f4ec"; g.lineWidth = 5',
192
- ' if (g.roundRect) { g.beginPath(); g.roundRect(4, 8, 504, 116, 16); g.stroke() }',
193
- ' else g.strokeRect(4, 8, 504, 116)',
194
- ' g.textAlign = "center"; g.textBaseline = "middle"',
195
- ' let label = String(name == null ? "" : name).trim() || "ANH EM"',
196
- ' if (label.length > 14) label = label.slice(0, 13) + "\\u2026"',
197
- ' let fs = 64',
198
- ' for (; fs > 20; fs -= 2) {',
199
- ' g.font = "800 " + fs + "px \\"Be Vietnam Pro\\", Arial, sans-serif"',
200
- ' if (g.measureText(label).width < 456) break',
201
- ' }',
202
- ' g.fillStyle = "#ffffff"',
203
- ' g.fillText(label, 256, 68)',
204
- ' const t = new THREE.CanvasTexture(c)',
205
- ' t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8; t.needsUpdate = true',
206
- ' _v115TexCache[key] = t',
207
- ' return t',
208
- '}',
209
- '',
210
- ].join('\n')
211
-
212
- if (s.includes('function _v115BackTex(')) ok('app.js: _v115BackTex/_v115NameTex da co (idem)')
213
- else {
214
- const anchor = 'function PlayerAvatar({ id, p, isLocal }) {'
215
- if (!s.includes(anchor)) throw new Error('KHONG THAY PlayerAvatar')
216
- s = s.replace(anchor, FNS + anchor)
217
- ok('app.js: them _v115BackTex + _v115NameTex (nen trong suot)')
218
- }
219
-
220
- /* ---------- A1. Go TRON bieu thuc JSX `{p.number != null && ( ... )}`
221
- cua ban goc (plane so ao phang o z=-0.31, KHONG xoay => in nguoc).
222
- Phai an CA dau `}` dong bieu thuc, neu khong se con `}` thua. ---------- */
223
- {
224
- const NEEDLE = 'p.number != null && ('
225
- let removed = 0, guard = 0, ambiguous = 0
226
- for (;;) {
227
- if (++guard > 8) break
228
- const i = s.indexOf(NEEDLE)
229
- if (i === -1) break
230
- const parenStart = i + NEEDLE.length - 1
231
- let depth = 0, pEnd = -1
232
- for (let k = parenStart; k < s.length; k++) {
233
- if (s[k] === '(') depth++
234
- else if (s[k] === ')') { depth--; if (depth === 0) { pEnd = k; break } }
235
- }
236
- if (pEnd === -1) throw new Error('KHONG CAN BANG duoc bieu thuc so ao ban goc')
237
- const inner = s.slice(parenStart + 1, pEnd)
238
- /* chi cat khi noi dung THAT SU la khoi so ao cu */
239
- if (!inner.includes('useNumTex(')) { ambiguous++; break }
240
- if (s[i - 1] !== '{') throw new Error('bieu thuc so ao khong nam trong { } JSX')
241
- let j = pEnd + 1
242
- while (j < s.length && (s[j] === ' ' || s[j] === '\t' || s[j] === '\r' || s[j] === '\n')) j++
243
- if (s[j] !== '}') throw new Error('KHONG THAY `}` dong bieu thuc so ao')
244
- const closeBrace = j
245
- let st = i - 1
246
- while (st > 0 && (s[st - 1] === ' ' || s[st - 1] === '\t')) st--
247
- if (s[st - 1] === '\n') st--
248
- let en = closeBrace + 1
249
- while (en < s.length && (s[en] === ' ' || s[en] === '\t')) en++
250
- if (s[en] === '\r') en++
251
- if (s[en] === '\n') en++
252
- s = s.slice(0, st) + s.slice(en)
253
- removed++
254
- }
255
- if (removed > 0) ok('app.js: GO ' + removed + ' bieu thuc plane so ao PHANG ban goc (ca dau } dong)')
256
- else if (ambiguous) ok('app.js: khoi `p.number` con lai KHONG phai plane so ao -> giu nguyen')
257
- else ok('app.js: khong con bieu thuc plane so ao ban goc (idem)')
258
- }
259
-
260
- /* ---------- A2. Go moi <mesh> LA con tham chieu texture danh dau CU ---------- */
261
- {
262
- const MARKERS = ['backPlateTex(', 'frontNameTex(', 'backTagTex(', 'nameTagTex(']
263
- const sp = leafMeshSpans(s, MARKERS)
264
- if (sp.length) { s = applyCuts(s, sp); ok('app.js: GO ' + sp.length + ' mesh danh dau CU (V109..V114)') }
265
- else ok('app.js: khong con mesh danh dau cu (idem)')
266
- }
267
-
268
- /* ---------- A3. Go 2 nhom tay cu ---------- */
269
- {
270
- let cuts = 0
271
- for (const ref of ['armL', 'armR']) {
272
- const re = new RegExp('[ \\t]*<group ref=\\{' + ref + '\\}[\\s\\S]*?</group>[ \\t]*\\r?\\n')
273
- const m = re.exec(s)
274
- if (m) { s = s.slice(0, m.index) + s.slice(m.index + m[0].length); cuts++ }
275
- }
276
- if (cuts) ok('app.js: GO ' + cuts + ' nhom tay cu')
277
- else ok('app.js: khong con nhom tay cu (idem)')
278
- }
279
-
280
- /* ---------- A4. Chen khoi V115 truoc <group ref={headRef} ---------- */
281
- const HEAD_ANCHOR = '<group ref={headRef}'
282
- const BLOCK = [
283
- ' {/* ===== V115: TAY LIEN THAN + TEN (nguc) + SO/LOGO (lung) ===== */}',
284
- ' {/* (1) TAY — group xoay quanh khop vai; cau deltoid dat DUNG tam xoay',
285
- ' nen khe vai kin o MOI goc dung dua (tam cau khong doi khi xoay).',
286
- ' Mat than cach tam vai sqrt(0.30^2+0.13^2)-0.30 = 0.0407 < 0.105',
287
- ' (ban kinh deltoid) => cau an sau vao than, khong the ho.',
288
- ' Ong tay r 0.068 tai y 1.16..1.44: mep trong 0.232 < 0.299 (ban',
289
- ' kinh than tai y 1.16) => an vao than, khong con khe. */}',
290
- ' <group ref={armL} position={[-0.30, 1.3, 0]}>',
291
- ' <mesh castShadow>',
292
- ' <sphereGeometry args={[0.105, 16, 12]} />',
293
- ' <meshStandardMaterial color={color} roughness={0.72} />',
294
- ' </mesh>',
295
- ' <mesh castShadow position={[0, -0.14, 0]}>',
296
- ' <capsuleGeometry args={[0.068, 0.20, 4, 10]} />',
297
- ' <meshStandardMaterial color={color} roughness={0.72} />',
298
- ' </mesh>',
299
- ' <mesh castShadow position={[0, -0.40, 0]}>',
300
- ' <capsuleGeometry args={[0.052, 0.18, 4, 10]} />',
301
- ' <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />',
302
- ' </mesh>',
303
- ' <mesh castShadow position={[0, -0.565, 0]}>',
304
- ' <sphereGeometry args={[0.058, 12, 10]} />',
305
- ' <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />',
306
- ' </mesh>',
307
- ' </group>',
308
- ' <group ref={armR} position={[0.30, 1.3, 0]}>',
309
- ' <mesh castShadow>',
310
- ' <sphereGeometry args={[0.105, 16, 12]} />',
311
- ' <meshStandardMaterial color={color} roughness={0.72} />',
312
- ' </mesh>',
313
- ' <mesh castShadow position={[0, -0.14, 0]}>',
314
- ' <capsuleGeometry args={[0.068, 0.20, 4, 10]} />',
315
- ' <meshStandardMaterial color={color} roughness={0.72} />',
316
- ' </mesh>',
317
- ' <mesh castShadow position={[0, -0.40, 0]}>',
318
- ' <capsuleGeometry args={[0.052, 0.18, 4, 10]} />',
319
- ' <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />',
320
- ' </mesh>',
321
- ' <mesh castShadow position={[0, -0.565, 0]}>',
322
- ' <sphereGeometry args={[0.058, 12, 10]} />',
323
- ' <meshStandardMaterial color={0xfdbcb4} roughness={0.9} />',
324
- ' </mesh>',
325
- ' </group>',
326
- ' {/* (3) BANG TEN NHAN VAT — MAT TRUOC AO (NGUC, z DUONG vi nhan vat',
327
- ' quay mat ve +z). Plane KHONG xoay => phap tuyen +z huong ra truoc',
328
- ' mat => nguoi doi dien doc DUNG chieu. Day la yEU CAU (3) cua nguoi',
329
- ' dung: bang ten in len MAT TRUOC cua ao.',
330
- ' Ban kinh than tai y 1.22 (chop tren capsule r 0.30 tam 1.17)',
331
- ' = sqrt(0.30^2 - 0.05^2) = 0.2958 => dat z 0.300 (lo ra 0.004).',
332
- ' Rong 0.30 < 0.5916 (be rong than). Ti le canvas 512x132 = 3.879;',
333
- ' plane 0.30/0.0774 = 3.876 => khong keo gian. */}',
334
- ' <mesh position={[0, 1.22, 0.300]}>',
335
- ' <planeGeometry args={[0.30, 0.0774]} />',
336
- ' <meshBasicMaterial map={_v115NameTex(p.name)} transparent',
337
- ' depthWrite={false} toneMapped={false} fog={false} />',
338
- ' </mesh>',
339
- ' {/* (2) SO AO + LOGO V.AI STUDIO — LUNG (z AM = phia camera mac dinh,',
340
- ' nen ban tu thay ngay khi vao hang). XOAY PI quanh Y: phap tuyen',
341
- ' +z -> -z, tuc huong VE camera => ta nhin MAT TRUOC cua plane nen',
342
- ' chu doc DUNG. Plane goc o z=-0.31 KHONG xoay la nguon loi "in',
343
- ' nguoc"; DoubleSide cua V109 chi lam no HIEN, khong lam no DUNG.',
344
- ' Than la tru thang r 0.30 tai y 0.83..1.17 nen dat z -0.306 =>',
345
- ' cach mat ao 0.006 (khong z-fight, khong tut vao trong than).',
346
- ' Rong 0.26 = 43% be rong ao 0.60. */}',
347
- ' <mesh position={[0, 0.99, -0.306]} rotation-y={Math.PI}>',
348
- ' <planeGeometry args={[0.26, 0.244]} />',
349
- ' <meshBasicMaterial map={_v115BackTex(p.number)} transparent',
350
- ' depthWrite={false} toneMapped={false} fog={false} />',
351
- ' </mesh>',
352
- '',
353
- ].join('\n')
354
-
355
- const SIG = 'planeGeometry args={[0.30, 0.0774]}'
356
- if (s.includes(SIG) && s.includes('planeGeometry args={[0.26, 0.244]}')) ok('app.js: khoi V115 da co (idem)')
357
- else {
358
- if (!s.includes(HEAD_ANCHOR)) throw new Error('KHONG THAY <group ref={headRef} lam diem chen')
359
- s = s.replace(HEAD_ANCHOR, BLOCK + ' ' + HEAD_ANCHOR)
360
- ok('app.js: TAY moi + BANG TEN nguc (+z) + SO/LOGO lung (-z, xoay PI)')
361
- }
362
-
363
- /* ---------- A5. Kiem tra "phong thu" (chi WARN, khong restore) ---------- */
364
- if (/side=\{THREE\.DoubleSide\}/.test(s)) warn('app.js: con side={THREE.DoubleSide} o cho khac (khong phai loi V115)')
365
- if (!/capsuleGeometry args=\{\[0\.3, 0\.34/.test(s)) warn('app.js: khong thay capsule than 0.3/0.34 — chi de tham khao')
366
-
367
- save(f, s)
368
- } catch (e) { fatal = 'app.js: ' + String((e && e.message) || e) }
369
-
370
- /* =====================================================================
371
- B) GUARD + VALIDATE — HARD FAIL chi khi: loi o A, thieu khoi V115,
372
- nhan vat bi xoa, hoac esbuild bao loi cu phap.
373
- ===================================================================== */
374
- let restored = false
375
- if (!fatal) {
376
- try {
377
- const app = read('frontend/app.js')
378
- const bad = []
379
- for (const m of ['function _v115BackTex(', 'function _v115NameTex(',
380
- 'planeGeometry args={[0.30, 0.0774]}',
381
- 'planeGeometry args={[0.26, 0.244]}',
382
- 'rotation-y={Math.PI}',
383
- 'map={_v115NameTex(p.name)}',
384
- 'map={_v115BackTex(p.number)}',
385
- '<group ref={armL} position={[-0.30, 1.3, 0]}>',
386
- '<group ref={armR} position={[0.30, 1.3, 0]}>',
387
- '<group ref={headRef}']) {
388
- if (!app.includes(m)) bad.push('thieu: ' + m)
389
- }
390
- if ((app.match(/function _v115BackTex\(/g) || []).length !== 1) bad.push('_v115BackTex != 1')
391
- if ((app.match(/<group ref=\{armL\}/g) || []).length !== 1) bad.push('armL != 1')
392
- if ((app.match(/<group ref=\{armR\}/g) || []).length !== 1) bad.push('armR != 1')
393
- /* AN TOAN: nhan vat phai con nguyen */
394
- if ((app.match(/<group ref=\{rootRef\}/g) || []).length !== 1) bad.push('rootRef != 1 (nhan vat bi xoa!)')
395
- if (!/capsuleGeometry args=\{\[0?\.3, 0?\.34/.test(app)) bad.push('mat than bi xoa')
396
- if (bad.length) throw new Error('marker: ' + bad.join(' | '))
397
-
398
- const esbuild = await import('esbuild')
399
- for (const p of ['frontend/app.js', 'frontend/cave3d.js', 'frontend/home3d.js']) {
400
- if (!has(p)) continue
401
- try { await esbuild.transform(read(p), { loader: 'jsx', format: 'esm', target: 'es2020' }) }
402
- catch (err) { throw new Error(p + ' KHONG HOP LE: ' + String((err && err.message) || err).split('\n').slice(0, 3).join(' ')) }
403
- }
404
- ok('esbuild transform OK: app.js + cave3d.js + home3d.js hop le')
405
- } catch (e) {
406
- warn('VALIDATE THAT BAI: ' + String((e && e.message) || e))
407
- for (const k of Object.keys(BAK)) save(k, BAK[k])
408
- restored = true
409
- warn('DA RESTORE ve ban truoc V115')
410
- }
411
- } else {
412
- warn(fatal)
413
- for (const k of Object.keys(BAK)) save(k, BAK[k])
414
- restored = true
415
- warn('DA RESTORE ve ban truoc V115')
416
- }
417
- if (restored) { console.log('[v115] SKIPPED (restored)'); process.exit(0) }
418
-
419
- /* =====================================================================
420
- C) VERSION + cache-bust
421
- ===================================================================== */
422
- try {
423
- if (has('backend.py')) {
424
- const b = read('backend.py')
425
- const nb = b.replace(/VERSION_ID = "v\d+"/, 'VERSION_ID = "v115"')
426
- if (nb !== b) { save('backend.py', nb); ok('backend.py: VERSION_ID -> v115') }
427
- }
428
- for (const ip of ['frontend/index.html', 'index.html']) {
429
- if (!has(ip)) continue
430
- const h = read(ip)
431
- const nh = h.replace(/\?v=\d+/g, '?v=115')
432
- if (nh !== h) { save(ip, nh); ok(ip + ': cache-bust -> ?v=115') }
433
- }
434
- } catch (e) { warn('version: ' + String((e && e.message) || e)) }
435
-
436
- console.log('[v115] DONE: ' + n + ' muc ap dung')
437
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v116.mjs DELETED
@@ -1,1176 +0,0 @@
1
- /* patch_v116.mjs — V116. Chay trong Docker build (hook cuoi o build/esbuild.config.mjs).
2
- =========================================================================
3
- NAM YEU CAU CUA NGUOI DUNG:
4
-
5
- (1) LOGO TREN AO = ANH POSTER THAT, VA LON HON backPlateTex().
6
- -> VIEC NAY DO patch_v116b.mjs LAM. Xem ghi chu o phan (A) ben duoi:
7
- ban dau V116 tu thay mieng lung o day, nhung doi chieu voi source
8
- GOC (commit e419952) cho thay cach cat do de lai mot mesh co
9
- map=null o lan render dau => meshBasicMaterial ve MIENG TRANG.
10
- v116b cat TRON <mesh> theo anchor position={[0, 0.99, -0.306]} do
11
- chinh patch_v115 dat vao, va boc moi thu trong guard vaiLogoTex.
12
- Phan con lai o day (vaiLogoTex hook + _v116NumTex) van can.
13
-
14
- (2) CHU "V.AI STUDIO" TRONG HANG -> ANH POSTER (drawImage, khong fillText):
15
- - cave3d makeBannerTex() : banner vom hang
16
- - home3d drawRedPlaque() : bia do ngoai cua hang
17
- - home3d VaiSteleText2() : chu khac tren tang da VaiSteleRock
18
- (ten THAT trong cay nguon la VaiSteleText2: patch_v95 tao VaiSteleText, roi
19
- patch_v97 CAT doan [const VAI_ROCK_POS = .. function HomeForecourt(] va
20
- thay bang VaiSteleText2. V116e sua anchor cho dung ten nay — truoc do
21
- anchor tro VaiSteleText nen cutFn tra null va v116 RESTORE ca 5 file.)
22
- drawRedPlaque con mot loi an: loadPlateImg().then(...) ve SAU khi texture
23
- da tao nhung KHONG bat needsUpdate => logo do khong bao gio hien. V116 bat.
24
-
25
- (3) BINH CHON THEO KIEN THUC AI + COT "LUOT BINH CHON":
26
- - POLL_QUESTIONS: 4 cau bong da -> 4 cau AI
27
- - handler websocket 'vote' -> _att_bump(name, "votes")
28
- - "votes" nap trong _att_load/_att_pull, tinh votes*3 trong _att_score,
29
- tra ra o /api/attendance/top, ve thanh COT 4 o BangVangDiemDanh.
30
-
31
- (4) VIDEO RANDOM KHI VAO HANG + TU NHAY BAI KHI HET:
32
- Effect tao iframe luon phat useIds[0] VA video_proxy.py cu hardcode
33
- `loop=1&playlist=...` => video LAP MAI, khong bao gio ket thuc nen khong
34
- the "tu nhay bai". V116:
35
- - THAY TOAN BO effect do (cat can bang ngoac, KHONG phu thuoc chuoi
36
- anchor ben trong — trong chain co nhieu bien the effect khac nhau)
37
- - ten ref container DUOC DOC TU CHINH doan bi cat (khong doan bua)
38
- - KHONG dung loop nua; iframe qua /api/video-proxy&loop=0
39
- - nghe 'hangmu-ended' (proxy ban khi playerState===0 ENDED) -> bai ke
40
- - nghe 'hangmu-play' (nut playlist) -> nhay dung bai
41
- - timer an toan 20 phut neu YouTube khong ban gi
42
- Chon bai NGAU NHIEN luc mount do patch_v116a.mjs dam nhan.
43
- video_proxy.py da sua trong cung commit nay.
44
-
45
- (5) NUT PLAYLIST MO/DOANH DANH SACH:
46
- .board-playbar truoc day LUON hien va KHONG co CSS nao trong 5 stylesheet
47
- duoc phuc vu. Nay co nut .board-playbar-toggle; panel chi hien khi co
48
- class .is-open. CSS nam trong frontend/styles/playlist.css vi
49
- `COPY frontend/styles` lay tu SOURCE TREE, khong qua build stage (bai hoc
50
- v82). index.html thi lay tu build stage nen V116 chi chen the <link>.
51
-
52
- AN TOAN: backup 5 file; validate marker + esbuild.transform; bat ky loi ->
53
- RESTORE tat ca va exit 0. Anchor lech KHONG BAO GIO lam sap Space.
54
- ========================================================================= */
55
- import fs from 'node:fs'
56
- import path from 'node:path'
57
-
58
- const ROOT = process.argv[2] || '.'
59
- let n = 0
60
- const ok = (m) => { n++; console.log('[v116] OK: ' + m) }
61
- const warn = (m) => console.warn('[v116] WARN: ' + m)
62
- const P = (...a) => path.join(ROOT, ...a)
63
- const has = (f) => fs.existsSync(P(f))
64
- const read = (f) => fs.readFileSync(P(f), 'utf8')
65
- const save = (f, s) => fs.writeFileSync(P(f), s)
66
-
67
- const BAK = {}
68
- for (const f of ['frontend/app.js', 'frontend/cave3d.js', 'frontend/home3d.js', 'backend.py', 'frontend/index.html', 'video_proxy.py']) {
69
- if (has(f)) BAK[f] = read(f)
70
- }
71
-
72
- /* cat khoi function theo TEN, can bang ngoac { } */
73
- function cutFn(src, name) {
74
- const m = new RegExp('function\\s+' + name + '\\s*\\([^)]*\\)\\s*\\{').exec(src)
75
- if (!m) return null
76
- /* V116f: start at the BRACE THE REGEX MATCHED (the function body), not at
77
- src.indexOf('{'). With a destructured signature such as
78
- function VaiSteleText2({ y, z, width }) { indexOf('{') lands on the
79
- PARAM brace, so the cut began mid-signature and left "}) {" plus a stray
80
- ')' -> esbuild 'Unexpected ")"'. The regex's \s*\{ is the body brace. */
81
- const start = m.index + m[0].length - 1
82
- let d = 0
83
- for (let k = start; k < src.length; k++) {
84
- if (src[k] === '{') d++
85
- else if (src[k] === '}') { d--; if (d === 0) return [m.index, k + 1] }
86
- }
87
- return null
88
- }
89
- /* cat khoi [ ... ] can bang ngoac vuong */
90
- function cutBracket(src, needle) {
91
- const i = src.indexOf(needle)
92
- if (i === -1) return null
93
- const start = src.indexOf('[', i)
94
- if (start === -1) return null
95
- let d = 0
96
- for (let k = start; k < src.length; k++) {
97
- if (src[k] === '[') d++
98
- else if (src[k] === ']') { d--; if (d === 0) return [i, k + 1] }
99
- }
100
- return null
101
- }
102
- /* cat TOAN BO loi goi fnName(...) chua `marker`, can bang ( ) — bo qua string
103
- literal va comment. Tra ve [start, end] hoac null. */
104
- function cutCallContaining(src, marker, names) {
105
- const mi = src.indexOf(marker)
106
- if (mi === -1) return null
107
- let ci = -1, fnLen = 0
108
- for (const nm of names) {
109
- const j = src.lastIndexOf(nm + '(', mi)
110
- if (j > ci) { ci = j; fnLen = nm.length }
111
- }
112
- if (ci === -1) return null
113
- const open = ci + fnLen
114
- let par = 0, q = null, line = false, blk = false
115
- for (let k = open; k < src.length; k++) {
116
- const ch = src[k], nx = src[k + 1]
117
- if (line) { if (ch === '\n') line = false; continue }
118
- if (blk) { if (ch === '*' && nx === '/') { blk = false; k++ } continue }
119
- if (q) {
120
- if (ch === '\\') { k++; continue }
121
- if (ch === q) q = null
122
- continue
123
- }
124
- if (ch === '/' && nx === '/') { line = true; k++; continue }
125
- if (ch === '/' && nx === '*') { blk = true; k++; continue }
126
- if (ch === '"' || ch === "'" || ch === '`') { q = ch; continue }
127
- if (ch === '(') par++
128
- else if (ch === ')') { par--; if (par === 0) return [ci, k + 1] }
129
- }
130
- return null
131
- }
132
-
133
- let fatal = null
134
-
135
- /* =====================================================================
136
- A) app.js — LOGO AO: chi them loader + hook + texture so ao.
137
- VIEC THAY MIENG LUNG DO patch_v116b.mjs LAM (xem ghi chu dau file).
138
- ===================================================================== */
139
- try {
140
- const f = 'frontend/app.js'
141
- if (!has(f)) throw new Error('app.js missing')
142
- let s = read(f)
143
-
144
- const LOADER = `
145
- /* ===== V116: LOGO TREN AO = ANH POSTER THAT (/images/vai-logo.png) =====
146
- CanvasTexture ve DONG BO nen cac ban truoc phai "ve chu" thay vi dung anh.
147
- TextureLoader la BAT DONG BO => PlayerAvatar phai giu STATE cho den khi anh
148
- load xong, neu khong lan render dau map=null se ra mieng dan TRANG tren lung.
149
- Cache o pham vi module: ca hang chi tai MOT lan, moi avatar dung chung.
150
- crossOrigin = anonymous BAT BUOC: thieu no texture nap vao GPU bi coi la
151
- "tainted".
152
- Anh loi / mat mang -> texture DU PHONG (huy hieu canvas) de ao khong bao gio
153
- trong. patch_v116b noi phan du phong do vao day. */
154
- const VAI_LOGO_URL = '/images/vai-logo.png'
155
- const _v116Logo = { tex: null, promise: null, done: false }
156
- function _v116LoadLogoTex() {
157
- if (_v116Logo.done) return Promise.resolve(_v116Logo.tex)
158
- if (_v116Logo.promise) return _v116Logo.promise
159
- _v116Logo.promise = new Promise((resolve) => {
160
- if (typeof THREE === 'undefined' || !THREE.TextureLoader) { _v116Logo.done = true; resolve(null); return }
161
- try {
162
- const loader = new THREE.TextureLoader()
163
- loader.setCrossOrigin('anonymous')
164
- loader.load(VAI_LOGO_URL, (t) => {
165
- t.colorSpace = THREE.SRGBColorSpace
166
- t.anisotropy = 8
167
- t.needsUpdate = true
168
- _v116Logo.tex = t
169
- _v116Logo.done = true
170
- resolve(t)
171
- }, undefined, () => { _v116Logo.done = true; resolve(null) })
172
- } catch (e) { _v116Logo.done = true; resolve(null) }
173
- })
174
- return _v116Logo.promise
175
- }
176
- function useVaiLogoTex() {
177
- const [tex, setTex] = React.useState(_v116Logo.tex)
178
- React.useEffect(() => {
179
- let alive = true
180
- _v116LoadLogoTex().then((t) => { if (alive) setTex(t) })
181
- return () => { alive = false }
182
- }, [])
183
- return tex
184
- }
185
- /* So ao — CANVAS rieng, nen TRONG SUOT, dat TRUOC mat poster nen doc duoc tren
186
- moi nen. Chi ve CHU SO (logo da la anh that o tren). */
187
- const _v116NumCache = {}
188
- function _v116NumTex(number) {
189
- const key = number == null ? 'none' : String(number)
190
- if (_v116NumCache[key]) return _v116NumCache[key]
191
- const c = document.createElement('canvas'); c.width = 160; c.height = 160
192
- const g = c.getContext('2d')
193
- g.clearRect(0, 0, 160, 160)
194
- g.textAlign = 'center'; g.textBaseline = 'middle'
195
- const label = String(number == null ? '' : number)
196
- if (label) {
197
- g.font = '900 108px Arial, sans-serif'
198
- g.lineWidth = 12; g.strokeStyle = 'rgba(20,26,42,0.92)'
199
- g.strokeText(label, 80, 84)
200
- g.fillStyle = '#ffffff'
201
- g.fillText(label, 80, 84)
202
- }
203
- const t = new THREE.CanvasTexture(c)
204
- t.colorSpace = THREE.SRGBColorSpace
205
- t.anisotropy = 8; t.needsUpdate = true
206
- _v116NumCache[key] = t
207
- return t
208
- }
209
-
210
- `
211
- /* Anchor bang REGEX (khong phu thuoc danh sach prop chinh xac). */
212
- const AV_RE = /function\s+PlayerAvatar\s*\([^)]*\)\s*\{/
213
- const av = AV_RE.exec(s)
214
- if (!av) throw new Error('KHONG THAY PlayerAvatar')
215
-
216
- if (s.includes('function useVaiLogoTex(')) ok('app.js: useVaiLogoTex (idem)')
217
- else {
218
- s = s.replace(AV_RE, LOADER + '$&')
219
- ok('app.js: them VAI_LOGO_URL + _v116LoadLogoTex + useVaiLogoTex + _v116NumTex')
220
- }
221
-
222
- if (s.includes('const vaiLogoTex = useVaiLogoTex()')) ok('app.js: hook vaiLogoTex (idem)')
223
- else {
224
- s = s.replace(AV_RE, (m0) => m0 + '\n const vaiLogoTex = useVaiLogoTex()')
225
- ok('app.js: PlayerAvatar -> state cho anh poster (const vaiLogoTex)')
226
- }
227
-
228
- /* KHONG thay mieng lung o day — patch_v116b.mjs lam, bang cach cat TRON
229
- <mesh position={[0, 0.99, -0.306]}> do patch_v115 dat vao. Xem ghi chu
230
- dau file ve loi "mieng dan TRANG". */
231
- if (s.includes('_v115BackTex(p.number)')) ok('app.js: mieng lung V115 con nguyen (v116b se thay)')
232
- else if (s.includes('planeGeometry args={[0.36, 0.32]}')) ok('app.js: mieng lung da la poster (idem)')
233
- else warn('app.js: khong thay mieng lung V115 — v116b se bao ro')
234
-
235
- save(f, s)
236
- } catch (e) { fatal = 'app.js(logo): ' + String((e && e.message) || e) }
237
-
238
- /* =====================================================================
239
- B) app.js — (4) RANDOM + TU NHAY BAI ; (5) NUT PLAYLIST
240
- ===================================================================== */
241
- if (!fatal) {
242
- try {
243
- const f = 'frontend/app.js'
244
- let s = read(f)
245
-
246
- /* ---- B1. state + nghe nut playlist (CHI mot anchor) ---- */
247
- const ST_OLD = ' const idxRef = React.useRef(0)'
248
- const ST_NEW = ` const idxRef = React.useRef(0)
249
- /* V116: (4) random khi vao hang + tu nhay bai. -1 = chua chon. */
250
- const [playIdx, setPlayIdx] = React.useState(-1)
251
- /* V116: (5) danh sach video la PANEL AN, chi hien khi bam nut. */
252
- const [playbarOpen, setPlaybarOpen] = React.useState(false)
253
- /* V116: (5) nut trong playlist phat bai tuong ung. Truoc day pick() ban
254
- hangmu-play nhung KHONG AI nghe => nut vo dung. */
255
- React.useEffect(() => {
256
- const onPlay = (ev) => {
257
- const i = ev && ev.detail ? ev.detail.index : null
258
- if (typeof i !== 'number') return
259
- setPlayIdx(i)
260
- }
261
- window.addEventListener('hangmu-play', onPlay)
262
- return () => window.removeEventListener('hangmu-play', onPlay)
263
- }, [])`
264
- if (s.includes('const [playIdx, setPlayIdx]')) ok('app.js: state + hangmu-play (idem)')
265
- else if (s.includes(ST_OLD)) { s = s.replace(ST_OLD, ST_NEW); ok('app.js: them playIdx + playbarOpen + nghe hangmu-play') }
266
- else throw new Error('KHONG THAY const idxRef = React.useRef(0)')
267
-
268
- /* ---- B3. THAY TOAN BO EFFECT tao iframe ----
269
- Ten ref container DOC TU chinh doan bi cat (khong doan bua) — neu dung
270
- sai ten thi `if (!wrap) return` se lam video KHONG BAO GIO hien.
271
- Nguon goc (commit e419952) dung `const ref = React.useRef(null)`, cac
272
- bien the sau do co the doi ten, nen phai doc dong. */
273
- const cutFx = cutCallContaining(s, "document.createElement('iframe')", ['React.useEffect', 'useEffect'])
274
- if (!cutFx) throw new Error('KHONG THAY effect tao iframe cua BoardVideoOverlay')
275
- const origFx = s.slice(cutFx[0], cutFx[1])
276
- let refName = ''
277
- const mRef = origFx.match(/([A-Za-z_$][\w$]*)\.current/)
278
- if (mRef && mRef[1] !== 'iframe') refName = mRef[1]
279
- if (!refName) throw new Error('KHONG DOC DUOC ten ref container trong effect cu')
280
- ok('app.js: ref container cua BoardVideoOverlay = ' + refName)
281
-
282
- const NEW_FX = ` React.useEffect(() => {
283
- /* ===== V116: (4) VIDEO RANDOM + TU NHAY BAI KHI HET =====
284
- - phat BAI playIdx (ngau nhien khi vao hang, hoac bai da chon)
285
- - iframe qua /api/video-proxy (xem duoc o VN) va loop=0 => video KET
286
- THUC that; proxy ban hangmu-ended khi playerState === 0 (ENDED)
287
- - nghe hangmu-ended => bai ke tiep
288
- - timer an toan 20 phut neu YouTube khong ban gi */
289
- if (!useIds || !useIds.length) return
290
- const wrap = ${refName}.current
291
- if (!wrap) return
292
- let cancelled = false
293
- const _idx = playIdx < 0 ? 0 : playIdx % useIds.length
294
- /* item co the la string hoac {url,title,img,yt,mp4} */
295
- const _norm = (it) => {
296
- if (!it) return { url: '', title: '', img: '', vid: '' }
297
- if (typeof it === 'string') {
298
- const m = it.match(/(?:v=|\\/embed\\/|youtu\\.be\\/|shorts\\/)([A-Za-z0-9_-]{6,})/)
299
- return {
300
- url: /^https?:/i.test(it) ? it : ('https://www.youtube.com/watch?v=' + (m ? m[1] : it)),
301
- title: '', img: '', vid: m ? m[1] : '',
302
- }
303
- }
304
- const raw = it.url || it.mp4 || ''
305
- const m = String(raw).match(/(?:v=|\\/embed\\/|youtu\\.be\\/|shorts\\/)([A-Za-z0-9_-]{6,})/)
306
- return { url: raw, title: it.title || '', img: it.img || '', vid: it.yt || (m ? m[1] : '') }
307
- }
308
- const cur = _norm(useIds[_idx])
309
- /* Tang 1 — poster nen, luon co nen man hinh khong bao gio trong */
310
- const poster = document.createElement('div')
311
- poster.style.cssText = 'position:absolute;inset:0;z-index:0;display:flex;flex-direction:column;align-items:center;justify-content:center;background:radial-gradient(circle at 50% 30%, #5c0e1b, #1b0508);color:#ffd76a;font:700 20px/1.3 "Be Vietnam Pro",sans-serif;text-align:center;padding:6px;gap:4px'
312
- poster.innerHTML = '<span style="font-size:36px;line-height:1">🔴⚪</span><span>BẢNG TIN V.AI STUDIO</span><span style="font-size:12px;color:#f0d9a8">HANG TU TRI AI</span>'
313
- wrap.appendChild(poster)
314
- /* Tang 2 — thumbnail (nen TRONG SUOT de poster lo ra khi anh loi) */
315
- const thumb = document.createElement('div')
316
- thumb.style.cssText = 'position:absolute;inset:0;z-index:2;background:transparent;overflow:hidden;display:block;opacity:0'
317
- const img = document.createElement('img')
318
- img.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:.95'
319
- img.alt = ''
320
- img.onerror = () => { if (!cancelled) thumb.style.opacity = '0' }
321
- img.onload = () => { if (!cancelled) thumb.style.opacity = '1' }
322
- const cap = document.createElement('div')
323
- cap.style.cssText = 'position:absolute;left:0;right:0;bottom:0;z-index:2;padding:5px 8px 6px;background:linear-gradient(180deg,transparent,rgba(0,0,0,.82));color:#ffd76a;font:700 13px/1.2 "Be Vietnam Pro",sans-serif;text-align:left;display:flex;align-items:center;gap:6px'
324
- cap.innerHTML = '<span style="background:#ff0202;color:#fff;border-radius:3px;padding:1px 5px;font-size:10px;font-weight:800">YOUTUBE</span><span style="color:#fff">V.AI STUDIO · HANG TU TRÍ AI</span>'
325
- thumb.appendChild(img)
326
- thumb.appendChild(cap)
327
- const badge = document.createElement('div')
328
- badge.style.cssText = 'position:absolute;left:6px;top:5px;z-index:3;background:rgba(0,0,0,.55);color:#fff;border-radius:999px;padding:2px 8px;font:800 12px/1.2 "Be Vietnam Pro",sans-serif'
329
- badge.textContent = (typeof channel !== 'undefined' && channel === 'football') ? '⚽ VIDEO AI' : '🎵 NHẠC AI'
330
- thumb.appendChild(badge)
331
- const setThumb = (i) => {
332
- const it = _norm(useIds[i % useIds.length])
333
- let src = it.img
334
- if (!src && it.vid) src = 'https://i.ytimg.com/vi/' + it.vid + '/hqdefault.jpg'
335
- if (!src) { thumb.style.opacity = '0'; return }
336
- img.src = src
337
- img.style.transition = 'opacity .4s'
338
- img.style.opacity = '0.3'
339
- requestAnimationFrame(() => { requestAnimationFrame(() => { if (!cancelled && img.complete) img.style.opacity = '.95' }) })
340
- }
341
- setThumb(_idx)
342
- wrap.appendChild(thumb)
343
- /* Tang 3 — iframe QUA /api/video-proxy, KHONG loop => video ket thuc that */
344
- const iframe = document.createElement('iframe')
345
- iframe.setAttribute('allow', 'autoplay; encrypted-media; picture-in-picture; fullscreen')
346
- iframe.setAttribute('allowfullscreen', '')
347
- iframe.setAttribute('referrerpolicy', 'no-referrer-when-downgrade')
348
- iframe.setAttribute('title', 'Video AI')
349
- iframe.style.cssText = 'position:absolute;inset:0;z-index:5;width:100%;height:100%;border:0;background:#000'
350
- if (cur.vid) {
351
- iframe.src = '/api/video-proxy?url=' + encodeURIComponent('https://www.youtube.com/watch?v=' + cur.vid) +
352
- '&title=' + encodeURIComponent(cur.title || 'Hang MU') +
353
- '&img=' + encodeURIComponent(cur.img || ('https://i.ytimg.com/vi/' + cur.vid + '/hqdefault.jpg')) +
354
- '&loop=0'
355
- } else if (cur.url) {
356
- iframe.src = cur.url
357
- } else {
358
- iframe.src = 'about:blank'
359
- iframe.style.display = 'none'
360
- }
361
- wrap.appendChild(iframe)
362
- /* Con song hay bi chan: nghe postMessage cua proxy + YouTube native */
363
- let ytAlive = false
364
- let endedOnce = false
365
- const probe = () => {
366
- if (cancelled) return
367
- try {
368
- if (iframe.contentWindow) iframe.contentWindow.postMessage(JSON.stringify({ event: 'listening', id: 'hangmu-probe' }), '*')
369
- } catch (e) {}
370
- }
371
- const nextTrack = () => {
372
- if (cancelled || endedOnce) return
373
- endedOnce = true
374
- setPlayIdx((c2) => ((c2 < 0 ? 0 : c2) + 1) % useIds.length)
375
- }
376
- const onMsg = (ev) => {
377
- if (!ev || ev.source !== iframe.contentWindow) return
378
- let d = null
379
- try { d = JSON.parse(typeof ev.data === 'string' ? ev.data : '') } catch (e) { return }
380
- if (!d) return
381
- if (d.event === 'hangmu-playing') {
382
- if (d.playing === true) { ytAlive = true; if (!cancelled) iframe.style.display = '' }
383
- return
384
- }
385
- if (d.event === 'onReady' || d.event === 'infoDelivery') {
386
- ytAlive = true
387
- if (!cancelled) iframe.style.display = ''
388
- }
389
- /* V116: (4) TU NHAY BAI KHI HET — proxy bao khi playerState === 0 */
390
- if (d.event === 'hangmu-ended') { nextTrack(); return }
391
- if (d.event === 'infoDelivery' && d.info && d.info.playerState === 0) { nextTrack() }
392
- }
393
- window.addEventListener('message', onMsg)
394
- const syncVis = () => { if (!cancelled) iframe.style.display = ytAlive ? '' : 'none' }
395
- const probeSync = () => { probe(); setTimeout(syncVis, 1200) }
396
- iframe.addEventListener('load', () => { setTimeout(probeSync, 300) })
397
- const t1 = setTimeout(probeSync, 500)
398
- const t2 = setTimeout(probeSync, 2000)
399
- const t3 = setTimeout(() => { if (!cancelled && !ytAlive) iframe.style.display = 'none' }, 6000)
400
- const iv = setInterval(probeSync, 10000)
401
- /* Luoi an toan: YouTube khong bao gi thi van sang bai sau 20 phut */
402
- const tEnd = setTimeout(() => { nextTrack() }, 20 * 60 * 1000)
403
- try { window.dispatchEvent(new CustomEvent('hangmu-board-ready', { detail: { videoIds: useIds, iframe } })) } catch (e) {}
404
- wrap._setThumb = setThumb
405
- return () => {
406
- cancelled = true
407
- clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); clearTimeout(tEnd); clearInterval(iv)
408
- window.removeEventListener('message', onMsg)
409
- try { wrap.innerHTML = '' } catch (e) {}
410
- }
411
- }, [useIds?.join(','), playIdx])`
412
-
413
- if (s.includes('V116: (4) VIDEO RANDOM + TU NHAY BAI KHI HET')) ok('app.js: effect video V116 (idem)')
414
- else {
415
- s = s.slice(0, cutFx[0]) + NEW_FX + s.slice(cutFx[1])
416
- ok('app.js: THAY effect video -> random + tu nhay bai (proxy loop=0 + hangmu-ended)')
417
- }
418
-
419
- /* ---- B4. (5) PLAYLIST -> NUT BAM, PANEL AN ---- */
420
- const PB_CLS = '<div className="board-playbar" role="toolbar"'
421
- const PB_IDX = s.indexOf(PB_CLS) !== -1 ? s.indexOf(PB_CLS) : s.indexOf('<div className="board-playbar"')
422
- if (s.includes('board-playbar-toggle')) ok('app.js: nut playlist (idem)')
423
- else if (PB_IDX !== -1) {
424
- const TOGGLE = `{/* V116: (5) NUT PLAYLIST — danh sach la PANEL AN, chi mo khi bam. */}
425
- <button type="button"
426
- className={\`board-playbar-toggle\${playbarOpen ? ' is-active' : ''}\`}
427
- onClick={() => setPlaybarOpen((v) => !v)}
428
- aria-expanded={playbarOpen} aria-controls="board-playlist"
429
- title={playbarOpen ? 'Đóng danh sách video' : 'Mở danh sách video'}>
430
- <span aria-hidden="true">{playbarOpen ? '✕' : '☰'}</span>
431
- <span className="board-playbar-toggle-label">{typeof channel !== 'undefined' && channel === 'football' ? '⚽' : '🎵'} Playlist</span>
432
- </button>
433
- <div className={\`board-playbar\${playbarOpen ? ' is-open' : ''}\`} id="board-playlist" role="toolbar"`
434
- let head = s.slice(PB_IDX)
435
- head = head.replace(/^<div className="board-playbar"[^>]*/, TOGGLE)
436
- s = s.slice(0, PB_IDX) + head
437
- ok('app.js: PLAYLIST -> nut bam mo/doanh panel (panel an mac dinh)')
438
- } else throw new Error('KHONG THAY khoi .board-playbar')
439
-
440
- /* ---- B5. danh dau bai dang phat ---- */
441
- if (s.includes('board-playbar-card${i === playIdx')) ok('app.js: card is-playing (idem)')
442
- else if (s.includes('className="board-playbar-card"')) {
443
- s = s.replace('className="board-playbar-card"',
444
- 'className={`board-playbar-card${i === playIdx ? \' is-playing\' : \'\'}`}')
445
- ok('app.js: card dang phat -> is-playing')
446
- } else throw new Error('KHONG THAY board-playbar-card')
447
-
448
- save(f, s)
449
- } catch (e) { fatal = 'app.js(video): ' + String((e && e.message) || e) }
450
- }
451
-
452
- /* =====================================================================
453
- C) cave3d.js — (2) banner ; (3) cot "Binh chon"
454
- ===================================================================== */
455
- if (!fatal) {
456
- try {
457
- const f = 'frontend/cave3d.js'
458
- if (!has(f)) throw new Error('cave3d.js missing')
459
- let s = read(f)
460
-
461
- if (!s.includes('function loadV116Logo(')) {
462
- const LOADER = `
463
- /* ===== V116: ANH POSTER THAT (/images/vai-logo.png) cho chu "V.AI STUDIO"
464
- trong hang. Canvas chi ve NEN/VIEN dong bo, con CHU + LOGO la drawImage tu
465
- anh that (yeu cau: dung anh poster thay fillText).
466
- Cache module: ca hang chi tai 1 lan. crossOrigin bat buoc. ===== */
467
- const V116_LOGO_URL = '/images/vai-logo.png'
468
- let _v116LogoImg = null
469
- let _v116LogoP = null
470
- function loadV116Logo() {
471
- if (_v116LogoImg) return Promise.resolve(_v116LogoImg)
472
- if (_v116LogoP) return _v116LogoP
473
- if (typeof Image === 'undefined') return Promise.resolve(null)
474
- _v116LogoP = new Promise((resolve) => {
475
- const img = new Image()
476
- img.crossOrigin = 'anonymous'
477
- img.decoding = 'async'
478
- img.onload = () => { _v116LogoImg = img; resolve(img) }
479
- img.onerror = () => { _v116LogoImg = null; resolve(null) }
480
- img.src = V116_LOGO_URL
481
- })
482
- return _v116LogoP
483
- }
484
-
485
- `
486
- const anchor = 'function makeBannerTex(text) {'
487
- if (!s.includes(anchor)) throw new Error('KHONG THAY makeBannerTex de chen loader')
488
- s = s.replace(anchor, LOADER + anchor)
489
- ok('cave3d: them loadV116Logo (cache + crossOrigin)')
490
- } else ok('cave3d: loadV116Logo (idem)')
491
-
492
- const cutB = cutFn(s, 'makeBannerTex')
493
- if (!cutB) throw new Error('KHONG THAY function makeBannerTex')
494
- const BANNER = `/* V116: BANNER TREN VOM — dung ANH POSTER THAT (drawImage) thay vi
495
- fillText('V.AI STUDIO'). Canvas chi ve nen + vien; chu/logo la anh that.
496
- Tra texture NGAY (khong bao gio trong); anh xong thi ve de len va bat
497
- needsUpdate — dung nguyen tac V96 da dung cho bang tin AI. */
498
- function makeBannerTex(text) {
499
- const c = document.createElement('canvas')
500
- c.width = 512; c.height = 128
501
- const g = c.getContext('2d')
502
- const t = new THREE.CanvasTexture(c)
503
- t.colorSpace = THREE.SRGBColorSpace
504
- t.anisotropy = 8
505
- const paint = (img) => {
506
- const gr = g.createLinearGradient(0, 0, 0, 128)
507
- gr.addColorStop(0, '#22304d'); gr.addColorStop(0.55, '#16203a'); gr.addColorStop(1, '#0c1322')
508
- g.fillStyle = gr; g.fillRect(0, 0, 512, 128)
509
- g.strokeStyle = '#f5c518'; g.lineWidth = 5; g.strokeRect(5, 5, 502, 118)
510
- if (img) {
511
- /* ANH POSTER THAT — tron trong o 296x104 ben trai */
512
- const iw = img.naturalWidth || img.width || 1
513
- const ih = img.naturalHeight || img.height || 1
514
- const boxW = 296, boxH = 104
515
- const sc = Math.min(boxW / iw, boxH / ih)
516
- const w = iw * sc, h = ih * sc
517
- g.save()
518
- g.fillStyle = 'rgba(8,10,16,0.55)'
519
- g.fillRect(10, 12, boxW, boxH)
520
- g.drawImage(img, 10 + (boxW - w) / 2, 12 + (boxH - h) / 2, w, h)
521
- g.strokeStyle = 'rgba(245,197,24,0.75)'; g.lineWidth = 2
522
- g.strokeRect(10, 12, boxW, boxH)
523
- g.restore()
524
- g.textAlign = 'left'; g.textBaseline = 'alphabetic'
525
- g.fillStyle = '#ffffff'; g.font = '900 42px Bitter, Georgia, serif'
526
- g.fillText('V.AI', 322, 54)
527
- g.fillStyle = '#f5c518'; g.font = '800 30px Bitter, Georgia, serif'
528
- g.fillText('STUDIO', 322, 88)
529
- g.fillStyle = 'rgba(247,244,236,0.72)'; g.font = '700 17px "Be Vietnam Pro", sans-serif'
530
- g.fillText('HANG TU TRI', 322, 114)
531
- } else {
532
- /* chua co anh: van co chu, khong bao gio trong */
533
- g.textAlign = 'center'; g.textBaseline = 'middle'
534
- g.fillStyle = '#f5c518'; g.font = '900 50px Bitter, Georgia, serif'
535
- g.fillText(text || 'V.AI STUDIO', 256, 62)
536
- }
537
- t.needsUpdate = true
538
- }
539
- paint(_v116LogoImg)
540
- if (!_v116LogoImg) loadV116Logo().then((img) => { if (img) paint(img) })
541
- return t
542
- }`
543
- if (s.includes("g.fillText('V.AI', 322, 54)")) ok('cave3d: banner drawImage (idem)')
544
- else { s = s.slice(0, cutB[0]) + BANNER + s.slice(cutB[1]); ok('cave3d: makeBannerTex -> drawImage ANH POSTER (bo fillText)') }
545
-
546
- /* C2. BangVangDiemDanh: them cot "Binh chon".
547
- Giu nguyen position/rotation cua ban cu; chi doi phan ve. */
548
- const cutA = cutFn(s, 'BangVangDiemDanh')
549
- if (!cutA) throw new Error('KHONG THAY function BangVangDiemDanh')
550
- if (s.slice(cutA[0], cutA[1]).includes("g.fillText('Bình chọn'")) ok('cave3d: BangVangDiemDanh co cot Binh chon (idem)')
551
- else {
552
- const oldFn = s.slice(cutA[0], cutA[1])
553
- const mPos = /<group position=\{\[[^\]]*\]\}/.exec(oldFn)
554
- const POS = mPos ? mPos[0] : '<group position={[40, 6.0, -34]}'
555
- const BOARD = `/* V116: BANG VANG DIEM DANH — them COT "Binh chon" (binh chon theo kien
556
- thuc AI o backend). 4 cot: ten · ghe hang · tro chuyen · binh chon.
557
- Nguon /api/attendance/top (co "votes" tu V116). */
558
- function BangVangDiemDanh() {
559
- const [tex, setTex] = React.useState(null)
560
- React.useEffect(() => {
561
- let alive = true
562
- const c = document.createElement('canvas'); c.width = 900; c.height = 1000
563
- const g = c.getContext('2d')
564
- const paintBase = () => {
565
- const gr = g.createLinearGradient(0, 0, 0, 1000)
566
- gr.addColorStop(0, '#3a2a08'); gr.addColorStop(0.55, '#241a05'); gr.addColorStop(1, '#120c02')
567
- g.fillStyle = gr; g.fillRect(0, 0, 900, 1000)
568
- g.strokeStyle = 'rgba(255,215,106,0.85)'; g.lineWidth = 8; g.strokeRect(8, 8, 884, 984)
569
- g.textAlign = 'center'; g.fillStyle = '#ffd76a'; g.font = '800 44px Bitter, Georgia, serif'
570
- g.fillText('BẢNG VÀNG ĐIỂM DANH', 450, 78)
571
- g.fillStyle = 'rgba(255,240,200,0.6)'; g.font = '600 25px "Be Vietnam Pro", sans-serif'
572
- g.fillText('Siêng vào hang · trò chuyện · bình chọn AI', 450, 120)
573
- }
574
- const push = () => {
575
- if (!alive) return
576
- const t2 = new THREE.CanvasTexture(c)
577
- t2.colorSpace = THREE.SRGBColorSpace; t2.anisotropy = 16
578
- setTex(t2)
579
- }
580
- paintBase()
581
- g.textAlign = 'center'; g.fillStyle = 'rgba(255,240,200,0.5)'
582
- g.font = '600 30px "Be Vietnam Pro", sans-serif'
583
- g.fillText('Đang tải bảng điểm danh...', 450, 480)
584
- push()
585
- const draw = (rows) => {
586
- if (!alive) return
587
- paintBase()
588
- g.fillStyle = '#1c1405'; g.fillRect(20, 146, 860, 806)
589
- g.strokeStyle = 'rgba(255,215,106,0.5)'; g.lineWidth = 3; g.strokeRect(20, 146, 860, 806)
590
- g.textAlign = 'left'; g.fillStyle = '#ffd76a'; g.font = '700 25px "Be Vietnam Pro", sans-serif'
591
- g.fillText('Hạng / Tên', 40, 190)
592
- g.textAlign = 'center'
593
- g.fillText('Ghé hang', 545, 190)
594
- g.fillText('Trò chuyện', 672, 190)
595
- g.fillStyle = '#8fdcff'
596
- g.fillText('Bình chọn', 806, 190)
597
- g.strokeStyle = 'rgba(255,215,106,0.35)'; g.lineWidth = 2
598
- g.beginPath(); g.moveTo(34, 206); g.lineTo(866, 206); g.stroke()
599
- const list = (rows || []).slice(0, 10)
600
- if (!list.length) {
601
- g.textAlign = 'center'; g.fillStyle = 'rgba(255,240,200,0.55)'
602
- g.font = '600 30px "Be Vietnam Pro", sans-serif'
603
- g.fillText('Chưa có ai ghé hang — bạn hãy là người đầu tiên!', 450, 420)
604
- }
605
- list.forEach((r, i) => {
606
- const y = 258 + i * 68
607
- const isTop = i === 0
608
- if (isTop) {
609
- g.fillStyle = 'rgba(255,215,106,0.16)'; g.fillRect(30, y - 40, 840, 60)
610
- g.strokeStyle = 'rgba(255,215,106,0.8)'; g.lineWidth = 3; g.strokeRect(30, y - 40, 840, 60)
611
- } else if (i % 2) {
612
- g.fillStyle = 'rgba(255,240,200,0.05)'; g.fillRect(30, y - 40, 840, 60)
613
- }
614
- g.textAlign = 'left'
615
- g.fillStyle = isTop ? '#ffd76a' : 'rgba(255,240,200,0.85)'
616
- g.font = isTop ? '800 34px Bitter, Georgia, serif' : '700 30px "Be Vietnam Pro", sans-serif'
617
- g.fillText((i + 1) + '.', 44, y)
618
- g.fillStyle = isTop ? '#fff6d8' : 'rgba(255,245,225,0.94)'
619
- g.font = isTop ? '800 34px Bitter, Georgia, serif' : '600 30px "Be Vietnam Pro", sans-serif'
620
- let nm = String((r && r.name) || '?')
621
- if (nm.length > 15) nm = nm.slice(0, 14) + '…'
622
- g.fillText(nm, 92, y, 420)
623
- g.textAlign = 'center'
624
- g.fillStyle = isTop ? '#ffd76a' : 'rgba(255,240,200,0.9)'
625
- g.font = isTop ? '800 32px Bitter, Georgia, serif' : '700 29px "Be Vietnam Pro", sans-serif'
626
- g.fillText(String((r && r.visits) != null ? r.visits : 0), 545, y)
627
- g.fillStyle = isTop ? '#ffe9a8' : 'rgba(200,225,255,0.92)'
628
- g.fillText(String((r && r.chats) != null ? r.chats : 0), 672, y)
629
- g.fillStyle = isTop ? '#bfe9ff' : 'rgba(143,220,255,0.92)'
630
- g.fillText(String((r && r.votes) != null ? r.votes : 0), 806, y)
631
- })
632
- g.textAlign = 'right'; g.fillStyle = 'rgba(255,240,200,0.4)'
633
- g.font = '500 25px "Be Vietnam Pro", sans-serif'
634
- g.fillText('Ghé hang = số ngày · Trò chuyện = số tin · Bình chọn = số lượt', 866, 936)
635
- push()
636
- }
637
- fetch('/api/attendance/top', { cache: 'no-store' })
638
- .then((r) => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))
639
- .then((d) => draw((d && d.top) || []))
640
- .catch(() => draw([]))
641
- return () => { alive = false }
642
- }, [])
643
- if (!tex) return null
644
- return (
645
- ${POS} rotation={[0, -0.35, 0]}>
646
- <mesh position={[0, 0, -0.08]}>
647
- <boxGeometry args={[6.6, 7.3, 0.28]} />
648
- <meshLambertMaterial color="#3d2a1a" flatShading />
649
- </mesh>
650
- <mesh position={[0, 0, 0.1]}>
651
- <planeGeometry args={[6.2, 6.9]} />
652
- <meshBasicMaterial map={tex} transparent toneMapped={false} fog={false} />
653
- </mesh>
654
- </group>
655
- )
656
- }`
657
- s = s.slice(0, cutA[0]) + BOARD + s.slice(cutA[1])
658
- ok('cave3d: BangVangDiemDanh -> them COT "Binh chon"')
659
- }
660
-
661
- save(f, s)
662
- } catch (e) { fatal = 'cave3d: ' + String((e && e.message) || e) }
663
- }
664
-
665
- /* =====================================================================
666
- D) home3d.js — (2) bia do + chu khac = ANH POSTER
667
- ===================================================================== */
668
- if (!fatal) {
669
- try {
670
- const f = 'frontend/home3d.js'
671
- if (!has(f)) throw new Error('home3d.js missing')
672
- let s = read(f)
673
-
674
- const LOADER = `
675
- /* ===== V116: ANH POSTER THAT cho chu "V.AI STUDIO" ngoai cua hang. =====
676
- Truoc day bia do va dong chu khac ve bang fillText(...) — canvas dong bo nen
677
- khong dung duoc anh. Nay drawImage anh that; canvas chi ve nen/khung.
678
- Cache module + crossOrigin (bat buoc khi texture nap vao GPU). ===== */
679
- const V116_POSTER_URL = '/images/vai-logo.png'
680
- let _v116PosterImg = null
681
- let _v116PosterP = null
682
- function _v116LoadVaiPoster() {
683
- if (_v116PosterImg) return Promise.resolve(_v116PosterImg)
684
- if (_v116PosterP) return _v116PosterP
685
- if (typeof Image === 'undefined') return Promise.resolve(null)
686
- _v116PosterP = new Promise((resolve) => {
687
- const img = new Image()
688
- img.crossOrigin = 'anonymous'
689
- img.decoding = 'async'
690
- img.onload = () => { _v116PosterImg = img; resolve(img) }
691
- img.onerror = () => { _v116PosterImg = null; resolve(null) }
692
- img.src = V116_POSTER_URL
693
- })
694
- return _v116PosterP
695
- }
696
- /* Ve anh poster TRON trong o (giu ti le, khong keo gian) len canvas n. */
697
- function _v116DrawPoster(n, cx, cy, boxW, boxH, frame) {
698
- const img = _v116PosterImg
699
- if (!img || !n) return false
700
- const iw = img.naturalWidth || img.width || 1
701
- const ih = img.naturalHeight || img.height || 1
702
- const sc = Math.min(boxW / iw, boxH / ih)
703
- const w = iw * sc, h = ih * sc
704
- n.save()
705
- n.fillStyle = 'rgba(24,8,8,0.45)'
706
- n.fillRect(cx - boxW / 2, cy - boxH / 2, boxW, boxH)
707
- n.drawImage(img, cx - w / 2, cy - h / 2, w, h)
708
- if (frame !== false) {
709
- n.strokeStyle = 'rgba(246,243,238,0.92)'; n.lineWidth = 6
710
- n.strokeRect(cx - boxW / 2, cy - boxH / 2, boxW, boxH)
711
- }
712
- n.restore()
713
- return true
714
- }
715
-
716
- `
717
- if (s.includes('function _v116LoadVaiPoster(')) ok('home3d: loader poster (idem)')
718
- else {
719
- const anchor = 'function drawRedPlaque() {'
720
- if (!s.includes(anchor)) throw new Error('KHONG THAY drawRedPlaque')
721
- s = s.replace(anchor, LOADER + anchor)
722
- ok('home3d: them _v116LoadVaiPoster + _v116DrawPoster')
723
- }
724
-
725
- /* D1. bo fillText 'AI V.AI STUDIO' -> ve ANH.
726
- Anchor DUNG NGUYEN VAN tu source (da doi chieu commit e419952):
727
- " n.font = '800 150px Georgia, serif'; n.fillText('AI V.AI STUDIO', 512, 690, 940)" */
728
- /* V116f: patch_v66 REWRITES this exact line BEFORE v116 runs, with
729
- /(\bn\.font\s*=\s*)'([^']*)'(\s*;\s*)n\.fillText\(\s*'AI V\.AI STUDIO'([^)]*\))/
730
- -> TWO lines at 0.72x font size (150 -> 105). Anchoring on the REPO text
731
- therefore NEVER matched, the throw voided ALL FIVE goals, and the build
732
- shipped v115. Confirmed from the real build log + a local chain replay.
733
- Match the POST-CHAIN text by regex; on drift WARN instead of throwing so
734
- items 1/3/4/5 still ship. */
735
- const RP_RE = /n\.font = '([0-9]+)px Georgia, serif'; n\.fillText\('TRI THỨC QUANH TA', 512, 690, 940\)\s*\n\s*n\.font = '([0-9]+)px Georgia, serif'; n\.fillText\('TRÍ TUỆ VƯƠN XA', 512, 800, 940\)/
736
- const RP_NEW = `/* V116: ANH POSTER THAT thay cho fillText('AI V.AI STUDIO').
737
- Neu anh chua tai xong: ve chu du phong (bia khong bao gio trong). */
738
- if (!_v116DrawPoster(n, 512, 655, 430, 300)) {
739
- n.font = '800 132px Georgia, serif'; n.fillText('AI V.AI STUDIO', 512, 700, 940)
740
- }`
741
- if (s.includes('_v116DrawPoster(n, 512, 655')) ok('home3d: drawRedPlaque poster (idem)')
742
- else if (RP_RE.test(s)) { s = s.replace(RP_RE, RP_NEW); ok('home3d: drawRedPlaque -> drawImage ANH POSTER (bo fillText V.AI STUDIO)') }
743
- else if (s.includes(RP_OLD)) { s = s.replace(RP_OLD, RP_NEW); ok('home3d: drawRedPlaque (ban repo) -> drawImage ANH POSTER') }
744
- else warn('home3d: KHONG THAY khoi fillText cua drawRedPlaque — BO QUA muc (2) o bia do, KHONG void 4 muc con lai')
745
-
746
- /* D2. anh xong -> ve lai + needsUpdate.
747
- Anchor da doi chieu: P_W nam trong clip cua drawRedPlaque, nen phai
748
- clip lai truoc khi to nen — neu khong se to de len phan da bi cat. */
749
- const TX_OLD = ` tex.anisotropy = 16
750
- tex.repeat.set(1 / (2 * 3.3), 1 / 2); tex.offset.set(0.5, 0.5)
751
- return tex`
752
- const TX_NEW = ` tex.anisotropy = 16
753
- tex.repeat.set(1 / (2 * 3.3), 1 / 2); tex.offset.set(0.5, 0.5)
754
- /* V116: anh chua co -> ve lai vung chu bang ANH khi tai xong, roi bao GPU.
755
- (loadPlateImg().then(...) cu ve SAU khi texture da tao nhung KHONG bat
756
- needsUpdate nen logo do khong bao gio hien.)
757
- Canvas truoc do da bi clip() theo hinh bia; sau restore() thi clip da mat,
758
- nen phai CLIP LAI y het truoc khi to nen — neu khong, hinh chu nhat se
759
- tran ra ngoai duong vien bia. */
760
- _v116LoadVaiPoster().then((img) => {
761
- if (!img) return
762
- try {
763
- n.save()
764
- n.beginPath()
765
- n.moveTo(440, 62); n.quadraticCurveTo(512, 128, 584, 62); n.lineTo(700, 84); n.lineTo(986, 112)
766
- n.lineTo(994, 300); n.lineTo(690, 322); n.quadraticCurveTo(700, 600, 672, 862)
767
- n.quadraticCurveTo(512, 878, 352, 862); n.quadraticCurveTo(324, 600, 334, 322)
768
- n.lineTo(30, 300); n.lineTo(38, 112); n.lineTo(324, 84); n.closePath()
769
- n.clip()
770
- n.fillStyle = '#da291c'; n.fillRect(0, 500, P_W, 340)
771
- const _rg = n.createRadialGradient(512, 380, 60, 512, 480, 560)
772
- _rg.addColorStop(0, 'rgba(255,255,255,0.08)'); _rg.addColorStop(1, 'rgba(60,0,0,0.28)')
773
- n.fillStyle = _rg; n.fillRect(0, 500, P_W, 340)
774
- n.textAlign = 'center'; n.textBaseline = 'alphabetic'
775
- n.fillStyle = '#f6f3ee'; n.font = '800 128px Georgia, serif'
776
- n.fillText('HANG TU TRÍ', 512, 470, 940)
777
- n.restore()
778
- _v116DrawPoster(n, 512, 655, 430, 300)
779
- tex.needsUpdate = true
780
- } catch (e) { /* canvas loi thi giu ban chu */ }
781
- })
782
- return tex`
783
- if (s.includes('_v116DrawPoster(n, 512, 655, 430, 300)')) ok('home3d: ve lai poster khi anh xong (idem)')
784
- else if (s.includes(TX_OLD)) { s = s.replace(TX_OLD, TX_NEW); ok('home3d: drawRedPlaque ve lai + needsUpdate khi anh xong (clip lai)') }
785
- else throw new Error('KHONG THAY cuoi drawRedPlaque (tex.repeat/return tex)')
786
-
787
- /* D3. VaiSteleText -> state + anh.
788
- LUU Y: sau patch_v95 (tao VaiSteleText) va patch_v97 (xoa VaiSteleText,
789
- thay bang VaiSteleText2) thi ten TON TAI trong cay nguon la
790
- VaiSteleText2. patch_v116e doi anchor + signature + return shape sang
791
- dung contract cua v97; neu v97 doi ten lan nua thi cutFn tra null va
792
- v116 restore, khong sap. Component nay POSITION chinh no (<mesh
793
- position={[0,y,z]}>) vi v97 mount no truc tiep trong <group>, khac
794
- v95 mount no lam con cua <mesh>. */
795
- const cutV = cutFn(s, 'VaiSteleText2')
796
- if (!cutV) throw new Error('KHONG THAY function VaiSteleText2 (patch_v97 xoa VaiSteleText va tao VaiSteleText2)')
797
- if (s.slice(cutV[0], cutV[1]).includes('ANH POSTER THAT o nua duoi')) ok('home3d: VaiSteleText poster (idem)')
798
- else {
799
- const VT = `/* V116: dong chu khac tren tang da (VaiSteleRock). Truoc day ve
800
- fillText('V.AI STUDIO'); nay dung ANH POSTER THAT (drawImage).
801
- Canvas dong bo -> phai chuyen sang useState + useEffect de cho anh.
802
- Props theo dung contract cua patch_v97: { y, z, width }. Component
803
- POSITION chinh no bang <mesh position={[0, y, z]}> va tra ve mesh +
804
- planeGeometry + meshBasicMaterial, vi v97 mount <VaiSteleText2 ... /> truc
805
- tiep trong <group> (v95 thi mount no lam CON cua <mesh>).
806
- Moi lan ve tao 1 texture MOI va dispose texture cu (ban v95 dung useMemo
807
- nen khong bao gio ve lai duoc khi anh den). */
808
- function VaiSteleText2({ y = 0.54, z = 0.35, width = 1.24 }) {
809
- const [tex, setTex] = React.useState(null)
810
- React.useEffect(() => {
811
- let alive = true
812
- const c = document.createElement('canvas')
813
- c.width = 1024; c.height = 192
814
- const g = c.getContext('2d')
815
- const paint = () => {
816
- const img = _v116PosterImg
817
- g.clearRect(0, 0, 1024, 192)
818
- g.textAlign = 'center'; g.textBaseline = 'middle'
819
- /* chu cham: bong toi phia tren, sang phia duoi, ruot mau da am */
820
- g.font = '900 96px Bitter, Georgia, serif'
821
- g.fillStyle = 'rgba(30,20,12,0.85)'
822
- g.fillText('HANG TU TRÍ', 512, 62)
823
- g.fillStyle = '#b08a60'
824
- g.fillText('HANG TU TRÍ', 512, 56)
825
- if (img) {
826
- /* ANH POSTER THAT o nua duoi */
827
- const iw = img.naturalWidth || img.width || 1
828
- const ih = img.naturalHeight || img.height || 1
829
- const boxW = 430, boxH = 92
830
- const sc = Math.min(boxW / iw, boxH / ih)
831
- const w = iw * sc, h = ih * sc
832
- g.drawImage(img, 512 - w / 2, 100 + (boxH - h) / 2, w, h)
833
- g.strokeStyle = 'rgba(195,154,108,0.8)'; g.lineWidth = 3
834
- g.strokeRect(512 - boxW / 2, 100, boxW, boxH)
835
- } else {
836
- g.font = '800 78px Bitter, Georgia, serif'
837
- g.fillStyle = 'rgba(30,20,12,0.85)'
838
- g.fillText('V.AI STUDIO', 512, 152)
839
- g.fillStyle = '#c39a6c'
840
- g.fillText('V.AI STUDIO', 512, 146)
841
- }
842
- const t = new THREE.CanvasTexture(c)
843
- t.colorSpace = THREE.SRGBColorSpace
844
- t.anisotropy = 8
845
- t.needsUpdate = true
846
- if (alive) setTex((old) => { if (old && old.dispose) { try { old.dispose() } catch (e) {} } return t })
847
- }
848
- paint()
849
- if (!_v116PosterImg) _v116LoadVaiPoster().then(() => { if (alive) paint() })
850
- return () => { alive = false }
851
- }, [])
852
- if (!tex) return null
853
- return (
854
- <mesh position={[0, y, z]}>
855
- <planeGeometry args={[width, width * 0.1875]} />
856
- <meshBasicMaterial map={tex} transparent depthWrite={false} toneMapped={false} />
857
- </mesh>
858
- )
859
- }`
860
- s = s.slice(0, cutV[0]) + VT + s.slice(cutV[1])
861
- ok('home3d: VaiSteleText -> drawImage ANH POSTER (state cho anh)')
862
- }
863
-
864
- save(f, s)
865
- } catch (e) { fatal = 'home3d: ' + String((e && e.message) || e) }
866
- }
867
-
868
- /* =====================================================================
869
- E) backend.py — (3) cau hoi AI + luot binh chon
870
- ===================================================================== */
871
- if (!fatal) {
872
- try {
873
- const f = 'backend.py'
874
- if (!has(f)) throw new Error('backend.py missing')
875
- let s = read(f)
876
-
877
- const POLLS = [
878
- {
879
- question: 'Mô hình ngôn ngữ lớn (LLM) viết tắt của cụm nào?',
880
- options: [
881
- { icon: '🧠', text: 'Large Language Model' },
882
- { icon: '📐', text: 'Logical Layer Model' },
883
- { icon: '⚡', text: 'Long Latency Memory' },
884
- { icon: '🔁', text: 'Linear Learning Machine' },
885
- ],
886
- },
887
- {
888
- question: 'ChatGPT do công ty nào phát triển?',
889
- options: [
890
- { icon: '🤖', text: 'OpenAI' },
891
- { icon: '🔎', text: 'Google' },
892
- { icon: '🐦', text: 'xAI' },
893
- { icon: '🦙', text: 'Meta' },
894
- ],
895
- },
896
- {
897
- question: 'CUDA — nền tảng tính toán song song cho AI — do ai tạo ra?',
898
- options: [
899
- { icon: '🟩', text: 'NVIDIA' },
900
- { icon: '🔴', text: 'AMD' },
901
- { icon: '🔵', text: 'Intel' },
902
- { icon: '🍎', text: 'Apple' },
903
- ],
904
- },
905
- {
906
- question: 'Tham số "temperature" của một LLM điều chỉnh gì?',
907
- options: [
908
- { icon: '🎲', text: 'Mức ngẫu nhiên của câu trả lời' },
909
- { icon: '📏', text: 'Số token tối đa' },
910
- { icon: '🚀', text: 'Tốc độ sinh chữ' },
911
- { icon: '💾', text: 'Kích thước mô hình' },
912
- ],
913
- },
914
- ]
915
- const PYB = POLLS.map((q) => {
916
- const opts = q.options.map((o) => '{"icon": ' + JSON.stringify(o.icon) + ', "text": ' + JSON.stringify(o.text) + '}').join(', ')
917
- return ' {"question": ' + JSON.stringify(q.question) + ', "options": [' + opts + ']},'
918
- }).join('\n')
919
- const POLL_NEW = 'POLL_QUESTIONS = [\n' + PYB + '\n]'
920
-
921
- /* V116f: 'Large Language Model' ALREADY EXISTS elsewhere in backend.py
922
- (the pre-existing AI quiz, ~line 1255), so it is NOT a usable
923
- idempotency marker — it made this step a silent no-op and left the
924
- 4 MU football questions in place. Test the POLL_QUESTIONS block
925
- itself instead. */
926
- if (/POLL_QUESTIONS = \[\s*\{"question": "Mô hình ngôn ngữ lớn/.test(s)) ok('backend: POLL_QUESTIONS AI (idem)')
927
- else {
928
- const cb = cutBracket(s, 'POLL_QUESTIONS = [')
929
- if (!cb) throw new Error('KHONG THAY POLL_QUESTIONS')
930
- s = s.slice(0, cb[0]) + POLL_NEW + s.slice(cb[1])
931
- ok('backend: POLL_QUESTIONS 4 cau MU -> 4 cau kien thuc AI')
932
- }
933
-
934
- /* V116f: /api/video-proxy phai NHAN &loop=0. app.js sends it (see the
935
- video effect) but the pristine route declares only (url, title, img), so
936
- FastAPI ignored it and video_proxy kept loop=1 -> video replayed forever
937
- and items (4) auto-advance could never fire.
938
- patch_v46 DUPLICATES this route at build time and its anchor is the
939
- EXACT original signature, so this must NOT be done by editing the
940
- committed backend.py (that breaks v46 and every later backend patch).
941
- v116 runs LAST, so both copies exist by now — rewrite them here. */
942
- const VP_SIG = `async def api_video_proxy(url: str = "", title: str = "", img: str = ""):`
943
- const VP_NEW = `async def api_video_proxy(url: str = "", title: str = "", img: str = "", loop: int = 1):`
944
- const VP_CALL = ` return video_proxy.render_video_proxy(url, title, img)`
945
- const VP_CALL_NEW = ` return video_proxy.render_video_proxy(url, title, img, loop)`
946
- if (s.includes(VP_NEW)) ok('backend: /api/video-proxy nhan loop (idem)')
947
- else {
948
- const nSig = s.split(VP_SIG).length - 1
949
- const nCall = s.split(VP_CALL).length - 1
950
- if (!nSig || !nCall) warn('backend: KHONG THAY route /api/video-proxy (loop=) — bo qua, video van lap')
951
- else {
952
- s = s.split(VP_SIG).join(VP_NEW)
953
- s = s.split(VP_CALL).join(VP_CALL_NEW)
954
- ok('backend: /api/video-proxy nhan loop (' + nSig + ' route) -> proxy loop=0 hoat dong')
955
- }
956
- }
957
-
958
- /* V116f: /api/video-proxy phai NHAN &loop=0 (item 4: tu nhay bai).
959
- app.js gui &loop=0 nhung route chi khai bao (url,title,img) nen FastAPI
960
- BO QUA -> video_proxy hardcode loop=1 -> iframe lap mai, KHONG BAO GIO
961
- ket thuc -> hangmu-ended khong bao gio ban -> khong tu nhay bai.
962
- patch_v60 GHI DE TOAN BO video_proxy.py tu template CLEAN_PROXY tai
963
- build time, nen sua file trong repo la VO NGHIA (da thu: 500
964
- "render_video_proxy() takes from 1 to 3 positional arguments but 4 were
965
- given"). v116 chay SAU v60 -> sua tai day. */
966
- {
967
- const vp = 'video_proxy.py'
968
- if (!has(vp)) throw new Error('video_proxy.py missing')
969
- let v = read(vp)
970
- const VP_SIG_O = 'def render_video_proxy(url: str, title: str = "", img: str = ""):'
971
- const VP_SIG_N = 'def render_video_proxy(url: str, title: str = "", img: str = "", loop: int = 1):'
972
- const VP_T_O = ' t = _re.sub(r"[<>&\\"\']", "", title or "Highlight MU")[:120]'
973
- const VP_T_N = VP_T_O + '\n' +
974
- ' # V116: app.js gui &loop=0 -> video PHAI ket thuc that de tu nhay bai.\n' +
975
- ' _lp = str(loop).strip().lower()\n' +
976
- ' loop_ok = "0" if _lp in ("0", "false", "no", "off") else "1"\n' +
977
- ' origin = "https://bep40-hangmu-docker.hf.space"'
978
- const VP_IFR_O = 'playsinline=1&loop=1&playlist={vid}"'
979
- const VP_IFR_N = 'playsinline=1&enablejsapi=1&origin={origin}&loop={loop_ok}&playlist={vid}"'
980
- const VP_ONR_O = " if (d && (d.event === 'onReady' || d.event === 'infoDelivery')) onReady();"
981
- const VP_ONR_N = " if (d && (d.event === 'onReady' || d.event === 'infoDelivery')) {{\n" +
982
- " onReady();\n" +
983
- " // playerState 0 = ENDED. Chi xay ra khi loop=0 (loop=1 thi YT tu lap).\n" +
984
- " if (d.info && d.info.playerState === 0) tellEnded();\n" +
985
- " }}"
986
- const VP_TELL = " var endedSent = false;\n" +
987
- " function tellEnded() {{\n" +
988
- " if (endedSent) return;\n" +
989
- " endedSent = true;\n" +
990
- " try {{\n" +
991
- " if (window.parent && window.parent !== window) {{\n" +
992
- " window.parent.postMessage(JSON.stringify({{ event: 'hangmu-ended', videoId: vid }}), '*');\n" +
993
- " }}\n" +
994
- " }} catch (e) {{}}\n" +
995
- " }}\n"
996
- if (v.includes('hangmu-ended')) ok('video_proxy: loop + hangmu-ended (idem)')
997
- else if (!v.includes(VP_SIG_O) || !v.includes(VP_T_O) || !v.includes(VP_IFR_O) || !v.includes(VP_ONR_O)) {
998
- warn('video_proxy: KHONG THAY du anchor cua v60 — BO QUA loop=0 (video se lap lai, khong tu nhay bai)')
999
- } else {
1000
- v = v.replace(VP_SIG_O, VP_SIG_N, 1)
1001
- v = v.replace(VP_T_O, VP_T_N, 1)
1002
- v = v.replace(VP_IFR_O, VP_IFR_N, 1)
1003
- v = v.replace(" var told = false;\n", " var told = false;\n" + VP_TELL, 1)
1004
- v = v.replace(VP_ONR_O, VP_ONR_N, 1)
1005
- save(vp, v)
1006
- ok('video_proxy: nhan loop=0 + enablejsapi + ban hangmu-ended khi ENDED')
1007
- }
1008
- }
1009
-
1010
- const VOTE_OLD = `poll["voted"][player_id] = True
1011
- poll["counts"][int(msg.get("option", 0)) % len(poll["options"])] += 1`
1012
- const VOTE_NEW = `poll["voted"][player_id] = True
1013
- poll["counts"][int(msg.get("option", 0)) % len(poll["options"])] += 1
1014
- _att_bump(p.name, "votes") # V116: diem danh theo luot binh chon`
1015
- if (s.includes('_att_bump(p.name, "votes")')) ok('backend: dem votes (idem)')
1016
- else if (s.includes(VOTE_OLD)) { s = s.replace(VOTE_OLD, VOTE_NEW); ok('backend: hook vote -> _att_bump(name,"votes")') }
1017
- else throw new Error('KHONG THAY handler vote')
1018
-
1019
- const SD_OLD = ' e = _att_stats.setdefault(nm, {"visits": 0, "chats": 0})'
1020
- const SD_NEW = ' e = _att_stats.setdefault(nm, {"visits": 0, "chats": 0, "joins": 0, "votes": 0})'
1021
- if (s.includes('"votes": 0}')) ok('backend: setdefault votes (idem)')
1022
- else if (s.includes(SD_OLD)) { s = s.replace(SD_OLD, SD_NEW); ok('backend: _att_stats mac dinh co votes') }
1023
- else throw new Error('KHONG THAY setdefault _att_stats')
1024
-
1025
- /* Nap "votes" trong MOI khoi _att_stats[str(k)[:60]] = { ... } (att_load,
1026
- att_pull co do sau khac nhau tuy bien the) — dong quat, khong anchor chuoi. */
1027
- const NEEDLE = '_att_stats[str(k)[:60]] = {'
1028
- let added = 0
1029
- {
1030
- let out = ''
1031
- let i = 0
1032
- for (;;) {
1033
- const p = s.indexOf(NEEDLE, i)
1034
- if (p === -1) { out += s.slice(i); break }
1035
- const open = s.indexOf('{', p)
1036
- if (open === -1) { out += s.slice(i); break }
1037
- let d = 0, end = -1
1038
- for (let k = open; k < s.length; k++) {
1039
- if (s[k] === '{') d++
1040
- else if (s[k] === '}') { d--; if (d === 0) { end = k; break } }
1041
- }
1042
- if (end === -1) { out += s.slice(i); break }
1043
- const block = s.slice(open, end + 1)
1044
- if (block.includes('"votes"')) { out += s.slice(i, end + 1); i = end + 1; continue }
1045
- const interior = s.slice(open + 1, end)
1046
- const lines = interior.split('\n').filter((l) => l.trim())
1047
- const lastLine = lines.length ? lines[lines.length - 1] : ''
1048
- const indent = (lastLine.match(/^[ \t]*/) || [''])[0] || ' '
1049
- out += s.slice(i, end).replace(/[ \t]+$/, '')
1050
- out += '\n' + indent + '"votes": int(v.get("votes", 0)),'
1051
- out += s.slice(end, end + 1)
1052
- i = end + 1
1053
- added++
1054
- }
1055
- if (added) s = out
1056
- }
1057
- if (added) ok('backend: nap "votes" trong ' + added + ' khoi _att_stats (att_load/att_pull)')
1058
- else if (s.includes('"votes": int(v.get("votes", 0))')) ok('backend: _att_stats da nap votes (idem)')
1059
- else throw new Error('KHONG THAY khoi _att_stats[str(k)[:60]] de nap votes')
1060
-
1061
- const SC_OLD = ' return int(r.get("visits", 0)) * 20 + int(r.get("chats", 0)) * 2 + int(r.get("joins", 0))'
1062
- const SC_NEW = ' return int(r.get("visits", 0)) * 20 + int(r.get("chats", 0)) * 2 + int(r.get("joins", 0)) + int(r.get("votes", 0)) * 3 # V116: + binh chon'
1063
- if (s.includes('int(r.get("votes", 0)) * 3')) ok('backend: _att_score votes (idem)')
1064
- else if (s.includes(SC_OLD)) { s = s.replace(SC_OLD, SC_NEW); ok('backend: _att_score -> + votes*3') }
1065
- else throw new Error('KHONG THAY return cua _att_score')
1066
-
1067
- const ROW_OLD = ` [{"name": k, "visits": int(v.get("visits", 0)),
1068
- "chats": int(v.get("chats", 0)),
1069
- "joins": int(v.get("joins", 0))}
1070
- for k, v in _att_stats.items()],`
1071
- const ROW_NEW = ` [{"name": k, "visits": int(v.get("visits", 0)),
1072
- "chats": int(v.get("chats", 0)),
1073
- "joins": int(v.get("joins", 0)),
1074
- "votes": int(v.get("votes", 0))}
1075
- for k, v in _att_stats.items()],`
1076
- if (s.includes(ROW_NEW)) ok('backend: top tra votes (idem)')
1077
- else if (s.includes(ROW_OLD)) { s = s.replace(ROW_OLD, ROW_NEW); ok('backend: /api/attendance/top tra them "votes"') }
1078
- else throw new Error('KHONG THAY row cua /api/attendance/top')
1079
-
1080
- save(f, s)
1081
- } catch (e) { fatal = 'backend: ' + String((e && e.message) || e) }
1082
- }
1083
-
1084
- /* =====================================================================
1085
- F) GUARD + VALIDATE -> loi thi RESTORE
1086
- ===================================================================== */
1087
- let restored = false
1088
- if (!fatal) {
1089
- try {
1090
- const bad = []
1091
- const app = read('frontend/app.js')
1092
- const cav = read('frontend/cave3d.js')
1093
- const hom = read('frontend/home3d.js')
1094
- const bek = read('backend.py')
1095
-
1096
- /* V116 khong con tu thay mieng lung — viec do la cua v116b. */
1097
- for (const m of ['function useVaiLogoTex(',
1098
- 'const vaiLogoTex = useVaiLogoTex()',
1099
- 'VAI_LOGO_URL',
1100
- 'function _v116NumTex(',
1101
- 'const [playIdx, setPlayIdx] = React.useState(-1)',
1102
- 'hangmu-ended',
1103
- '&loop=0',
1104
- 'board-playbar-toggle',
1105
- 'board-playbar-card${i === playIdx']) {
1106
- if (!app.includes(m)) bad.push('app.js thieu: ' + m)
1107
- }
1108
- if ((app.match(/function useVaiLogoTex\(/g) || []).length !== 1) bad.push('useVaiLogoTex != 1')
1109
- if ((app.match(/<group ref=\{rootRef\}/g) || []).length !== 1) bad.push('rootRef != 1 (nhan vat bi xoa!)')
1110
-
1111
- for (const m of ['function loadV116Logo(',
1112
- "g.fillText('V.AI', 322, 54)",
1113
- "g.fillText('Bình chọn', 806, 190)",
1114
- 'r.votes']) {
1115
- if (!cav.includes(m)) bad.push('cave3d thieu: ' + m)
1116
- }
1117
- if ((cav.match(/function BangVangDiemDanh\(/g) || []).length !== 1) bad.push('BangVangDiemDanh != 1')
1118
- if ((cav.match(/function makeBannerTex\(/g) || []).length !== 1) bad.push('makeBannerTex != 1')
1119
-
1120
- for (const m of ['function _v116LoadVaiPoster(',
1121
- '_v116DrawPoster(n, 512, 655']) {
1122
- if (!hom.includes(m)) bad.push('home3d thieu: ' + m)
1123
- }
1124
- if ((hom.match(/function VaiSteleText2\(/g) || []).length !== 1) bad.push('VaiSteleText2 != 1')
1125
- if ((hom.match(/function drawRedPlaque\(/g) || []).length !== 1) bad.push('drawRedPlaque != 1')
1126
-
1127
- if (!bek.includes('Large Language Model')) bad.push('backend: POLL_QUESTIONS chua la cau AI')
1128
- if (!bek.includes('"votes": int(v.get("votes", 0))')) bad.push('backend: thieu votes trong du lieu')
1129
- if (!bek.includes('_att_bump(p.name, "votes")')) bad.push('backend: thieu hook votes')
1130
- if (!bek.includes('int(r.get("votes", 0)) * 3')) bad.push('backend: thieu votes trong _att_score')
1131
- if (!/POLL_QUESTIONS = \[/.test(bek)) bad.push('backend: POLL_QUESTIONS bi xoa')
1132
- if (bad.length) throw new Error('marker: ' + bad.join(' | '))
1133
-
1134
- const esbuild = await import('esbuild')
1135
- for (const p of ['frontend/app.js', 'frontend/cave3d.js', 'frontend/home3d.js']) {
1136
- try { await esbuild.transform(read(p), { loader: 'jsx', format: 'esm', target: 'es2020' }) }
1137
- catch (err) { throw new Error(p + ' KHONG HOP LE: ' + String((err && err.message) || err).split('\n').slice(0, 3).join(' ')) }
1138
- }
1139
- ok('esbuild transform OK: app.js + cave3d.js + home3d.js hop le')
1140
- } catch (e) {
1141
- warn('VALIDATE THAT BAI: ' + String((e && e.message) || e))
1142
- for (const k of Object.keys(BAK)) save(k, BAK[k])
1143
- restored = true
1144
- warn('DA RESTORE ve ban truoc V116 — Space van chay binh thuong')
1145
- }
1146
- } else {
1147
- warn(fatal)
1148
- for (const k of Object.keys(BAK)) save(k, BAK[k])
1149
- restored = true
1150
- warn('DA RESTORE ve ban truoc V116 — Space van chay binh thuong')
1151
- }
1152
- if (restored) { console.log('[v116] SKIPPED (restored)'); process.exit(0) }
1153
-
1154
- /* =====================================================================
1155
- G) index.html: chen <link> playlist.css + cache-bust ; VERSION_ID
1156
- ===================================================================== */
1157
- try {
1158
- if (has('backend.py')) {
1159
- const b = read('backend.py')
1160
- const nb = b.replace(/VERSION_ID = "v\d+"/, 'VERSION_ID = "v116"')
1161
- if (nb !== b) { save('backend.py', nb); ok('backend.py: VERSION_ID -> v116') }
1162
- }
1163
- for (const ip of ['frontend/index.html', 'index.html']) {
1164
- if (!has(ip)) continue
1165
- let h = read(ip)
1166
- const before = h
1167
- if (!h.includes('/styles/playlist.css')) {
1168
- h = h.replace('</head>', ' <link rel="stylesheet" href="/styles/playlist.css?v=116" />\n </head>')
1169
- }
1170
- h = h.replace(/\?v=\d+/g, '?v=116')
1171
- if (h !== before) { save(ip, h); ok(ip + ': <link> playlist.css + cache-bust -> ?v=116') }
1172
- }
1173
- } catch (e) { warn('version: ' + String((e && e.message) || e)) }
1174
-
1175
- console.log('[v116] DONE: ' + n + ' muc ap dung')
1176
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v116a.mjs DELETED
@@ -1,49 +0,0 @@
1
- /* patch_v116a.mjs — V116a: sua duy nhat MOT loi cua V116 (yeu cau 4).
2
- =========================================================================
3
- LOI: patch_v116 dat `const [playIdx, setPlayIdx] = React.useState(-1)` va
4
- trong effect moi dung
5
- const _idx = playIdx < 0 ? 0 : playIdx % useIds.length
6
- => khi vua vao hang (playIdx = -1) video LUON phat bai DAU, khong random.
7
- Dung yeu cau (4): "playItem(0) -> playItem(Math.floor(Math.random()*totalV))".
8
-
9
- SUA: khi playIdx < 0 (chua chon bai) thi chon NGAU NHIEN mot bai.
10
- Co tinh KHONG goi setPlayIdx luc mount: playIdx = -1 dong vai "chua chon",
11
- effect chi chay lai khi playIdx doi, nen random duoc chon DUNG MOT LAN —
12
- khong sinh them mot lan load iframe thu hai (setState trong effect se lam
13
- video nhay 2 lan).
14
-
15
- An toan: chi sua 1 dong, backup + restore neu khong khop. exit 0.
16
- ========================================================================= */
17
- import fs from 'node:fs'
18
- import path from 'node:path'
19
-
20
- const ROOT = process.argv[2] || '.'
21
- const F = path.join(ROOT, 'frontend/app.js')
22
- if (!fs.existsSync(F)) { console.warn('[v116a] WARN: app.js missing — skip'); process.exit(0) }
23
-
24
- const orig = fs.readFileSync(F, 'utf8')
25
- let s = orig
26
-
27
- const OLD = 'const _idx = playIdx < 0 ? 0 : playIdx % useIds.length'
28
- const NEW = 'const _idx = playIdx < 0 ? Math.floor(Math.random() * useIds.length) : playIdx % useIds.length'
29
-
30
- if (s.includes('Math.floor(Math.random() * useIds.length)')) {
31
- console.log('[v116a] OK: da random san (idem)')
32
- } else if (s.includes(OLD)) {
33
- s = s.split(OLD).join(NEW)
34
- console.log('[v116a] OK: vao hang -> BAI NGAU NHIEN (yeu cau 4)')
35
- } else {
36
- console.warn('[v116a] WARN: KHONG THAY dong _idx cua V116 — patch_v116 co the chua chay. Bo qua.')
37
- process.exit(0)
38
- }
39
-
40
- /* Guard toi thieu: khong duoc lam hong bundle, va khong duoc de lai loop=1 */
41
- if (/loop=1&playlist=/.test(s)) {
42
- console.warn('[v116a] WARN: phat hien loop=1 — khoi phuc ban truoc')
43
- fs.writeFileSync(F, orig)
44
- process.exit(0)
45
- }
46
-
47
- fs.writeFileSync(F, s)
48
- console.log('[v116a] DONE')
49
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v116b.mjs DELETED
@@ -1,172 +0,0 @@
1
- /* patch_v116b.mjs — V116b: sua 3 LOI THAT cua patch_v116, tim ra bang cach
2
- doi chieu voi source GOC (commit e419952) va patch_v115.mjs.
3
- =========================================================================
4
- LOI 1 (nghiem trong nhat — "mieng dan TRANG"): patch_v116 thay mieng lung
5
- <mesh>...<planeGeometry 0.26x0.244 />...<meshBasicMaterial map={_v115BackTex(p.number)} />
6
- bang mot mesh co map={vaiLogoTex}, nhung vaiLogoTex = NULL trong lan render
7
- dau (anh load bat dong bo). meshBasicMaterial voi map=null ve MAU TRANG duc
8
- => lung ao thanh mot mieng trang. Day dung la loi ma ban than V116 da mo ta
9
- ("can them state cho anh load") nhung patch_v116 lai KHONG guard.
10
- SUA: chi render mesh khi vaiLogoTex != null.
11
-
12
- LOI 2 (anchor mo ho): patch_v116 tim `s.indexOf('</mesh>', iGeo)` de ket thuc
13
- mieng lung. Nhung no bat dau tu <planeGeometry> nam BEN TRONG <mesh>, nen
14
- phuong an do chi dung nho "<planeGeometry" la con DAU TIEN cua mesh.
15
- Doi sang cat TRON <mesh> theo `position={[0, 0.99, -0.306]}` — dinh danh
16
- duy nhat do chinh patch_v115 dat vao, khong the nham.
17
-
18
- LOI 3 (ao trong khi anh loi): neu /images/vai-logo.png 404 thi khong co logo
19
- nao ca. SUA: texture du phong ve huy hieu V.AI STUDIO bang canvas, chi dung
20
- khi anh that FAIL — nen ao khong bao gio trong.
21
-
22
- V116f (HARDENING): v116b truoc day chay VO DIEU KIEN. Neu patch_v116 da
23
- RESTORE (anchor chet), thi vaiLogoTex / _v116NumTex KHONG TON TAI, nhung
24
- v116b van chen {vaiLogoTex && ( ... )} + map={_v116NumTex(p.number)} vao
25
- PlayerAvatar => ReferenceError => ErrorBoundary => mat TOAN BO app (te hon
26
- v115, vi truoc do khong co v116). patch_v116d da don cac tham chieu mo coi
27
- do SAU, nhung cach do la chua trieu chung.
28
- Nay v116b tu KIEM TRA: khong thay function _v116LoadLogoTex( (do chinh
29
- patch_v116 dinh nghia, CUNG luc voi vaiLogoTex/_v116NumTex) thi BO QUA
30
- hoan toan — tham chieu mo coi KHONG BAO GIO duoc tao ra.
31
- v116d van duoc giu nhu lop chan thu hai, doc lap.
32
-
33
- An toan: backup + restore neu marker khong khop; exit 0.
34
- ========================================================================= */
35
- import fs from 'node:fs'
36
- import path from 'node:path'
37
-
38
- const ROOT = process.argv[2] || '.'
39
- const F = path.join(ROOT, 'frontend/app.js')
40
- if (!fs.existsSync(F)) { console.warn('[v116b] WARN: app.js missing — skip'); process.exit(0) }
41
-
42
- const BAK = fs.readFileSync(F, 'utf8')
43
- let s = BAK
44
- let n = 0
45
- const ok = (m) => { n++; console.log('[v116b] OK: ' + m) }
46
- const warn = (m) => console.warn('[v116b] WARN: ' + m)
47
-
48
- /* ---------- 0) V116f HARDENING — dung han neu patch_v116 da restore ----
49
- vaiLogoTex va _v116NumTex CHI do patch_v116 dinh nghia, cung luc voi
50
- function _v116LoadLogoTex(. Neu loader do khong co thi hai ten kia cung
51
- khong co: chen chung vao day se tao tham chieu mo coi => ReferenceError
52
- khi PlayerAvatar render => mat ca app. Bo qua hoan toan thay vi chen. */
53
- if (!s.includes('function _v116LoadLogoTex(')) {
54
- warn('patch_v116 CHUA ap dung (khong thay function _v116LoadLogoTex) — BO QUA v116b, khong chen tham chieu mo coi')
55
- console.log('[v116b] DONE (no-op: v116 restore — app giu nguyen hanh vi v115, khong crash)')
56
- process.exit(0)
57
- }
58
-
59
- /* ---------- 1) texture du phong khi anh that FAIL ---------- */
60
- if (s.includes('function _v116FallbackTex(')) ok('fallback tex da co (idem)')
61
- else if (s.includes('function _v116LoadLogoTex(')) {
62
- const FB = `
63
- /* V116b: chi dung khi /images/vai-logo.png LOAD LOI — ve huy hieu V.AI STUDIO
64
- bang canvas de lung ao khong bao gio bi trong. */
65
- function _v116FallbackTex() {
66
- if (_v116FallbackTex._t) return _v116FallbackTex._t
67
- const c = document.createElement('canvas'); c.width = 320; c.height = 300
68
- const g = c.getContext('2d')
69
- g.clearRect(0, 0, 320, 300)
70
- g.textAlign = 'center'; g.textBaseline = 'middle'
71
- g.strokeStyle = 'rgba(34,48,77,0.55)'; g.lineWidth = 5
72
- g.beginPath(); g.arc(160, 96, 62, 0, Math.PI * 2); g.stroke()
73
- g.lineWidth = 11; g.strokeStyle = 'rgba(34,48,77,0.85)'; g.fillStyle = '#ffffff'
74
- g.font = '900 94px Bitter, Georgia, serif'
75
- g.strokeText('V', 160, 98); g.fillText('V', 160, 98)
76
- g.font = '800 27px Bitter, Georgia, serif'
77
- g.strokeText('STUDIO', 160, 152); g.fillText('STUDIO', 160, 152)
78
- g.font = '700 20px "Be Vietnam Pro", Arial, sans-serif'
79
- g.fillStyle = 'rgba(255,255,255,0.74)'
80
- g.fillText('HANG TU TRI AI', 160, 262)
81
- const t = new THREE.CanvasTexture(c)
82
- t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8; t.needsUpdate = true
83
- _v116FallbackTex._t = t
84
- return t
85
- }
86
- `
87
- s = s.replace('function _v116LoadLogoTex(', FB.trimStart() + 'function _v116LoadLogoTex(')
88
- /* khi load loi -> texture du phong, KHONG phai null */
89
- s = s.split('}, undefined, () => { _v116Logo.done = true; resolve(null) })')
90
- .join('}, undefined, () => { _v116Logo.done = true; _v116Logo.tex = _v116FallbackTex(); resolve(_v116Logo.tex) })')
91
- s = s.split(' } catch (e) { _v116Logo.done = true; resolve(null) }')
92
- .join(' } catch (e) { _v116Logo.done = true; _v116Logo.tex = _v116FallbackTex(); resolve(_v116Logo.tex) }')
93
- s = s.split("} catch (e) { _v116Logo.done = true; resolve(null) }")
94
- .join("} catch (e) { _v116Logo.done = true; _v116Logo.tex = _v116FallbackTex(); resolve(_v116Logo.tex) }")
95
- s = s.split("if (typeof THREE === 'undefined' || !THREE.TextureLoader) { _v116Logo.done = true; resolve(null); return }")
96
- .join("if (typeof THREE === 'undefined' || !THREE.TextureLoader) { _v116Logo.done = true; resolve(null); return }")
97
- ok('them _v116FallbackTex + dung khi anh that load loi')
98
- } else warn('KHONG THAY _v116LoadLogoTex — patch_v116 chua chay?')
99
-
100
- /* ---------- 2) THAY TRON mieng lung V115 -> ANH POSTER, co guard null ---------- */
101
- const OPEN = '<mesh position={[0, 0.99, -0.306]} rotation-y={Math.PI}>'
102
- if (s.includes('V116b: LUNG AO = ANH POSTER THAT')) ok('mieng lung da sua (idem)')
103
- else {
104
- const i0 = s.indexOf(OPEN)
105
- if (i0 === -1) warn('KHONG THAY <mesh position={[0, 0.99, -0.306]}> cua V115 — bo qua')
106
- else {
107
- const iEnd = s.indexOf('</mesh>', i0)
108
- if (iEnd === -1) warn('KHONG THAY </mesh> dong mieng lung — bo qua')
109
- else {
110
- const BLOCK = `{/* V116b: LUNG AO = ANH POSTER THAT, LON HON backPlateTex()
111
- cu (0.26x0.244 -> 0.36x0.32, dien tich x1.8). Guard vaiLogoTex: neu
112
- render khi map=null thi meshBasicMaterial ve MOT MIENG TRANG —
113
- dung loi V116 ban dau mac phai. Anh load bat dong bo nen lan render
114
- dau tien KHONG ve gi ca, vai giu nguyen mau ao. */}
115
- {vaiLogoTex && (
116
- <mesh position={[0, 0.99, -0.306]} rotation-y={Math.PI}>
117
- <planeGeometry args={[0.36, 0.32]} />
118
- <meshBasicMaterial map={vaiLogoTex} transparent
119
- depthWrite={false} toneMapped={false} fog={false} />
120
- </mesh>
121
- )}
122
- {/* V116: SO AO — mieng RIENG 0.13x0.13 dat TRUOC mat poster (z -0.313 <
123
- -0.306) nen poster khong che so. Canvas nen TRONG SUOT. */}
124
- {p.number != null && String(p.number) !== '' && (
125
- <mesh position={[0, 0.885, -0.313]} rotation-y={Math.PI}>
126
- <planeGeometry args={[0.13, 0.13]} />
127
- <meshBasicMaterial map={_v116NumTex(p.number)} transparent
128
- depthWrite={false} toneMapped={false} fog={false} />
129
- </mesh>
130
- )}`
131
- s = s.slice(0, i0) + BLOCK + s.slice(iEnd + '</mesh>'.length)
132
- ok('LUNG AO -> <mesh> duoc guard vaiLogoTex, poster 0.36x0.32 + so ao rieng')
133
- }
134
- }
135
- }
136
-
137
- /* ---------- 3) GUARD ---------- */
138
- const bad = []
139
- if (!s.includes('vaiLogoTex && (')) bad.push('thieu guard vaiLogoTex && ( -> se co mieng TRANG')
140
- if (!s.includes('<planeGeometry args={[0.36, 0.32]} />')) bad.push('thieu poster 0.36x0.32')
141
- if (!s.includes('_v116NumTex(p.number)')) bad.push('thieu so ao rieng')
142
- if (s.includes('map={_v115BackTex(p.number)}')) bad.push('van con _v115BackTex (chua thay)')
143
- if ((s.match(/<group ref=\{rootRef\}/g) || []).length !== 1) bad.push('rootRef != 1 (nhan vat bi xoa!)')
144
- /* meshBasicMaterial map={vaiLogoTex} PHAI nam trong guard */
145
- const gi = s.indexOf('vaiLogoTex && (')
146
- const mi = s.indexOf('map={vaiLogoTex}')
147
- if (mi !== -1 && gi !== -1 && mi < gi) bad.push('map={vaiLogoTex} nam NGOAI guard')
148
- /* V116f: ca hai ten duoc chen phai THUC SU duoc dinh nghia trong file nay,
149
- neu khong thi da tao ra tham chieu mo coi => ReferenceError luc render. */
150
- if (!s.includes('function _v116LoadLogoTex(')) bad.push('thieu dinh nghia _v116LoadLogoTex')
151
- if (!s.includes('function _v116NumTex(')) bad.push('thieu dinh nghia _v116NumTex')
152
- if (bad.length) {
153
- warn('VALIDATE THAT BAI: ' + bad.join(' | '))
154
- fs.writeFileSync(F, BAK)
155
- warn('DA RESTORE app.js ve truoc V116b')
156
- process.exit(0)
157
- }
158
-
159
- try {
160
- const esbuild = await import('esbuild')
161
- await esbuild.transform(s, { loader: 'jsx', format: 'esm', target: 'es2020' })
162
- ok('esbuild transform OK')
163
- } catch (e) {
164
- warn('JSX KHONG HOP LE: ' + String((e && e.message) || e).split('\n').slice(0, 3).join(' '))
165
- fs.writeFileSync(F, BAK)
166
- warn('DA RESTORE app.js ve truoc V116b')
167
- process.exit(0)
168
- }
169
-
170
- fs.writeFileSync(F, s)
171
- console.log('[v116b] DONE: ' + n + ' muc')
172
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v116c.mjs DELETED
@@ -1,216 +0,0 @@
1
- /* patch_v116c.mjs — V116c: dung LAI BangVangDiemDanh cho DUNG ban goc
2
- =========================================================================
3
- Cac loi cua patch_v116 ma patch nay sua:
4
-
5
- LOI A (hoi quy tinh nang): patch_v116 thay TOAN BO function BangVangDiemDanh
6
- va chi fetch MOT LAN. Ban goc (do patch_v83 tao ra) co POLLING
7
- setInterval 60s voi clearInterval khi unmount. Thay ca function =>
8
- bang dung yen sau lan tai dau.
9
-
10
- LOI B (thay doi pham vi, khong ai yeu cau): ban viet lai cua v116 doi luon
11
- ca kich thuoc canvas va hinh hoc cua bang:
12
- goc : canvas 1024x1180, boxGeometry 8.0x9.0, planeGeometry 7.6x8.6,
13
- rotation [0, -0.42, 0]
14
- v116 : canvas 900x1000, boxGeometry 6.6x7.3, planeGeometry 6.2x6.9,
15
- rotation [0, -0.35, 0]
16
- Nguoi dung chi yeu cau THEM COT "luot binh chon" — khong yeu cau doi
17
- kich thuoc/goc xoay cua bang. Ban nay giu NGUYEN canvas 1024x1180.
18
-
19
- LOI C (phat hien khi doi chieu patch_v116.mjs, sua o ban nay):
20
- Ban dau patch nay "giu nguyen opening tag <group>" doc tu function dang co.
21
- NHUNG patch_v116 LUON chay truoc va LUON dat rotation={[0, -0.35, 0]}.
22
- => "giu nguyen tag" hoa ra la giu DUNG cai rotation SAI cua v116, khong
23
- bao gio khoi phuc duoc -0.42 cua patch_v83. Goc nhin bang bi lech so voi
24
- ban goc ma khong ai yeu cau.
25
- SUA: giu `position` (vi patch_v82/v84 co the da doi vi tri that su, nen
26
- phai doc tu source hien tai) NHUNG LUON dat lai rotation ve -0.42 goc.
27
-
28
- KHONG phu thuoc patch_v116: patch nay dung lai tu BAT KY ban nao dang co
29
- (ban goc patch_v83 hoac ban cua v116), nen cot thu 4 luon duoc tao ke ca
30
- khi patch_v116 tu restore vi anchor troi. Idempotent qua marker V116c.
31
-
32
- Ket qua: bang giong het ban goc + 1 cot moi "BINH CHON" + polling 60s.
33
- An toan: backup + restore neu marker khong khop; esbuild.transform phai qua.
34
- ========================================================================= */
35
- import fs from 'node:fs'
36
- import path from 'node:path'
37
-
38
- const ROOT = process.argv[2] || '.'
39
- const F = path.join(ROOT, 'frontend/cave3d.js')
40
- if (!fs.existsSync(F)) { console.warn('[v116c] WARN: cave3d.js missing — skip'); process.exit(0) }
41
-
42
- const BAK = fs.readFileSync(F, 'utf8')
43
- let s = BAK
44
- let n = 0
45
- const ok = (m) => { n++; console.log('[v116c] OK: ' + m) }
46
- const warn = (m) => console.warn('[v116c] WARN: ' + m)
47
-
48
- /* cat khoi function theo TEN, can bang ngoac { } */
49
- function cutFn(src, name) {
50
- const m = new RegExp('function\\s+' + name + '\\s*\\([^)]*\\)\\s*\\{').exec(src)
51
- if (!m) return null
52
- const start = src.indexOf('{', m.index)
53
- let d = 0
54
- for (let k = start; k < src.length; k++) {
55
- if (src[k] === '{') d++
56
- else if (src[k] === '}') { d--; if (d === 0) return [m.index, k + 1] }
57
- }
58
- return null
59
- }
60
-
61
- const cut = cutFn(s, 'BangVangDiemDanh')
62
- if (!cut) { warn('KHONG THAY function BangVangDiemDanh — bo qua'); process.exit(0) }
63
- const oldFn = s.slice(cut[0], cut[1])
64
-
65
- /* Idempotent: neu da la ban V116c thi thoi */
66
- if (oldFn.includes('V116c: GIU NGUYEN canvas 1024x1180')) {
67
- ok('da la ban V116c (idem)')
68
- process.exit(0)
69
- }
70
- ok('se dung lai tu ban hien co (' + (oldFn.includes('setInterval') ? 'co polling' : 'khong polling') + ')')
71
-
72
- /* ---- position: DOC TU SOURCE HIEN TAI (patch_v82/v84 co the da doi that su)
73
- rotation: LUON dat lai -0.42 nhu patch_v83 goc (xem LOI C) ---- */
74
- const mPos = /<group\s+position=\{\[[^\]]*\]\}/.exec(oldFn)
75
- const POS_ATTR = mPos ? mPos[0].replace(/^<group\s+/, '') : 'position={[19, 6.2, -24]}'
76
- const OPEN_TAG = '<group ' + POS_ATTR + ' rotation={[0, -0.42, 0]}>'
77
- const mRot = /rotation=\{\[[^\]]*\]\}/.exec(oldFn)
78
- if (mRot && mRot[0] !== 'rotation={[0, -0.42, 0]}') {
79
- ok('khoi phuc rotation goc: ' + mRot[0] + ' -> rotation={[0, -0.42, 0]}')
80
- }
81
- ok('giu position hien tai: ' + POS_ATTR)
82
-
83
- const BOARD = `/* V116c: GIU NGUYEN canvas 1024x1180 + hinh hoc + rotation cua ban goc
84
- (patch_v83), chi THEM cot thu 4 "BINH CHON" va polling 60s nhu cu.
85
- Du lieu: /api/attendance/top (co "votes" tu V116). */
86
- function BangVangDiemDanh() {
87
- const [tex, setTex] = React.useState(null)
88
- React.useEffect(() => {
89
- let alive = true
90
- const c = document.createElement('canvas'); c.width = 1024; c.height = 1180
91
- const g = c.getContext('2d')
92
- const W = 1024, H = 1180
93
- const draw = (rows) => {
94
- if (!alive) return
95
- const gr = g.createLinearGradient(0, 0, 0, H)
96
- gr.addColorStop(0, '#2a1a08'); gr.addColorStop(.55, '#1a1004'); gr.addColorStop(1, '#0d0702')
97
- g.fillStyle = gr; g.fillRect(0, 0, W, H)
98
- g.strokeStyle = '#ecd08c'; g.lineWidth = 6; g.strokeRect(14, 14, W - 28, H - 28)
99
- g.fillStyle = '#ffd76a'; g.font = '900 46px Bitter, Georgia, serif'
100
- g.textAlign = 'center'; g.fillText('BẢNG VÀNG ĐIỂM DANH', W / 2, 78)
101
- g.fillStyle = 'rgba(200,225,255,.85)'; g.font = '600 23px "Be Vietnam Pro", sans-serif'
102
- g.fillText('Top 10 người siêng vào hang nhất', W / 2, 112)
103
- g.strokeStyle = 'rgba(236,208,140,.5)'; g.lineWidth = 2
104
- g.beginPath(); g.moveTo(40, 132); g.lineTo(W - 40, 132); g.stroke()
105
- /* V116: 4 cot — them "BINH CHON" ben phai "TIN NHAN" */
106
- g.fillStyle = 'rgba(236,208,140,.75)'; g.font = '700 22px "Be Vietnam Pro", sans-serif'
107
- g.textAlign = 'left'; g.fillText('#', 54, 164); g.fillText('TÊN', 116, 164)
108
- g.textAlign = 'right'
109
- g.fillText('LẦN VÀO', W - 330, 164)
110
- g.fillText('TIN NHẮN', W - 190, 164)
111
- g.fillStyle = 'rgba(143,220,255,.85)'
112
- g.fillText('BÌNH CHỌN', W - 54, 164)
113
- const arr = (rows || []).slice(0, 10)
114
- if (!arr.length) {
115
- g.fillStyle = 'rgba(255,240,200,.6)'; g.font = '600 26px "Be Vietnam Pro", sans-serif'
116
- g.textAlign = 'center'; g.fillText('Chưa có dữ liệu điểm danh', W / 2, H / 2)
117
- } else {
118
- const rowH = 90, top = 220
119
- arr.forEach((r, i) => {
120
- const y = top + i * rowH
121
- if (i === 0) {
122
- g.fillStyle = 'rgba(255,215,106,.16)'; g.fillRect(40, y - 36, W - 80, rowH - 8)
123
- g.strokeStyle = 'rgba(255,215,106,.8)'; g.lineWidth = 3
124
- g.strokeRect(40, y - 36, W - 80, rowH - 8)
125
- } else if (i % 2 === 0) {
126
- g.fillStyle = 'rgba(255,255,255,.05)'; g.fillRect(40, y - 36, W - 80, rowH - 8)
127
- }
128
- g.fillStyle = i === 0 ? '#ffd76a' : 'rgba(200,225,255,.92)'
129
- g.font = '800 30px "Be Vietnam Pro", sans-serif'; g.textAlign = 'left'
130
- g.fillText(String(i + 1), 54, y)
131
- g.fillStyle = '#fff6ec'; g.font = '700 27px "Be Vietnam Pro", sans-serif'
132
- g.fillText(String(r && r.name || 'Ẩn danh').slice(0, 24), 116, y)
133
- g.textAlign = 'right'
134
- g.fillStyle = i === 0 ? '#ffd76a' : 'rgba(255,240,200,.88)'
135
- g.font = '700 26px "Be Vietnam Pro", sans-serif'
136
- g.fillText(String(r && r.visits != null ? r.visits : 0), W - 330, y)
137
- g.fillStyle = 'rgba(200,225,255,.92)'
138
- g.fillText(String(r && r.chats != null ? r.chats : 0), W - 190, y)
139
- /* V116: cot binh chon */
140
- g.fillStyle = i === 0 ? '#bfe9ff' : 'rgba(143,220,255,.92)'
141
- g.fillText(String(r && r.votes != null ? r.votes : 0), W - 54, y)
142
- })
143
- }
144
- g.textAlign = 'right'; g.fillStyle = 'rgba(255,240,200,.45)'
145
- g.font = '500 21px "Be Vietnam Pro", sans-serif'
146
- g.fillText('Lần vào = số lần vào · Tin nhắn = số chat · Bình chọn = số lượt', W - 54, H - 30)
147
- const t = new THREE.CanvasTexture(c)
148
- t.colorSpace = THREE.SRGBColorSpace
149
- t.anisotropy = 4
150
- setTex(t)
151
- }
152
- draw([])
153
- /* V116c: POLLING 60s nhu ban goc patch_v83 (v116 lam mat tinh nang nay) */
154
- const pull = () => {
155
- fetch('/api/attendance/top', { cache: 'no-store' })
156
- .then((r) => r.ok ? r.json() : null)
157
- .then((d) => { if (alive && d) draw(d.top || []) })
158
- .catch(() => {})
159
- }
160
- pull()
161
- const iv = setInterval(pull, 60000)
162
- return () => { alive = false; clearInterval(iv) }
163
- }, [])
164
- if (!tex) return null
165
- return (
166
- ${OPEN_TAG}
167
- <mesh position={[0, 0, -0.08]}>
168
- <boxGeometry args={[8.0, 9.0, 0.28]} />
169
- <meshLambertMaterial color="#3d2a1a" flatShading />
170
- </mesh>
171
- <mesh position={[0, 0, 0.1]}>
172
- <planeGeometry args={[7.6, 8.6]} />
173
- <meshBasicMaterial map={tex} transparent toneMapped={false} fog={false} />
174
- </mesh>
175
- </group>
176
- )
177
- }`
178
-
179
- s = s.slice(0, cut[0]) + BOARD + s.slice(cut[1])
180
-
181
- /* ---- GUARD ---- */
182
- const bad = []
183
- if (!s.includes('V116c: GIU NGUYEN canvas 1024x1180')) bad.push('thieu marker V116c')
184
- if (!s.includes('setInterval(pull, 60000)')) bad.push('thieu polling 60s')
185
- if (!s.includes('clearInterval(iv)')) bad.push('thieu clearInterval (ro ri khi unmount)')
186
- if (!s.includes("g.fillText('BÌNH CHỌN', W - 54, 164)")) bad.push('thieu tieu de cot Binh chon')
187
- if (!s.includes('r.votes')) bad.push('thieu gia tri votes')
188
- if (!s.includes('c.width = 1024; c.height = 1180')) bad.push('sai kich thuoc canvas (phai 1024x1180)')
189
- if (!s.includes('boxGeometry args={[8.0, 9.0, 0.28]}')) bad.push('sai boxGeometry (phai 8.0x9.0)')
190
- if (!s.includes('planeGeometry args={[7.6, 8.6]}')) bad.push('sai planeGeometry (phai 7.6x8.6)')
191
- if (!s.includes(OPEN_TAG)) bad.push('mat opening tag cua bang (position/rotation)')
192
- if (!s.includes('rotation={[0, -0.42, 0]}')) bad.push('rotation khong phai -0.42 goc')
193
- if ((s.match(/function BangVangDiemDanh\(/g) || []).length !== 1) bad.push('BangVangDiemDanh != 1')
194
- if ((s.match(/function makeBannerTex\(/g) || []).length !== 1) bad.push('makeBannerTex != 1')
195
- if (bad.length) {
196
- warn('VALIDATE THAT BAI: ' + bad.join(' | '))
197
- fs.writeFileSync(F, BAK)
198
- warn('DA RESTORE cave3d.js')
199
- process.exit(0)
200
- }
201
-
202
- try {
203
- const esbuild = await import('esbuild')
204
- await esbuild.transform(s, { loader: 'jsx', format: 'esm', target: 'es2020' })
205
- ok('esbuild transform OK')
206
- } catch (e) {
207
- warn('JSX KHONG HOP LE: ' + String((e && e.message) || e).split('\n').slice(0, 3).join(' '))
208
- fs.writeFileSync(F, BAK)
209
- warn('DA RESTORE cave3d.js')
210
- process.exit(0)
211
- }
212
-
213
- fs.writeFileSync(F, s)
214
- ok('BangVangDiemDanh: canvas 1024x1180 + hinh hoc goc + rotation goc + cot "Binh chon" + polling 60s')
215
- console.log('[v116c] DONE: ' + n + ' muc')
216
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v116d.mjs DELETED
@@ -1,156 +0,0 @@
1
- /* patch_v116d.mjs — V116d + V116f
2
- =========================================================================
3
- V116f — SUA CRASH THAT (log runtime 23/11/2026):
4
- "Co loi xay ra" / "vaiLogoTex is not defined", bundle ?v=115.
5
-
6
- NGUYEN CHUOI (da xac nhan bang log):
7
- patch_v116.mjs CO top-level await (`const esbuild = await import(...)`),
8
- buoc 8 cua v116e validate bang target es2020 -> esbuild tu choi -> v116e
9
- restore BAN GOC patch_v116.mjs (anchor chet van con) -> v116 throw ->
10
- RESTORE CA 5 FILE (?v=115) -> patch_v116b VAN CHAY va chen
11
- {vaiLogoTex && (...)} + map={_v116NumTex(p.number)} vao — hai ten CHI do
12
- v116 dinh nghia => ReferenceError khi PlayerAvatar render => mat toan app.
13
-
14
- SUA O DAY (lop chan cuoi, doc lap voi viec v116 co chay hay khong):
15
- Neu app.js khong co function useVaiLogoTex( / _v116NumTex( thi vo hieu
16
- hoa tham chieu mo coi TRUOC khi ghi file.
17
-
18
- HAI LOI TU GAY RA o ban dau, da sua:
19
- a) Comment thay the chua dung chuoi 'vaiLogoTex' => guard
20
- /\bvaiLogoTex\b/ tu bat chinh no => tu choi ghi => crash VAN CON.
21
- b) map={_v115BackTex(p.number)} la MOT THAM CHIEU MO COI khac neu v115
22
- cung restore => phai kiem tra _v115BackTex co ton tai truoc khi dung.
23
-
24
- -------------------------------------------------------------------------
25
- V116d (giu nguyen) — sua LOI CAT HAM trong patch_v116:
26
- helper cutCallContaining() chon ung vien bang `if (j > ci)` => chon vi tri
27
- BAT DAU MUON NHAT trong ['React.useEffect','useEffect']. Voi
28
- 'React.useEffect(() => {' , lastIndexOf('useEffect(') tra ve vi tri CUA
29
- 'useEffect(' nam BEN TRONG 'React.useEffect(' — tre hon 6 ky tu. Doan bi
30
- cat bat dau tu 'useEffect(' nen 6 ky tu 'React.' bi BO SOT, ghep voi phan
31
- thay the ta duoc
32
- React. React.useEffect(() => { ... })
33
- Cu phap HOP LE nen esbuild khong bao loi, nhung luc chay React.React la
34
- undefined -> TypeError -> mat ca man hinh trong hang.
35
- Sua: gop 'React.' + khoang trang + 'React.useEffect(' (dung \s+).
36
- ========================================================================= */
37
- import fs from 'node:fs'
38
- import path from 'node:path'
39
-
40
- const ROOT = process.argv[2] || '.'
41
- const F = path.join(ROOT, 'frontend/app.js')
42
- if (!fs.existsSync(F)) { console.warn('[v116d] WARN: app.js missing — skip'); process.exit(0) }
43
-
44
- const BAK = fs.readFileSync(F, 'utf8')
45
- let s = BAK
46
- let n = 0
47
- const ok = (m) => { n++; console.log('[v116d] OK: ' + m) }
48
- const warn = (m) => console.warn('[v116d] WARN: ' + m)
49
-
50
- /* ============================================================
51
- V116f — chan tham chieu mo coi khi patch_v116 da RESTORE
52
- ============================================================ */
53
- const v116Applied = s.includes('function useVaiLogoTex(') && s.includes('function _v116NumTex(')
54
- if (!v116Applied) {
55
- warn('patch_v116 da RESTORE (khong thay useVaiLogoTex/_v116NumTex) — vo hieu hoa tham chieu mo coi cua v116b')
56
- let fixed = 0
57
-
58
- /* (1) khoi lung ao: vaiLogoTex khong ton tai -> false && ( ... )
59
- JSX element KHONG duoc tao vi && short-circuit, nen map= ben trong
60
- khong bao gio duoc danh gia.
61
- Comment thay the TUYET DOI khong duoc chua lai chuoi 'vaiLogoTex',
62
- neu khong guard ben duoi se bat chinh no va tu choi ghi file. */
63
- if (s.includes('{vaiLogoTex && (')) {
64
- s = s.split('{vaiLogoTex && (').join('{/* V116f: v116 restore => khong co tex poster */ false && (')
65
- fixed++
66
- }
67
- if (s.includes('map={vaiLogoTex}')) { s = s.split('map={vaiLogoTex}').join('map={null}'); fixed++ }
68
-
69
- /* (2) mieng so ao: _v116NumTex khong ton tai.
70
- Dung lai _v115BackTex cua v115 NEU v115 CO THAT (van hien so ao);
71
- neu v115 cung restore thi _v115BackTex cung khong ton tai — luc do
72
- phai dung map={null} (mesh trong suot) chu khong duoc tao them mot
73
- tham chieu mo coi nua. */
74
- if (s.includes('map={_v116NumTex(p.number)}')) {
75
- const hasV115Back = s.includes('function _v115BackTex(')
76
- s = s.split('map={_v116NumTex(p.number)}')
77
- .join(hasV115Back ? 'map={_v115BackTex(p.number)}' : 'map={null}')
78
- warn('so ao -> ' + (hasV115Back ? '_v115BackTex (v115 co)' : 'null (v115 cung restore)'))
79
- fixed++
80
- }
81
-
82
- /* Guard: khong con tham chieu nao toi ten do v116 dinh nghia */
83
- if (/\bvaiLogoTex\b/.test(s) || /_v116NumTex\s*\(/.test(s)) {
84
- warn('KHONG the vo hieu hoa het tham chieu mo coi — GIU NGUYEN app.js (khong ghi)')
85
- process.exit(0)
86
- }
87
- if (!fixed) {
88
- ok('khong co tham chieu mo coi — khong can sua')
89
- console.log('[v116d] DONE (no-op)')
90
- process.exit(0)
91
- }
92
- try {
93
- const esbuild = await import('esbuild')
94
- await esbuild.transform(s, { loader: 'jsx', format: 'esm', target: 'es2020' })
95
- ok('esbuild transform OK (sau khi vo hieu hoa ' + fixed + ' tham chieu mo coi)')
96
- } catch (e) {
97
- warn('JSX KHONG HOP LE sau khi sua: ' + String((e && e.message) || e).split('\n').slice(0, 3).join(' '))
98
- warn('GIU NGUYEN app.js (khong ghi de)')
99
- process.exit(0)
100
- }
101
- fs.writeFileSync(F, s)
102
- console.log('[v116d] DONE (orphan-neutralised): ' + n + ' muc — app khong con crash "vaiLogoTex is not defined"')
103
- process.exit(0)
104
- }
105
-
106
- /* ============================================================
107
- Duong binh thuong: patch_v116 DA ap dung -> chi sua 'React.'
108
- ============================================================ */
109
-
110
- /* Mau loi: 'React.' + khoang trang + 'React.useEffect(' (doan bi cat bo sot 'React.') */
111
- const BAD = /\bReact\.\s+(?=React\.useEffect\()/g
112
- const hits = (s.match(BAD) || []).length
113
-
114
- if (hits === 0) {
115
- ok('khong co mau loi "React. React.useEffect" (patch_v116 cat dung)')
116
- console.log('[v116d] DONE: ' + n + ' muc')
117
- process.exit(0)
118
- }
119
-
120
- warn('PHAT HIEN ' + hits + ' mau loi "React. React.useEffect" — doan cat cua v116 bo sot "React.", dang sua')
121
- s = s.replace(BAD, '')
122
-
123
- /* ---- GUARD ---- */
124
- const bad = []
125
- if (/\bReact\.\s+React\./.test(s)) bad.push('van con "React. React."')
126
- if (!s.includes('React.useEffect(() => {\n /* ===== V116: (4) VIDEO RANDOM')) {
127
- bad.push('hieu/khong tim thay dau effect V116 sau khi sua')
128
- }
129
- if (!s.includes('hangmu-ended')) bad.push('mat hangmu-ended')
130
- if (!s.includes('&loop=0')) bad.push('mat &loop=0')
131
- if (!s.includes('const [playIdx, setPlayIdx] = React.useState(-1)')) bad.push('mat playIdx')
132
- if (!s.includes('board-playbar-toggle')) bad.push('mat nut playlist')
133
- if (!s.includes('vaiLogoTex')) bad.push('mat vaiLogoTex')
134
- if ((s.match(/<group ref=\{rootRef\}/g) || []).length !== 1) bad.push('rootRef != 1 (nhan vat bi xoa!)')
135
- if (bad.length) {
136
- warn('VALIDATE THAT BAI: ' + bad.join(' | '))
137
- fs.writeFileSync(F, BAK)
138
- warn('DA RESTORE app.js')
139
- process.exit(0)
140
- }
141
-
142
- try {
143
- const esbuild = await import('esbuild')
144
- await esbuild.transform(s, { loader: 'jsx', format: 'esm', target: 'es2020' })
145
- ok('esbuild transform OK')
146
- } catch (e) {
147
- warn('JSX KHONG HOP LE: ' + String((e && e.message) || e).split('\n').slice(0, 3).join(' '))
148
- fs.writeFileSync(F, BAK)
149
- warn('DA RESTORE app.js')
150
- process.exit(0)
151
- }
152
-
153
- fs.writeFileSync(F, s)
154
- ok('gop "React. React.useEffect(" -> "React.useEffect(" (' + hits + ' cho)')
155
- console.log('[v116d] DONE: ' + n + ' muc')
156
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v116e.mjs DELETED
@@ -1,211 +0,0 @@
1
- /* patch_v116e.mjs — V116e: THE BUG THAT MADE ALL FIVE v116 GOALS VANISH,
2
- plus the follow-on breakages that fixing it alone would cause.
3
- =========================================================================
4
- V116f (23/11/2026, tu log runtime thuc te):
5
- Log that bao:
6
- Co loi xay ra | vaiLogoTex is not defined
7
- GET /static/app.bundle.js?v=115 <- v116 da RESTORE
8
- Nghia la v116e DA THAT BAI va tu restore. Nguyen nhan CHINH XAC:
9
-
10
- patch_v116.mjs CO top-level await:
11
- const esbuild = await import('esbuild') (trong khoi `if` o muc F,
12
- van la module scope)
13
- Buoc 8 cua v116e validate no bang:
14
- target: 'es2020'
15
- esbuild tu choi top-level await voi target < es2022 => nem loi =>
16
- v116e ghi lai BAN GOC patch_v116.mjs (anchor VaiSteleText CHET van con)
17
- => v116 throw => RESTORE 5 file => ?v=115 => v116b chen vaiLogoTex
18
- (khong ton tai) => CRASH toan app.
19
-
20
- SUA: target 'es2022'. Va buoc 8 gio CHI kiem tra CU PHAP: neu loi chi la
21
- top-level-await/ve target thi coi nhu DAT (khong restore).
22
-
23
- -------------------------------------------------------------------------
24
- Van de goc (giu nguyen mo ta):
25
- patch_v95.mjs inserts a block BEFORE `function HomeForecourt(` beginning
26
- const VAI_ROCK_POS = { ... }
27
- defining BOTH VaiSteleRock and
28
- function VaiSteleText({ width = 2.3 }) { ... } <- old name
29
-
30
- patch_v97.mjs then does
31
- const i0 = s.indexOf('const VAI_ROCK_POS =')
32
- const i1 = s.indexOf('function HomeForecourt(')
33
- s = s.slice(0, i0) + NEW + s.slice(i1)
34
- i.e. DISCARDS the region where v95's VaiSteleText lived; NEW defines only
35
- VaiSteleRockV2 and VaiSteleText2({ y, z, width })
36
-
37
- => After the chain, `function VaiSteleText(` DOES NOT EXIST.
38
- v116's cutFn(s,'VaiSteleText') = /function\s+VaiSteleText\s*\(/ cannot match
39
- 'VaiSteleText2(' -> null -> throw -> fatal -> RESTORE all 5 files, exit 0,
40
- GREEN build, Space keeps v115 behaviour.
41
-
42
- WHY REPOINTING THE CUT ALONE IS WORSE:
43
- v116's VT targets the v95 contract (fragment mounted as a CHILD of <mesh>);
44
- after v97 the contract is <mesh position={[0,y,z]}> mounted directly in
45
- <group>, with sites <VaiSteleText2 y={..} z={..} width={1.24} />.
46
- Cut-only => `VaiSteleText2` UNDEFINED at every mount site => home scene
47
- dies => strictly worse. So V116e moves FOUR things together: cut,
48
- VT signature, VT return shape, and v116's section-F guard.
49
- ========================================================================= */
50
- import fs from 'node:fs'
51
- import path from 'node:path'
52
-
53
- const ROOT = process.argv[2] || '.'
54
- const F = path.join(ROOT, 'patch_v116.mjs')
55
- if (!fs.existsSync(F)) { console.warn('[v116e] WARN: patch_v116.mjs missing — skip'); process.exit(0) }
56
-
57
- const BAK = fs.readFileSync(F, 'utf8')
58
- let s = BAK
59
- let n = 0
60
- const ok = (m) => { n++; console.log('[v116e] OK: ' + m) }
61
- const warn = (m) => console.warn('[v116e] WARN: ' + m)
62
-
63
- /* ============================================================
64
- 1) THE CUT — use the component name that exists after patch_v97
65
- ============================================================ */
66
- const OLD_CUT = "const cutV = cutFn(s, 'VaiSteleText')"
67
- const NEW_CUT = "const cutV = cutFn(s, 'VaiSteleText2')"
68
- if (s.includes(NEW_CUT)) ok('1) cutFn da tro VaiSteleText2 (idem)')
69
- else if (s.includes(OLD_CUT)) { s = s.split(OLD_CUT).join(NEW_CUT); ok('1) cutFn: VaiSteleText -> VaiSteleText2 (ANCHOR CHET da sua)') }
70
- else warn('1) KHONG THAY dong cutFn VaiSteleText — patch_v116 da bi sua khac?')
71
-
72
- /* ============================================================
73
- 2) VT SIGNATURE — must match v97's props (y, z, width)
74
- ============================================================ */
75
- const OLD_SIG = 'function VaiSteleText({ width = 2.3 }) {'
76
- const NEW_SIG = 'function VaiSteleText2({ y = 0.54, z = 0.35, width = 1.24 }) {'
77
- if (s.includes(NEW_SIG)) ok('2) VT da la VaiSteleText2({y,z,width}) (idem)')
78
- else if (s.includes(OLD_SIG)) { s = s.split(OLD_SIG).join(NEW_SIG); ok('2) VT signature -> VaiSteleText2({ y, z, width })') }
79
- else warn('2) KHONG THAY signature VT')
80
-
81
- /* ============================================================
82
- 3) VT RETURN — fragment (v95 contract) -> <mesh> (v97 contract)
83
- ============================================================ */
84
- const OLD_TAIL = [
85
- ' return (',
86
- ' <>',
87
- ' <planeGeometry args={[width, width * 0.1875]} />',
88
- ' <meshBasicMaterial map={tex} transparent depthWrite={false} toneMapped={false} />',
89
- ' </>',
90
- ' )',
91
- '}',
92
- ].join('\n')
93
- const NEW_TAIL = [
94
- ' return (',
95
- ' <mesh position={[0, y, z]}>',
96
- ' <planeGeometry args={[width, width * 0.1875]} />',
97
- ' <meshBasicMaterial map={tex} transparent depthWrite={false} toneMapped={false} />',
98
- ' </mesh>',
99
- ' )',
100
- '}',
101
- ].join('\n')
102
- if (s.includes(' <mesh position={[0, y, z]}>')) ok('3) VT tra ve <mesh position={[0,y,z]}> (idem)')
103
- else if (s.includes(OLD_TAIL)) { s = s.split(OLD_TAIL).join(NEW_TAIL); ok('3) VT return: fragment -> <mesh position={[0, y, z]}>') }
104
- else warn('3) KHONG THAY return fragment cua VT')
105
-
106
- /* ============================================================
107
- 4) v116 SECTION-F GUARD — it asserts the OLD name
108
- ============================================================ */
109
- const OLD_G = "if ((hom.match(/function VaiSteleText\\(/g) || []).length !== 1) bad.push('VaiSteleText != 1')"
110
- const NEW_G = "if ((hom.match(/function VaiSteleText2\\(/g) || []).length !== 1) bad.push('VaiSteleText2 != 1')"
111
- if (s.includes(NEW_G)) ok('4) guard section F dung VaiSteleText2 (idem)')
112
- else if (s.includes(OLD_G)) { s = s.split(OLD_G).join(NEW_G); ok('4) guard section F: VaiSteleText -> VaiSteleText2') }
113
- else warn('4) KHONG THAY guard VaiSteleText cua section F')
114
-
115
- /* ============================================================
116
- 5) the thrown message, so a future drift reports the right name
117
- ============================================================ */
118
- const OLD_ERR = "throw new Error('KHONG THAY function VaiSteleText (patch_v95 co the doi ten)')"
119
- const NEW_ERR = "throw new Error('KHONG THAY function VaiSteleText2 (patch_v97 xoa VaiSteleText va tao VaiSteleText2)')"
120
- if (s.includes(NEW_ERR)) ok('5) thong bao loi dung ten (idem)')
121
- else if (s.includes(OLD_ERR)) { s = s.split(OLD_ERR).join(NEW_ERR); ok('5) sua thong bao loi -> VaiSteleText2') }
122
- else warn('5) KHONG THAY thong bao loi cua cutV')
123
-
124
- /* ============================================================
125
- 6) comments that asserted the opposite of the truth
126
- ============================================================ */
127
- const hdrRe = /\(nguoi dung goi la "VaiSteleText2";[\s\S]*?chay TRUOC v116\.\)/
128
- const HDR_NEW = '(ten THAT trong cay nguon la VaiSteleText2: patch_v95 tao VaiSteleText, roi\n' +
129
- ' patch_v97 CAT doan [const VAI_ROCK_POS = .. function HomeForecourt(] va\n' +
130
- ' thay bang VaiSteleText2. V116e sua anchor cho dung ten nay — truoc do\n' +
131
- ' anchor tro VaiSteleText nen cutFn tra null va v116 RESTORE ca 5 file.)'
132
- if (s.includes('V116e sua anchor cho dung ten nay')) ok('6a) comment header da sua (idem)')
133
- else if (hdrRe.test(s)) { s = s.replace(hdrRe, HDR_NEW); ok('6a) sua comment header (v95/v97 thuc te)') }
134
- else warn('6a) KHONG THAY comment header')
135
-
136
- const lineRe = /- home3d VaiSteleText\(\)\s+: chu khac/
137
- if (s.includes('- home3d VaiSteleText2()')) ok('6b) dong tom tat da dung ten (idem)')
138
- else if (lineRe.test(s)) { s = s.replace(lineRe, '- home3d VaiSteleText2() : chu khac'); ok('6b) sua dong tom tat -> VaiSteleText2') }
139
- else warn('6b) KHONG THAY dong tom tat')
140
-
141
- const d3Re = /LUU Y: VaiSteleText KHONG co trong file home3d\.js trong repo[\s\S]*?khong sap\./
142
- const D3_NEW = 'LUU Y: sau patch_v95 (tao VaiSteleText) va patch_v97 (xoa VaiSteleText,\n' +
143
- ' thay bang VaiSteleText2) thi ten TON TAI trong cay nguon la\n' +
144
- ' VaiSteleText2. patch_v116e doi anchor + signature + return shape sang\n' +
145
- ' dung contract cua v97; neu v97 doi ten lan nua thi cutFn tra null va\n' +
146
- ' v116 restore, khong sap. Component nay POSITION chinh no (<mesh\n' +
147
- ' position={[0,y,z]}>) vi v97 mount no truc tiep trong <group>, khac\n' +
148
- ' v95 mount no lam con cua <mesh>.'
149
- if (s.includes('patch_v116e doi anchor + signature')) ok('6c) comment D3 da sua (idem)')
150
- else if (d3Re.test(s)) { s = s.replace(d3Re, D3_NEW); ok('6c) sua comment D3 (v95/v97 thuc te)') }
151
- else warn('6c) KHONG THAY comment D3')
152
-
153
- const vtRe = /Giu nguyen prop width va cach dung <VaiSteleText width=\{\.\.\.\} \/> —[\s\S]*?planeGeometry \+ meshBasicMaterial nhu ban cu\./
154
- const VT_NEW = 'Props theo dung contract cua patch_v97: { y, z, width }. Component\n' +
155
- ' POSITION chinh no bang <mesh position={[0, y, z]}> va tra ve mesh +\n' +
156
- ' planeGeometry + meshBasicMaterial, vi v97 mount <VaiSteleText2 ... /> truc\n' +
157
- ' tiep trong <group> (v95 thi mount no lam CON cua <mesh>).'
158
- if (s.includes('Props theo dung contract cua patch_v97')) ok('6d) comment VT da sua (idem)')
159
- else if (vtRe.test(s)) { s = s.replace(vtRe, VT_NEW); ok('6d) sua comment VT (contract v97)') }
160
- else warn('6d) KHONG THAY comment VT')
161
-
162
- /* ============================================================
163
- 7) GUARD — every piece of the fix must be present, and the old shape gone
164
- ============================================================ */
165
- const bad = []
166
- if (s.includes("cutFn(s, 'VaiSteleText')")) bad.push('van con cutFn VaiSteleText')
167
- if ((s.match(/cutFn\(s, 'VaiSteleText2'\)/g) || []).length !== 1) bad.push('cutFn VaiSteleText2 != 1 lan')
168
- if (!s.includes(NEW_SIG)) bad.push('thieu signature VaiSteleText2({ y, z, width })')
169
- if (s.includes(OLD_SIG)) bad.push('van con signature VaiSteleText({ width = 2.3 })')
170
- if (!s.includes(' <mesh position={[0, y, z]}>')) bad.push('VT chua tra ve <mesh position={[0,y,z]}>')
171
- if (s.includes(' <>\n <planeGeometry')) bad.push('VT van con return fragment')
172
- if (!s.includes(NEW_G)) bad.push('guard section F chua doi sang VaiSteleText2')
173
- if (bad.length) {
174
- warn('VALIDATE THAT BAI: ' + bad.join(' | ') + ' — RESTORE patch_v116.mjs')
175
- fs.writeFileSync(F, BAK)
176
- process.exit(0)
177
- }
178
-
179
- /* ============================================================
180
- 8) the patched patch file must still be valid JS
181
- ------------------------------------------------------------
182
- V116f: target es2020 KHONG chap nhan top-level await, ma patch_v116.mjs
183
- CO top-level await (`const esbuild = await import('esbuild')`). Voi
184
- es2020, esbuild nem loi => v116e tu restore => anchor chet song lai =>
185
- v116 restore => v116b crash "vaiLogoTex is not defined". Nay dung es2022.
186
- Them nua: neu loi CHI lien quan top-level-await/target thi coi nhu DAT,
187
- vi do khong phai loi cu phap that.
188
- ============================================================ */
189
- let valid = false
190
- try {
191
- const esbuild = await import('esbuild')
192
- await esbuild.transform(s, { loader: 'js', format: 'esm', target: 'es2022' })
193
- valid = true
194
- ok('8) esbuild transform OK (target es2022) — patch_v116.mjs van hop le')
195
- } catch (e) {
196
- const msg = String((e && e.message) || e)
197
- if (/top-level await|target/i.test(msg) && !/Unexpected|Expected/i.test(msg)) {
198
- valid = true
199
- warn('8) esbuild chi phan nan ve target/top-level await (' + msg.split('\n')[0] + ') — COI NHU DAT')
200
- } else {
201
- warn('8) patch_v116.mjs KHONG HOP LE: ' + msg.split('\n').slice(0, 3).join(' ') + ' — RESTORE')
202
- }
203
- }
204
- if (!valid) {
205
- fs.writeFileSync(F, BAK)
206
- process.exit(0)
207
- }
208
-
209
- fs.writeFileSync(F, s)
210
- console.log('[v116e] DONE: ' + n + ' muc — v116 se khong con tu RESTORE (cut + signature + return + guard)')
211
- process.exit(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v117.mjs DELETED
@@ -1,794 +0,0 @@
1
- /* V117 — 5 muc:
2
- 1. Video tu nhay bai: proxy gui 'listening' -> YT ban infoDelivery -> hangmu-ended
3
- app.js: nextTrack track index THAT qua ref (khong dung playIdx)
4
- 2. So ao TREN logo V.AI STUDIO (gop thanh 1 canvas texture)
5
- 3. Mat: to hon, mui/mieng dep hon
6
- 4. Man hinh YouTube bi cay che: raycast trong BoardProjector
7
- 5. Trang tri cay thong: backend + store + UI + 3D ornament meshes
8
- */
9
- import { readFileSync, writeFileSync } from 'fs'
10
-
11
- const F = 'frontend/app.js'
12
- const C = 'frontend/cave3d.js'
13
- const S = 'frontend/store.js'
14
- const B = 'backend.py'
15
- const V = 'video_proxy.py'
16
- const U = 'esbuild.config.mjs'
17
-
18
- function patch(file, name, fn) {
19
- let src = readFileSync(file, 'utf8')
20
- const before = src
21
- try {
22
- src = fn(src)
23
- } catch (e) {
24
- console.error(`V117 FAIL ${name}: ${e.message}`)
25
- writeFileSync(file, before)
26
- return
27
- }
28
- if (src === before) {
29
- console.error(`V117 WARN ${name}: NO CHANGE (anchor miss)`)
30
- return
31
- }
32
- writeFileSync(file, src)
33
- console.log(`V117 OK ${name}`)
34
- }
35
-
36
- /* ============ 1. video_proxy.py: 'listening' handshake ============ */
37
- patch(V, 'proxy-listening', (s) => {
38
- if (s.includes("event:'listening'") || s.includes('event: "listening"')) return s
39
- /* onReady: sau unMute, gui 'listening' -> YT IFrame API bat dau ban infoDelivery */
40
- const old = ` function onReady() {{`
41
- const neu = ` function sendListen() {{
42
- try {{
43
- if (player && player.contentWindow) {{
44
- player.contentWindow.postMessage(JSON.stringify({{event:'listening', id:'hangmu-proxy'}}), '*');
45
- }}
46
- }} catch (e) {{}}
47
- }}
48
- function onReady() {{`
49
- s = s.replace(old, neu)
50
- /* Trong onReady, sau unMute them sendListen */
51
- const old2 = ` player.contentWindow.postMessage(JSON.stringify({{event:'command', func:'unMute', args:[]}}), '*');
52
- }}
53
- }} catch (e) {{}}`
54
- const neu2 = ` player.contentWindow.postMessage(JSON.stringify({{event:'command', func:'unMute', args:[]}}), '*');
55
- }}
56
- sendListen();
57
- }} catch (e) {{}}`
58
- s = s.replace(old2, neu2)
59
- /* Cung goi sendListen sau load + interval nho (YT can nhan nhieu lan de bat dau) */
60
- const old3 = ` player.addEventListener('load', onReady);`
61
- const neu3 = ` player.addEventListener('load', onReady);
62
- // Gui 'listening' lap lai — YT IFrame API can nhan truoc khi ban su kien
63
- var listenIv = setInterval(sendListen, 2000);
64
- setTimeout(function() {{ clearInterval(listenIv); }}, 30000);`
65
- s = s.replace(old3, neu3)
66
- return s
67
- })
68
-
69
- /* ============ 2. app.js: fix nextTrack + _idx (index that) ============ */
70
- patch(F, 'video-index-fix', (s) => {
71
- /* Them ref de track index that. Dat ngay sau _idx. */
72
- const old = ` const _idx = playIdx < 0 ? Math.floor(Math.random() * useIds.length) : playIdx % useIds.length`
73
- const neu = ` const _idx = playIdx < 0 ? Math.floor(Math.random() * useIds.length) : playIdx % useIds.length
74
- /* V117: track index THAT de nextTrack dung — playIdx=-1 (random dau) lam
75
- cong thuc (c2<0?0:c2)+1 nhay sai (jump ve 1 thay vi tiep tuc). */
76
- _idxRef.current = _idx`
77
- s = s.replace(old, neu)
78
-
79
- /* nextTrack dung _idxRef thay vi playIdx */
80
- const old2 = ` const nextTrack = () => {
81
- if (cancelled || endedOnce) return
82
- endedOnce = true
83
- setPlayIdx((c2) => ((c2 < 0 ? 0 : c2) + 1) % useIds.length)
84
- }`
85
- const neu2 = ` const nextTrack = () => {
86
- if (cancelled || endedOnce) return
87
- endedOnce = true
88
- /* V117: index that tu ref — tiep tuc tu bai hien tai, khong jump sai. */
89
- const cur = _idxRef.current
90
- setPlayIdx(((cur < 0 ? 0 : cur) + 1) % useIds.length)
91
- }`
92
- s = s.replace(old2, neu2)
93
-
94
- /* Khai bao _idxRef o dau BoardVideoOverlay (sau idxRef) */
95
- const old3 = ` const idxRef = React.useRef(0)`
96
- const neu3 = ` const idxRef = React.useRef(0)
97
- const _idxRef = React.useRef(0)`
98
- s = s.replace(old3, neu3)
99
- return s
100
- })
101
-
102
- /* ============ 3. app.js: go logo + so ao thanh 1 texture ============ */
103
- patch(F, 'jersey-number-on-logo', (s) => {
104
- /* Bo 2 mesh rieng (logo + number), thay bang 1 mesh voi texture da gop.
105
- Ham _v116NumTex -> _v116JerseyTex(logo, number): ve logo + so len tren. */
106
- const old = ` {vaiLogoTex && (
107
- <mesh position={[0, 0.99, -0.306]} rotation-y={Math.PI}>
108
- <planeGeometry args={[0.36, 0.32]} />
109
- <meshBasicMaterial map={vaiLogoTex} transparent
110
- depthWrite={false} toneMapped={false} fog={false} />
111
- </mesh>
112
- )}
113
- {/* V116: SO AO — mieng RIENG 0.13x0.13 dat TRUOC mat poster (z -0.313 <
114
- -0.306) nen poster khong che so. Canvas nen TRONG SUOT. */}
115
- {p.number != null && String(p.number) !== '' && (
116
- <mesh position={[0, 0.885, -0.313]} rotation-y={Math.PI}>
117
- <planeGeometry args={[0.13, 0.13]} />
118
- <meshBasicMaterial map={_v116NumTex(p.number)} transparent
119
- depthWrite={false} toneMapped={false} fog={false} />
120
- </mesh>
121
- )}`
122
-
123
- const neu = ` {/* V117: LUNG AO = 1 TEXTURE DA GOP (logo V.AI STUDIO + so ao).
124
- Truoc: 2 mesh rieng (logo + so) => so nam DUOI logo, khong ph be.
125
- Nay: ve ca 2 len 1 canvas 0.36x0.32, so nam TREN logo goc phai.
126
- Guard vaiLogoTex: render khi map=null thi khong ve gi (ao giu mau). */}
127
- {vaiLogoTex && (
128
- <mesh position={[0, 0.99, -0.306]} rotation-y={Math.PI}>
129
- <planeGeometry args={[0.36, 0.32]} />
130
- <meshBasicMaterial map={_v116JerseyTex(vaiLogoTex, p.number)} transparent
131
- depthWrite={false} toneMapped={false} fog={false} />
132
- </mesh>
133
- )}`
134
-
135
- s = s.replace(old, neu)
136
-
137
- /* Them _v116JerseyTex ngay sau _v116NumTex (giu _v116NumTex de khong pha gi) */
138
- const anchor = `const _v116NumCache = {}`
139
- const func = `/* V117: go logo + so ao thanh 1 canvas. So ve TREN goc phai logo,
140
- chu to dieu got, nen doc duoc tren moi nen. Cache theo number. */
141
- const _v116JerseyCache = {}
142
- function _v116JerseyTex(logoTex, number) {
143
- const key = number == null ? 'none' : String(number)
144
- if (_v116JerseyCache[key]) return _v116JerseyCache[key]
145
- const c = document.createElement('canvas'); c.width = 512; c.height = 455
146
- const g = c.getContext('2d')
147
- g.clearRect(0, 0, 512, 455)
148
- /* Ve logo (1024x1024) vao canvas, giu ti le, dat o giua-tren */
149
- try {
150
- const img = logoTex.image || logoTex
151
- if (img && img.width) {
152
- const sz = 455
153
- g.drawImage(img, (512 - sz) / 2, 0, sz, sz)
154
- } else {
155
- /* Fallback: ve chu V.AI STUDIO */
156
- g.textAlign = 'center'; g.textBaseline = 'middle'
157
- g.strokeStyle = 'rgba(34,48,77,0.55)'; g.lineWidth = 6
158
- g.beginPath(); g.arc(256, 150, 90, 0, Math.PI * 2); g.stroke()
159
- g.fillStyle = '#fff'; g.font = '900 130px Bitter, Georgia, serif'
160
- g.fillText('V', 256, 155)
161
- g.font = '800 38px Bitter, Georgia, serif'
162
- g.fillText('STUDIO', 256, 250)
163
- }
164
- } catch (e) {}
165
- /* So ao — goc phai duoi, chu to, vien dam de doc tren moi nen */
166
- const label = String(number == null ? '' : number)
167
- if (label) {
168
- g.textAlign = 'center'; g.textBaseline = 'middle'
169
- g.font = '900 120px Arial, sans-serif'
170
- g.lineWidth = 14; g.strokeStyle = 'rgba(20,26,42,0.92)'
171
- g.strokeText(label, 256, 390)
172
- g.fillStyle = '#ffffff'
173
- g.fillText(label, 256, 390)
174
- }
175
- const t = new THREE.CanvasTexture(c)
176
- t.colorSpace = THREE.SRGBColorSpace
177
- t.anisotropy = 8; t.needsUpdate = true
178
- _v116JerseyCache[key] = t
179
- return t
180
- }
181
- const _v116NumCache = {}`
182
- s = s.replace(anchor, func)
183
- return s
184
- })
185
-
186
- /* ============ 4. app.js: face to hon, mui/mieng dep hon ============ */
187
- patch(F, 'face-improve', (s) => {
188
- /* Mat to hon: ellipse 13x15 -> 17x19, long den 7.4 -> 9.5, diem sang 3.2 -> 4.2 */
189
- s = s.replace(
190
- `g.beginPath(); g.ellipse(-30 + dx, ey, 13, 15, 0, 0, Math.PI * 2); g.fill()
191
- g.beginPath(); g.ellipse(30 + dx, ey, 13, 15, 0, 0, Math.PI * 2); g.fill()`,
192
- `g.beginPath(); g.ellipse(-30 + dx, ey, 17, 19, 0, 0, Math.PI * 2); g.fill()
193
- g.beginPath(); g.ellipse(30 + dx, ey, 17, 19, 0, 0, Math.PI * 2); g.fill()`
194
- )
195
- s = s.replace(
196
- `g.beginPath(); g.arc(-28 + dx, ey + 1, 7.4, 0, Math.PI * 2); g.fill()
197
- g.beginPath(); g.arc(32 + dx, ey + 1, 7.4, 0, Math.PI * 2); g.fill()`,
198
- `g.beginPath(); g.arc(-28 + dx, ey + 1, 9.5, 0, Math.PI * 2); g.fill()
199
- g.beginPath(); g.arc(32 + dx, ey + 1, 9.5, 0, Math.PI * 2); g.fill()`
200
- )
201
- s = s.replace(
202
- `g.beginPath(); g.arc(-30.8 + dx, ey - 2.4, 3.2, 0, Math.PI * 2); g.fill()
203
- g.beginPath(); g.arc(29.2 + dx, ey - 2.4, 3.2, 0, Math.PI * 2); g.fill()`,
204
- `g.beginPath(); g.arc(-30.8 + dx, ey - 2.4, 4.2, 0, Math.PI * 2); g.fill()
205
- g.beginPath(); g.arc(29.2 + dx, ey - 2.4, 4.2, 0, Math.PI * 2); g.fill()`
206
- )
207
- /* Mui dep hon: net cong muot + canh mui nhe */
208
- s = s.replace(
209
- `/* MUI — net cong nhe */
210
- g.strokeStyle = 'rgba(154,99,68,0.9)'; g.lineWidth = 5
211
- g.beginPath(); g.moveTo(0 + dx, ey + 6); g.quadraticCurveTo(8 + dx, ey + 20, -3 + dx, ey + 23); g.stroke()`,
212
- `/* MUI — than mui + canh mui nhe, muot hon */
213
- g.strokeStyle = 'rgba(154,99,68,0.85)'; g.lineWidth = 5
214
- g.beginPath(); g.moveTo(0 + dx, ey + 6); g.quadraticCurveTo(7 + dx, ey + 18, 1 + dx, ey + 22); g.stroke()
215
- g.strokeStyle = 'rgba(154,99,68,0.5)'; g.lineWidth = 3.5
216
- g.beginPath(); g.moveTo(-6 + dx, ey + 22); g.quadraticCurveTo(0 + dx, ey + 26, 6 + dx, ey + 22); g.stroke()`
217
- )
218
- /* Mieng dep hon: them khóe miệng + môi dưới khi happy */
219
- s = s.replace(
220
- `} else if (mood === 'happy') {
221
- g.beginPath(); g.arc(0 + dx, ey + 36, 23, 0.10 * Math.PI, 0.90 * Math.PI); g.stroke()`,
222
- `} else if (mood === 'happy') {
223
- g.beginPath(); g.arc(0 + dx, ey + 34, 24, 0.08 * Math.PI, 0.92 * Math.PI); g.stroke()
224
- /* Moi duoi nhe */
225
- g.strokeStyle = 'rgba(93,42,34,0.55)'; g.lineWidth = 4
226
- g.beginPath(); g.arc(0 + dx, ey + 38, 14, 0.20 * Math.PI, 0.80 * Math.PI); g.stroke()
227
- g.strokeStyle = ink; g.lineWidth = 8`
228
- )
229
- return s
230
- })
231
-
232
- /* ============ 5. cave3d.js: tag tree cones as 'tree-occluder' ============ */
233
- patch(C, 'tree-occluder-tag', (s) => {
234
- const old = ` {[0, 1, 2, 3, 4].map((i) => (
235
- <mesh key={i} position={[0, 1.5 + i * 2.5, 0]} castShadow>
236
- <coneGeometry args={[4.7 - i * 0.88, 3.3, 14]} />
237
- <meshLambertMaterial color={i % 2 ? '#1d5c33' : '#164a29'} flatShading />
238
- </mesh>
239
- ))}`
240
- const neu = ` {[0, 1, 2, 3, 4].map((i) => (
241
- <mesh key={i} name="tree-occluder" position={[0, 1.5 + i * 2.5, 0]} castShadow>
242
- <coneGeometry args={[4.7 - i * 0.88, 3.3, 14]} />
243
- <meshLambertMaterial color={i % 2 ? '#1d5c33' : '#164a29'} flatShading />
244
- </mesh>
245
- ))}`
246
- s = s.replace(old, neu)
247
- /* Danh dau cay de ChristmasDecorLayer biet vi tri (tree group position) */
248
- const old2 = ` {/* CAY THONG */}
249
- <group position={[0, pitY, 0]}>`
250
- const neu2 = ` {/* CAY THONG — name="christmas-tree" de layer trang tri raycast */}
251
- <group name="christmas-tree" position={[0, pitY, 0]}>`
252
- s = s.replace(old2, neu2)
253
- return s
254
- })
255
-
256
- /* ============ 6. app.js: BoardProjector raycast occlusion ============ */
257
- patch(F, 'board-occlusion', (s) => {
258
- /* V117: (4) sua loi man hinh YouTube hien TRUOC cay thong.
259
- BoardProjector raycast tu camera -> 4 goc board; neu cay (mesh
260
- name="tree-occluder") chan truoc => boardPx.ok = false => overlay an.
261
- Cung them ExposeScene de ChristmasDecorLayer lay scene/camera. */
262
- const oldBoard = `function BoardProjector() {
263
- const { camera, size } = useThree()
264
- const v = React.useMemo(() => [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()], [])
265
- useFrame(() => {
266
- const w = size.width, h = size.height
267
- const out = []
268
- let any = false
269
- let allFront = true
270
- for (let i = 0; i < 4; i++) {
271
- v[i].set(...BOARD_CORNERS[i]).project(camera)
272
- const z = v[i].z
273
- if (z < 1 && z > -1) any = true
274
- if (!(z < 1 && z > -1)) allFront = false
275
- out.push(((v[i].x * 0.5 + 0.5) * w) / 1, ((-v[i].y * 0.5 + 0.5) * h) / 1)
276
- }
277
- boardPx.pts = out
278
- boardPx.ok = any
279
- boardPx.allFront = allFront
280
- })
281
- return null
282
- }`;
283
-
284
- const newBoard = `/* V117: expose R3F scene/camera ra window de ChristmasDecorLayer raycast */
285
- function ExposeScene() {
286
- const { scene, camera } = useThree()
287
- React.useEffect(() => {
288
- window.__r3fScene = scene
289
- window.__r3fCamera = camera
290
- return () => { window.__r3fScene = null; window.__r3fCamera = null }
291
- }, [scene, camera])
292
- return null
293
- }
294
-
295
- function BoardProjector() {
296
- const { camera, size, scene } = useThree()
297
- const v = React.useMemo(() => [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()], [])
298
- const _ray = React.useRef(null)
299
- const _treeMeshes = React.useRef(null)
300
- React.useEffect(() => {
301
- _ray.current = new THREE.Raycaster()
302
- const meshes = []
303
- scene.traverse((o) => { if (o.isMesh && o.name === 'tree-occluder') meshes.push(o) })
304
- _treeMeshes.current = meshes
305
- }, [scene])
306
- useFrame(() => {
307
- const w = size.width, h = size.height
308
- const out = []
309
- let any = false
310
- let allFront = true
311
- const ray = _ray.current
312
- const treeMeshes = _treeMeshes.current
313
- for (let i = 0; i < 4; i++) {
314
- v[i].set(...BOARD_CORNERS[i]).project(camera)
315
- const z = v[i].z
316
- if (z < 1 && z > -1) any = true
317
- if (!(z < 1 && z > -1)) allFront = false
318
- out.push(((v[i].x * 0.5 + 0.5) * w) / 1, ((-v[i].y * 0.5 + 0.5) * h) / 1)
319
- }
320
- let occluded = false
321
- if (ray && treeMeshes && treeMeshes.length > 0) {
322
- const camPos = camera.position
323
- for (let i = 0; i < 4; i++) {
324
- const target = new THREE.Vector3(...BOARD_CORNERS[i])
325
- const dir = target.clone().sub(camPos)
326
- const dist = dir.length()
327
- if (dist < 0.1) continue
328
- dir.normalize()
329
- ray.set(camPos, dir)
330
- ray.far = dist - 0.5
331
- const hits = ray.intersectObjects(treeMeshes, false)
332
- if (hits.length > 0) { occluded = true; break }
333
- }
334
- }
335
- boardPx.pts = out
336
- boardPx.ok = any && !occluded
337
- boardPx.allFront = allFront
338
- })
339
- return null
340
- }`;
341
-
342
- if (!s.includes(oldBoard)) return s
343
- s = s.replace(oldBoard, newBoard)
344
-
345
- /* Mount ExposeScene trong Canvas — sau <CaveScene /> */
346
- const oldMount = ` <CaveScene />`
347
- const newMount = ` <CaveScene />
348
- <ExposeScene />`
349
- if (s.includes(oldMount) && !s.includes('<ExposeScene />')) {
350
- s = s.replace(oldMount, newMount)
351
- }
352
- return s
353
- })
354
-
355
- /* ============ 7. backend.py: christmas_decor handler ============ */
356
- patch(B, 'christmas-backend', (s) => {
357
- /* Them handler sau ping */
358
- const old = ` elif t == "ping":
359
- await send(ws, {"type": "pong", "t": msg.get("t", 0)})`
360
- const neu = ` elif t == "ping":
361
- await send(ws, {"type": "pong", "t": msg.get("t", 0)})
362
-
363
- elif t == "christmas_decor":
364
- # Trang tri cay thong — broadcast cho tat ca trong phong
365
- decor = {
366
- "type": "christmas_decor",
367
- "player_id": player_id,
368
- "kind": str(msg.get("kind", ""))[:20],
369
- "x": float(msg.get("x", 0)),
370
- "y": float(msg.get("y", 0)),
371
- "z": float(msg.get("z", 0)),
372
- "color": str(msg.get("color", "#e8262b"))[:20],
373
- }
374
- await broadcast(room_id, decor)
375
- # Gui lai cho nguoi gui de ho biet da nhan
376
- await send(ws, {"type": "christmas_ack", "seq": msg.get("seq", 0)})`
377
-
378
- s = s.replace(old, neu)
379
- return s
380
- })
381
-
382
- /* ============ 8. store.js: christmas subsystem ============ */
383
- patch(S, 'christmas-store', (s) => {
384
- /* Them makeChristmas sau makeRage */
385
- const old = `function makeRage() {
386
- const state = { active: false }
387
- const listeners = new Set()
388
- const emit = () => listeners.forEach((fn) => fn())
389
- return {
390
- get state() { return state },
391
- subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn) },
392
- getSnapshot() { return state },
393
- set(p) { Object.assign(state, p); emit() },
394
- }
395
- }`
396
-
397
- const neu = `function makeRage() {
398
- const state = { active: false }
399
- const listeners = new Set()
400
- const emit = () => listeners.forEach((fn) => fn())
401
- return {
402
- get state() { return state },
403
- subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn) },
404
- getSnapshot() { return state },
405
- set(p) { Object.assign(state, p); emit() },
406
- }
407
- }
408
- function makeChristmas() {
409
- /* ornaments: [{id, kind, x, y, z, color, by}] — vi tri trong toa do local cua cay */
410
- const state = { active: false, ornaments: [], selected: 'bauble', seq: 0 }
411
- const listeners = new Set()
412
- const emit = () => listeners.forEach((fn) => fn())
413
- return {
414
- get state() { return state },
415
- subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn) },
416
- getSnapshot() { return state },
417
- set(p) { Object.assign(state, p); emit() },
418
- addOrnament(o) {
419
- const id = (state.seq || 0) + 1
420
- state.seq = id
421
- state.ornaments = [...state.ornaments, { ...o, id }]
422
- emit()
423
- },
424
- }
425
- }`
426
- s = s.replace(old, neu)
427
-
428
- /* Them christmas vao store state */
429
- const old2 = ` rage: makeRage(),`
430
- const neu2 = ` rage: makeRage(),
431
- christmas: makeChristmas(),`
432
- s = s.replace(old2, neu2)
433
-
434
- /* Them useChristmas hook */
435
- const old3 = `export function useRage() { return useSyncStore(useGame((s) => s.rage)) }`
436
- const neu3 = `export function useRage() { return useSyncStore(useGame((s) => s.rage)) }
437
- export function useChristmas() { return useSyncStore(useGame((s) => s.christmas)) }`
438
- s = s.replace(old3, neu3)
439
-
440
- /* Them handler cho 'christmas_decor' va 'christmas_ack' trong handleServer */
441
- const old4 = ` case 'pong': break
442
- default: break`
443
- const neu4 = ` case 'pong': break
444
- case 'christmas_decor': {
445
- /* Nguoi khac vua trang tri — them vao cay cua minh */
446
- const ch = g.christmas
447
- ch.addOrnament({
448
- kind: data.kind,
449
- x: data.x, y: data.y, z: data.z,
450
- color: data.color,
451
- by: data.player_id,
452
- })
453
- break
454
- }
455
- case 'christmas_ack': {
456
- /* Xac nhan da gui — khong can lam gi */
457
- break
458
- }
459
- default: break`
460
- s = s.replace(old4, neu4)
461
- return s
462
- })
463
-
464
- /* ============ 9. app.js: ChristmasDecorLayer + mount ============ */
465
- patch(F, 'christmas-layer', (s) => {
466
- /* Them import useChristmas — tim dong import tu store.js, them useChristmas */
467
- {
468
- const m = s.match(/import \{([^}]+)\} from '\.\/store\.js'/)
469
- if (m && !m[1].includes('useChristmas')) {
470
- const newImp = `import {${m[1]}, useChristmas} from './store.js'`
471
- s = s.replace(m[0], newImp)
472
- console.log('V117 OK christmas-import: them useChristmas vao import')
473
- } else if (m && m[1].includes('useChristmas')) {
474
- console.log('V117 OK christmas-import (already present)')
475
- } else {
476
- console.log('V117 WARN christmas-import: khong tim thay import tu store.js')
477
- }
478
- }
479
-
480
- /* Them ChristmasDecorLayer ngay truoc RageLayer */
481
- const oldMount = ` <RageLayer touch={touch} />`
482
- const neuMount = ` <ChristmasDecorLayer touch={touch} />
483
- <RageLayer touch={touch} />`
484
- s = s.replace(oldMount, neuMount)
485
-
486
- /* Them component ChristmasDecorLayer ngay truoc function RageLayer */
487
- const oldFn = `const RAGE_DUMMY_POS = [`
488
- const neuFn = `/* V117: (5) TRANG TRI CAY THONG —
489
- - Khi nguoi choi den gan cay (r < 7 tu tam cay tai 0,0), hien nut "Trang tri"
490
- - Bam nut -> chon loai: bong tron / tat / keo / moki khoa nguoi tuyet
491
- - Chon vi tri tren cay bang cach bam vao man hinh (raycast vao tree-occluder)
492
- - Nguoi khac thay ornament duoc them vao cay (qua broadcast christmas_decor) */
493
- const XMAS_TREE_POS = { x: 0, z: 0 }
494
- const XMAS_RADIUS = 7
495
- const XMAS_KINDS = [
496
- { id: 'bauble', label: '🔴 Bống tròn', color: '#e8262b' },
497
- { id: 'stocking', label: '🧦 T���t', color: '#1f7a3d' },
498
- { id: 'candy', label: '🍬 Kẹo', color: '#ff6a5c' },
499
- { id: 'snowman', label: '⛄ Người tuyết', color: '#f2f2f2' },
500
- ]
501
- function ChristmasDecorLayer({ touch }) {
502
- const ch = useChristmas()
503
- const players = useGame((s) => s.players)
504
- const playerId = useGame((s) => s.playerId)
505
- const me = players.get(playerId)
506
- const [near, setNear] = React.useState(false)
507
- const active = ch.active
508
-
509
- /* Kiem tra khoang cach toi cay */
510
- React.useEffect(() => {
511
- if (active) return
512
- const id = setInterval(() => {
513
- if (!me || !me.pos) return
514
- const dx = me.pos.x - XMAS_TREE_POS.x, dz = me.pos.z - XMAS_TREE_POS.z
515
- setNear(dx * dx + dz * dz < XMAS_RADIUS * XMAS_RADIUS)
516
- }, 500)
517
- return () => clearInterval(id)
518
- }, [active, me && me.pos && me.pos.x, me && me.pos && me.pos.z])
519
-
520
- /* Phim tat: E de mo/dong (khi gan cay), Esc de dong */
521
- React.useEffect(() => {
522
- const down = (e) => {
523
- if (e.code === 'KeyE' && near && !active) {
524
- ch.set({ active: true })
525
- }
526
- if (e.code === 'Escape' && active) {
527
- ch.set({ active: false })
528
- }
529
- }
530
- window.addEventListener('keydown', down)
531
- return () => window.removeEventListener('keydown', down)
532
- }, [near, active])
533
-
534
- /* Khi active: raycast vao tree-occluder de biet vi tri bam */
535
- const handleClick = React.useCallback((ev) => {
536
- if (!active) return
537
- /* Lay toa do tree group tu scene — qua window.__xmasTreeRef */
538
- const treeGroup = window.__xmasTreeRef
539
- if (!treeGroup) return
540
- const canvas = document.querySelector('#cave-canvas-wrap canvas')
541
- if (!canvas) return
542
- const rect = canvas.getBoundingClientRect()
543
- const nx = ((ev.clientX - rect.left) / rect.width) * 2 - 1
544
- const ny = -((ev.clientY - rect.top) / rect.height) * 2 + 1
545
- /* Dung THREE.Raycaster tu scene cua R3F — lay qua window.__r3fScene */
546
- const scene = window.__r3fScene
547
- const camera = window.__r3fCamera
548
- if (!scene || !camera || !THREE.Raycaster) return
549
- const ray = new THREE.Raycaster()
550
- ray.setFromCamera({ x: nx, y: ny }, camera)
551
- const treeMeshes = []
552
- scene.traverse((o) => { if (o.isMesh && o.name === 'tree-occluder') treeMeshes.push(o) })
553
- const hits = ray.intersectObjects(treeMeshes, false)
554
- if (hits.length === 0) return
555
- /* Chuyen diem hit sang toa do local cua tree group */
556
- const pt = hits[0].point
557
- const local = treeGroup.worldToLocal(pt.clone())
558
- const kind = ch.selected || 'bauble'
559
- const kindInfo = XMAS_KINDS.find((k) => k.id === kind) || XMAS_KINDS[0]
560
- /* Them vao store + gui len backend */
561
- ch.addOrnament({ kind, x: local.x, y: local.y, z: local.z, color: kindInfo.color, by: playerId })
562
- Net.send({ type: 'christmas_decor', kind, x: local.x, y: local.y, z: local.z, color: kindInfo.color, seq: Date.now() })
563
- }, [active, ch, playerId])
564
-
565
- /* Bind click khi active */
566
- React.useEffect(() => {
567
- if (!active) return
568
- const canvas = document.querySelector('#cave-canvas-wrap canvas')
569
- if (!canvas) return
570
- canvas.addEventListener('click', handleClick)
571
- return () => canvas.removeEventListener('click', handleClick)
572
- }, [active, handleClick])
573
-
574
- /* Expose scene/camera cho handleClick */
575
- React.useEffect(() => {
576
- const canvas = document.querySelector('#cave-canvas-wrap canvas')
577
- if (!canvas) return
578
- /* R3F expose qua canvas.__r3f — khong co thi dung window fallback */
579
- try {
580
- const r3f = canvas.__r3f || canvas.parentElement?.__r3f
581
- if (r3f) {
582
- window.__r3fScene = r3f.root?.getState?.().scene
583
- window.__r3fCamera = r3f.root?.getState?.().camera
584
- }
585
- } catch (e) {}
586
- }, [])
587
-
588
- if (!active && !near) return null
589
-
590
- /* Prompt khi gan cay */
591
- if (!active && near) {
592
- return (
593
- <div style={{ position: 'fixed', bottom: 120, left: '50%', transform: 'translateX(-50%)', zIndex: 9999, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, pointerEvents: 'auto' }}>
594
- <button type="button" onClick={() => ch.set({ active: true })}
595
- style={{ background: 'linear-gradient(180deg,#1f7a3d,#0d4a1d)', color: '#fff', border: '2px solid #ffd76a', borderRadius: 999, padding: '10px 22px', fontSize: 15, fontWeight: 800, cursor: 'pointer', boxShadow: '0 4px 14px #000a' }}>
596
- 🎄 Trang trí cây thông
597
- </button>
598
- {!touch && <span style={{ fontSize: 12, color: '#fff6ec', background: 'rgba(0,0,0,0.6)', padding: '3px 10px', borderRadius: 8 }}>hoặc nhấn <kbd>E</kbd></span>}
599
- </div>
600
- )
601
- }
602
-
603
- /* Panel chon loai + huong dan */
604
- return (
605
- <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 9999, pointerEvents: 'none' }}>
606
- {/* Panel chon loai — goc tren phai */}
607
- <div style={{ position: 'absolute', top: 70, right: 16, width: 220, background: 'rgba(12,8,6,0.92)', border: '1px solid #ecd08c66', borderRadius: 14, padding: 14, pointerEvents: 'auto', boxShadow: '0 6px 20px #000a' }}>
608
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
609
- <h3 style={{ margin: 0, fontSize: 15, color: '#ffd76a', fontWeight: 800 }}>🎄 Trang trí</h3>
610
- <button type="button" onClick={() => ch.set({ active: false })}
611
- style={{ background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)', borderRadius: 8, padding: '3px 9px', color: '#fff', fontSize: 13, cursor: 'pointer' }}>✕</button>
612
- </div>
613
- <p style={{ margin: '0 0 10px', fontSize: 12, color: '#c8b89a' }}>Chọn loại, rồi bấm vào cây để đặt:</p>
614
- <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
615
- {XMAS_KINDS.map((k) => (
616
- <button key={k.id} type="button"
617
- onClick={() => ch.set({ selected: k.id })}
618
- style={{ textAlign: 'left', padding: '8px 10px', borderRadius: 9, border: ch.selected === k.id ? '2px solid #ffd76a' : '1px solid rgba(255,255,255,0.15)', background: ch.selected === k.id ? 'rgba(255,215,106,0.15)' : 'rgba(255,255,255,0.05)', color: '#fff', fontSize: 13, cursor: 'pointer', fontWeight: ch.selected === k.id ? 700 : 400 }}>
619
- {k.label}
620
- </button>
621
- ))}
622
- </div>
623
- <p style={{ margin: '10px 0 0', fontSize: 11, color: '#8a7a5c', fontStyle: 'italic' }}>Bấm vào cây để đặt · Esc để đóng</p>
624
- </div>
625
- {/* Huong dan giua man hinh */}
626
- <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%)', pointerEvents: 'none', textAlign: 'center' }}>
627
- <div style={{ display: 'inline-block', background: 'rgba(0,0,0,0.55)', color: '#ffd76a', padding: '8px 18px', borderRadius: 12, fontSize: 14, fontWeight: 700 }}>
628
- 🖱️ Bấm vào cây thông để đặt {XMAS_KINDS.find(k => k.id === (ch.selected || 'bauble'))?.label || 'bống tròn'}
629
- </div>
630
- </div>
631
- </div>
632
- )
633
- }
634
-
635
- const RAGE_DUMMY_POS = [`
636
- s = s.replace(oldFn, neuFn)
637
- return s
638
- })
639
-
640
- /* ============ 10. cave3d.js: expose tree group + scene/camera + ornament meshes ============ */
641
- patch(C, 'xmas-ornaments', (s) => {
642
- /* Expose tree group ref ra window de ChristmasDecorLayer raycast */
643
- const old = ` const treeRef = useRef(null)`
644
- const neu = ` const treeRef = useRef(null)
645
- const _outerTreeRef = useRef(null)
646
- React.useEffect(() => { window.__xmasTreeRef = _outerTreeRef.current }, [])`
647
- s = s.replace(old, neu)
648
-
649
- /* Gan ref vao outer group cua cay */
650
- const old2 = ` <group name="christmas-tree" position={[0, pitY, 0]}>`
651
- const neu2 = ` <group name="christmas-tree" ref={_outerTreeRef} position={[0, pitY, 0]}>`
652
- s = s.replace(old2, neu2)
653
-
654
- /* Them ornament meshes sau socks */
655
- const old3 = ` {socks.map((k, i) => (
656
- <group key={'s' + i} position={[k.x, k.y, k.z]}>
657
- <mesh>
658
- <boxGeometry args={[0.3, 0.46, 0.08]} />
659
- <meshStandardMaterial color={i % 2 ? '#e8262b' : '#f2f2f2'} roughness={0.85} />
660
- </mesh>
661
- <mesh position={[0, -0.27, 0.03]}>
662
- <boxGeometry args={[0.3, 0.15, 0.15]} />
663
- <meshStandardMaterial color={i % 2 ? '#e8262b' : '#f2f2f2'} roughness={0.85} />
664
- </mesh>
665
- </group>
666
- ))}`
667
-
668
- const neu3 = ` {socks.map((k, i) => (
669
- <group key={'s' + i} position={[k.x, k.y, k.z]}>
670
- <mesh>
671
- <boxGeometry args={[0.3, 0.46, 0.08]} />
672
- <meshStandardMaterial color={i % 2 ? '#e8262b' : '#f2f2f2'} roughness={0.85} />
673
- </mesh>
674
- <mesh position={[0, -0.27, 0.03]}>
675
- <boxGeometry args={[0.3, 0.15, 0.15]} />
676
- <meshStandardMaterial color={i % 2 ? '#e8262b' : '#f2f2f2'} roughness={0.85} />
677
- </mesh>
678
- </group>
679
- ))}
680
- {/* V117: (5) ORNAMENT DO NGUOI CHOI DAT — doc tu store christmas */}
681
- {xmasOrnaments.map((o, i) => (
682
- <XmasOrnament key={i} ornament={o} />
683
- ))}`
684
-
685
- s = s.replace(old3, neu3)
686
-
687
- /* Them hook doc ornaments vao ChristmasGrove */
688
- const old4 = `function ChristmasGrove() {
689
- const pitY = -CAVE.pitDepth`
690
- const neu4 = `function ChristmasGrove() {
691
- const pitY = -CAVE.pitDepth
692
- const xmasStore = useGame((s) => s.christmas)
693
- const xmasOrnaments = xmasStore ? (xmasStore.ornaments || []) : []`
694
- s = s.replace(old4, neu4)
695
-
696
- /* Them component XmasOrnament truoc ChristmasGrove */
697
- const old5 = `function ChristmasGrove() {`
698
- const neu5 = `/* V117: (5) MOT ORNAMENT — render theo kind */
699
- function XmasOrnament({ ornament }) {
700
- const o = ornament
701
- if (!o) return null
702
- const pos = [o.x, o.y, o.z]
703
- if (o.kind === 'stocking') {
704
- /* Tat: hop dai + chan */
705
- return (
706
- <group position={pos}>
707
- <mesh>
708
- <boxGeometry args={[0.3, 0.46, 0.08]} />
709
- <meshStandardMaterial color={o.color || '#1f7a3d'} roughness={0.85} />
710
- </mesh>
711
- <mesh position={[0, -0.27, 0.03]}>
712
- <boxGeometry args={[0.3, 0.15, 0.15]} />
713
- <meshStandardMaterial color={o.color || '#1f7a3d'} roughness={0.85} />
714
- </mesh>
715
- </group>
716
- )
717
- }
718
- if (o.kind === 'candy') {
719
- /* Keo: vien dieu + than */
720
- return (
721
- <group position={pos}>
722
- <mesh>
723
- <cylinderGeometry args={[0.06, 0.06, 0.4, 8]} />
724
- <meshStandardMaterial color={o.color || '#ff6a5c'} roughness={0.6} />
725
- </mesh>
726
- <mesh position={[0, 0.2, 0]}>
727
- <sphereGeometry args={[0.1, 10, 8]} />
728
- <meshStandardMaterial color={o.color || '#ff6a5c'} roughness={0.4} />
729
- </mesh>
730
- <mesh position={[0, -0.2, 0]}>
731
- <sphereGeometry args={[0.1, 10, 8]} />
732
- <meshStandardMaterial color={o.color || '#ff6a5c'} roughness={0.4} />
733
- </mesh>
734
- </group>
735
- )
736
- }
737
- if (o.kind === 'snowman') {
738
- /* Moc khoa nguoi tuyet: 2 cau + mui + mat */
739
- return (
740
- <group position={pos} scale={0.5}>
741
- <mesh position={[0, 0.15, 0]}>
742
- <sphereGeometry args={[0.3, 12, 10]} />
743
- <meshStandardMaterial color="#f4f7fb" roughness={0.85} />
744
- </mesh>
745
- <mesh position={[0, 0.55, 0]}>
746
- <sphereGeometry args={[0.2, 12, 10]} />
747
- <meshStandardMaterial color="#f4f7fb" roughness={0.85} />
748
- </mesh>
749
- <mesh position={[0, 0.55, 0.18]}>
750
- <coneGeometry args={[0.06, 0.15, 8]} />
751
- <meshStandardMaterial color="#ff8c00" roughness={0.6} />
752
- </mesh>
753
- <mesh position={[-0.08, 0.6, 0.16]}>
754
- <sphereGeometry args={[0.03, 6, 6]} />
755
- <meshBasicMaterial color="#20150c" />
756
- </mesh>
757
- <mesh position={[0.08, 0.6, 0.16]}>
758
- <sphereGeometry args={[0.03, 6, 6]} />
759
- <meshBasicMaterial color="#20150c" />
760
- </mesh>
761
- </group>
762
- )
763
- }
764
- /* Default: bong tron (bauble) */
765
- return (
766
- <mesh position={pos}>
767
- <sphereGeometry args={[0.18, 12, 10]} />
768
- <meshStandardMaterial color={o.color || '#e8262b'} metalness={0.55} roughness={0.22} />
769
- </mesh>
770
- )
771
- }
772
-
773
- function ChristmasGrove() {`
774
- s = s.replace(old5, neu5)
775
- return s
776
- })
777
-
778
- /* ============ 11. esbuild.config.mjs: bump version ============ */
779
- /* V117: bump VERSION_ID trong backend.py (khong phai esbuild.config.mjs) */
780
- {
781
- const BF = 'backend.py'
782
- let bs = readFileSync(BF, 'utf8')
783
- if (bs.includes('VERSION_ID = "v117"')) {
784
- console.log('V117 OK version-bump (already v117)')
785
- } else if (bs.includes('VERSION_ID = "v116"')) {
786
- bs = bs.replace('VERSION_ID = "v116"', 'VERSION_ID = "v117"')
787
- writeFileSync(BF, bs)
788
- console.log('V117 OK version-bump -> v117')
789
- } else {
790
- console.log('V117 WARN version-bump: VERSION_ID khong tim thay')
791
- }
792
- }
793
-
794
- console.log('V117 DONE: 11 muc — video next, jersey number, face, occlusion, christmas decor')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
patch_v118.mjs DELETED
@@ -1,460 +0,0 @@
1
- /* patch_v118.mjs — V118. Chay TRONG Docker build, SAU patch_v117.mjs, TRUOC esbuild.
2
- 1. So ao: chuyen tu y=390 (duoi cung) len y=228 (giua logo V.AI STUDIO).
3
- 2. Bang huong dan: them bang "CAY THONG TRANG TRI →" gan cay thong.
4
- 3. Fix trang tri: thay raycast click bang modal scene (cay thong rieng + chon qua).
5
- 4. Backend: xoa duplicate christmas_decor handler, them _att_bump 'decor',
6
- them 'decor' vao _att_score + /api/attendance/top.
7
- 5. BangVangDiemDanh: them cot "TRANG TRI".
8
- */
9
- import { readFileSync, writeFileSync } from 'fs'
10
-
11
- let n = 0
12
- const ok = (m) => { n++; console.log('[v118] OK: ' + m) }
13
- const warn = (m) => console.warn('[v118] WARN: ' + m)
14
-
15
- function patch(file, name, fn) {
16
- const s = readFileSync(file, 'utf8')
17
- const out = fn(s)
18
- if (out && out !== s) {
19
- writeFileSync(file, out)
20
- ok(name)
21
- } else {
22
- warn(name + ': NO CHANGE')
23
- }
24
- }
25
-
26
- /* ============ 1. app.js: so ao len tren logo V.AI STUDIO ============ */
27
- const F = 'frontend/app.js'
28
-
29
- patch(F, 'jersey-number-position', (s) => {
30
- /* So ao hien tai o y=390 (duoi cung canvas). Chuyen len y=228 (giua logo). */
31
- const old = "g.strokeText(label, 256, 390)"
32
- const neu = "g.strokeText(label, 256, 228)"
33
- if (!s.includes(old)) return s
34
- s = s.replace(old, neu)
35
- s = s.replace("g.fillText(label, 256, 390)", "g.fillText(label, 256, 228)")
36
- return s
37
- })
38
-
39
- /* ============ 2. app.js: bang huong dan den cay thong ============ */
40
- patch(F, 'direction-board', (s) => {
41
- /* Them component BangHuongDanCayThong — hien thi khi player o xa cay (< 15) */
42
- const oldFn = 'function ChristmasDecorLayer({ touch }) {'
43
- const newFn = `/* V118: Bang huong dan den cay thong — hien khi player o xa cay */
44
- function BangHuongDanCayThong() {
45
- const players = useGame((s) => s.players)
46
- const playerId = useGame((s) => s.playerId)
47
- const me = players.get(playerId)
48
- const [dist, setDist] = React.useState(999)
49
- React.useEffect(() => {
50
- const id = setInterval(() => {
51
- if (!me || !me.pos) return
52
- const dx = me.pos.x - XMAS_TREE_POS.x, dz = me.pos.z - XMAS_TREE_POS.z
53
- setDist(Math.sqrt(dx * dx + dz * dz))
54
- }, 800)
55
- return () => clearInterval(id)
56
- }, [me && me.pos && me.pos.x, me && me.pos && me.pos.z])
57
- /* Hien khi o xa cay (dist > 7) nhung chua qua xa (dist < 25) */
58
- if (dist <= XMAS_RADIUS || dist > 25) return null
59
- const dir = dist < 12 ? 'đi thẳng' : 'đi vào giữa hang'
60
- return (
61
- <div style={{ position: 'fixed', bottom: 180, left: '50%', transform: 'translateX(-50%)', zIndex: 9998, pointerEvents: 'auto', textAlign: 'center' }}>
62
- <div style={{ background: 'linear-gradient(180deg, rgba(20,40,20,0.92), rgba(10,25,10,0.92))', border: '2px solid #2d8a4e', borderRadius: 14, padding: '12px 22px', boxShadow: '0 6px 20px #000a', maxWidth: 360 }}>
63
- <div style={{ fontSize: 16, fontWeight: 800, color: '#7ddf9a', marginBottom: 4 }}>🎄 Cây thông trang trí</div>
64
- <div style={{ fontSize: 13, color: '#c8e8d0', lineHeight: 1.5 }}>
65
- {dir} đến cây thông ở giữa hang<br />
66
- <span style={{ color: '#ffd76a', fontWeight: 700 }}>còn ~{Math.ceil(dist)}m</span> · Nhấn <kbd>E</kbd> khi đến gần
67
- </div>
68
- </div>
69
- </div>
70
- )
71
- }
72
-
73
- function ChristmasDecorLayer({ touch }) {`
74
- if (!s.includes(oldFn)) return s
75
- s = s.replace(oldFn, newFn)
76
-
77
- /* Mount BangHuongDanCayThong truoc ChristmasDecorLayer */
78
- const oldMount = ' <ChristmasDecorLayer touch={touch} />'
79
- const neuMount = ' <BangHuongDanCayThong />\n <ChristmasDecorLayer touch={touch} />'
80
- if (s.includes(oldMount)) {
81
- s = s.replace(oldMount, neuMount)
82
- }
83
- return s
84
- })
85
-
86
- /* ============ 3. app.js: thay ChristmasDecorLayer bang modal scene ============ */
87
- patch(F, 'christmas-modal-scene', (s) => {
88
- /* Thay toan bo ChristmasDecorLayer: khi active, hien modal voi cay thong rieng
89
- (khong raycast vao scene chinh), cham vao cay de dat ornament.
90
- Modal co canvas 2D don gian — ve cay thong SVG-like, cham vao vi tri de dat. */
91
- const oldStart = 'function ChristmasDecorLayer({ touch }) {'
92
- const oldEnd = '/* Expose R3F scene/camera'
93
- const startIdx = s.indexOf(oldStart)
94
- if (startIdx === -1) return s
95
- /* Tim function RageLayer de biet noi dung cu ket thuc o dau */
96
- const rageIdx = s.indexOf('function RageLayer(', startIdx)
97
- if (rageIdx === -1) return s
98
- /* Tim function tiep theo sau ChristmasDecorLayer */
99
- const nextFn = s.indexOf('function ', startIdx + oldStart.length)
100
- if (nextFn === -1) return s
101
-
102
- /* Lay doan cu */
103
- const oldBlock = s.slice(startIdx, nextFn)
104
-
105
- const newBlock = `function ChristmasDecorLayer({ touch }) {
106
- const ch = useChristmas()
107
- const players = useGame((s) => s.players)
108
- const playerId = useGame((s) => s.playerId)
109
- const me = players.get(playerId)
110
- const [near, setNear] = React.useState(false)
111
- const active = ch.active
112
-
113
- /* Kiem tra khoang cach toi cay */
114
- React.useEffect(() => {
115
- if (active) return
116
- const id = setInterval(() => {
117
- if (!me || !me.pos) return
118
- const dx = me.pos.x - XMAS_TREE_POS.x, dz = me.pos.z - XMAS_TREE_POS.z
119
- setNear(dx * dx + dz * dz < XMAS_RADIUS * XMAS_RADIUS)
120
- }, 500)
121
- return () => clearInterval(id)
122
- }, [active, me && me.pos && me.pos.x, me && me.pos && me.pos.z])
123
-
124
- /* Phim tat: E de mo/dong (khi gan cay), Esc de dong */
125
- React.useEffect(() => {
126
- const down = (e) => {
127
- if (e.code === 'KeyE' && near && !active) {
128
- ch.set({ active: true })
129
- }
130
- if (e.code === 'Escape' && active) {
131
- ch.set({ active: false })
132
- }
133
- }
134
- window.addEventListener('keydown', down)
135
- return () => window.removeEventListener('keydown', down)
136
- }, [near, active])
137
-
138
- /* Modal canvas 2D — ve cay thong + ornament, cham de dat */
139
- const _canvasRef = React.useRef(null)
140
- const [modalOrnaments, setModalOrnaments] = React.useState([])
141
-
142
- /* Ve modal canvas khi active */
143
- React.useEffect(() => {
144
- if (!active || !_canvasRef.current) return
145
- const c = _canvasRef.current
146
- const g = c.getContext('2d')
147
- const W = c.width, H = c.height
148
- const draw = () => {
149
- /* Background */
150
- const gr = g.createLinearGradient(0, 0, 0, H)
151
- gr.addColorStop(0, '#0a1528'); gr.addColorStop(0.5, '#0d2818'); gr.addColorStop(1, '#0a1528')
152
- g.fillStyle = gr; g.fillRect(0, 0, W, H)
153
- /* Cay thong — tam giac lap */
154
- const cx = W / 2, baseY = H - 80, topY = 60
155
- /* Than cay */
156
- g.fillStyle = '#4a3220'
157
- g.fillRect(cx - 12, baseY - 10, 24, 40)
158
- /* 3 tang la */
159
- const layers = [
160
- { y: topY + 20, w: 120, h: 120 },
161
- { y: topY + 90, w: 160, h: 140 },
162
- { y: topY + 160, w: 200, h: 160 },
163
- ]
164
- for (const L of layers) {
165
- g.fillStyle = '#1d5c33'
166
- g.beginPath()
167
- g.moveTo(cx, L.y)
168
- g.lineTo(cx - L.w / 2, L.y + L.h)
169
- g.lineTo(cx + L.w / 2, L.y + L.h)
170
- g.closePath()
171
- g.fill()
172
- /* Layer phu */
173
- g.fillStyle = '#164a29'
174
- g.beginPath()
175
- g.moveTo(cx, L.y + 10)
176
- g.lineTo(cx - L.w / 2 + 10, L.y + L.h)
177
- g.lineTo(cx + L.w / 2 - 10, L.y + L.h)
178
- g.closePath()
179
- g.fill()
180
- }
181
- /* Nguoi tuyết tren dinh */
182
- g.fillStyle = '#ffe14d'
183
- g.beginPath()
184
- g.arc(cx, topY, 8, 0, Math.PI * 2)
185
- g.fill()
186
- /* Ornament da dat */
187
- for (const o of modalOrnaments) {
188
- const ox = cx + o.nx * 100 /* nx: -1..1 */
189
- const oy = topY + 40 + o.ny * 200 /* ny: 0..1 tu tren xuong */
190
- if (o.kind === 'bauble') {
191
- g.fillStyle = o.color
192
- g.beginPath(); g.arc(ox, oy, 12, 0, Math.PI * 2); g.fill()
193
- g.fillStyle = 'rgba(255,255,255,0.4)'
194
- g.beginPath(); g.arc(ox - 3, oy - 3, 4, 0, Math.PI * 2); g.fill()
195
- } else if (o.kind === 'stocking') {
196
- g.fillStyle = o.color
197
- g.fillRect(ox - 8, oy - 12, 16, 20)
198
- g.fillRect(ox - 8, oy + 6, 22, 8)
199
- g.fillStyle = '#fff'
200
- g.fillRect(ox - 8, oy - 12, 16, 4)
201
- } else if (o.kind === 'candy') {
202
- g.fillStyle = o.color
203
- g.beginPath()
204
- g.ellipse(ox, oy, 14, 7, 0.5, 0, Math.PI * 2)
205
- g.fill()
206
- g.strokeStyle = '#fff'; g.lineWidth = 2
207
- for (let a = 0; a < 4; a++) {
208
- const ang = a * Math.PI / 2 + 0.5
209
- g.beginPath()
210
- g.moveTo(ox, oy)
211
- g.lineTo(ox + Math.cos(ang) * 14, oy + Math.sin(ang) * 7)
212
- g.stroke()
213
- }
214
- } else if (o.kind === 'snowman') {
215
- g.fillStyle = '#f2f2f2'
216
- g.beginPath(); g.arc(ox, oy + 4, 10, 0, Math.PI * 2); g.fill()
217
- g.beginPath(); g.arc(ox, oy - 6, 7, 0, Math.PI * 2); g.fill()
218
- g.fillStyle = '#ff6600'
219
- g.fillRect(ox - 1, oy - 8, 3, 5)
220
- g.fillStyle = '#222'
221
- g.beginPath(); g.arc(ox - 2, oy - 8, 1, 0, Math.PI * 2); g.fill()
222
- g.beginPath(); g.arc(ox + 2, oy - 8, 1, 0, Math.PI * 2); g.fill()
223
- }
224
- }
225
- /* Huong dan */
226
- g.fillStyle = 'rgba(255,240,200,.85)'; g.font = '600 16px "Be Vietnam Pro", sans-serif'
227
- g.textAlign = 'center'
228
- g.fillText('Chạm vào cây để đặt ' + (XMAS_KINDS.find(k => k.id === (ch.selected || 'bauble'))?.label || 'bống'), cx, H - 20)
229
- }
230
- draw()
231
- /* Redraw khi modalOrnaments thay doi */
232
- const iv = setInterval(draw, 200)
233
- return () => clearInterval(iv)
234
- }, [active, modalOrnaments, ch.selected])
235
-
236
- /* Click tren modal canvas de dat ornament */
237
- const handleModalClick = React.useCallback((ev) => {
238
- if (!active || !_canvasRef.current) return
239
- const c = _canvasRef.current
240
- const rect = c.getBoundingClientRect()
241
- const mx = (ev.clientX - rect.left) / rect.width
242
- const my = (ev.clientY - rect.top) / rect.height
243
- /* Kiem tra cham vao vung cay (giua man hinh) */
244
- const cx = 0.5
245
- const nx = (mx - cx) * 2 /* -1..1 */
246
- const ny = Math.max(0, Math.min(1, (my - 0.15) / 0.7)) /* 0..1 tu tren xuong */
247
- if (nx < -0.6 || nx > 0.6 || ny < 0 || ny > 1) return
248
- const kind = ch.selected || 'bauble'
249
- const kindInfo = XMAS_KINDS.find((k) => k.id === kind) || XMAS_KINDS[0]
250
- const ornament = { kind, nx, ny, color: kindInfo.color }
251
- /* Them vao modal */
252
- setModalOrnaments((prev) => [...prev, ornament])
253
- /* Them vao store (toa do local cua tree) — map nx,ny sang x,y,z */
254
- /* Tree local: y tu 0 (goc) den 13 (dinh), x tu -4.5 den 4.5 */
255
- const tx = nx * 4.0
256
- const ty = 1.5 + ny * 10.5 /* y trong tree local */
257
- const tz = 0 /* dat o mat truoc */
258
- ch.addOrnament({ kind, x: tx, y: ty, z: tz, color: kindInfo.color, by: playerId })
259
- /* Gui len backend */
260
- Net.send({ type: 'christmas_decor', kind, x: tx, y: ty, z: tz, color: kindInfo.color, seq: Date.now() })
261
- }, [active, ch, playerId, modalOrnaments])
262
-
263
- /* Reset modalOrnaments khi dong */
264
- React.useEffect(() => {
265
- if (!active) setModalOrnaments([])
266
- }, [active])
267
-
268
- if (!active && !near) return null
269
-
270
- /* Prompt khi gan cay */
271
- if (!active && near) {
272
- return (
273
- <div style={{ position: 'fixed', bottom: 120, left: '50%', transform: 'translateX(-50%)', zIndex: 9999, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, pointerEvents: 'auto' }}>
274
- <button type="button" onClick={() => ch.set({ active: true })}
275
- style={{ background: 'linear-gradient(180deg,#1f7a3d,#0d4a1d)', color: '#fff', border: '2px solid #ffd76a', borderRadius: 999, padding: '10px 22px', fontSize: 15, fontWeight: 800, cursor: 'pointer', boxShadow: '0 4px 14px #000a' }}>
276
- 🎄 Trang trí cây thông
277
- </button>
278
- {!touch && <span style={{ fontSize: 12, color: '#fff6ec', background: 'rgba(0,0,0,0.6)', padding: '3px 10px', borderRadius: 8 }}>hoặc nhấn <kbd>E</kbd></span>}
279
- </div>
280
- )
281
- }
282
-
283
- /* Modal scene: cay thong rieng + chon loai qua */
284
- return (
285
- <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 9999, background: 'rgba(0,0,0,0.85)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 12 }}>
286
- {/* Tieu de */}
287
- <div style={{ color: '#ffd76a', fontSize: 20, fontWeight: 800, textShadow: '0 2px 8px #000' }}>🎄 Trang trí cây thông</div>
288
- {/* Canvas cay thong */}
289
- <canvas ref={_canvasRef} width={400} height={480} onClick={handleModalClick}
290
- style={{ border: '2px solid #ecd08c', borderRadius: 14, cursor: 'pointer', boxShadow: '0 8px 30px #000a', background: '#0a1528', touchAction: 'manipulation' }} />
291
- {/* Chon loai qua */}
292
- <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', justifyContent: 'center', maxWidth: 420 }}>
293
- {XMAS_KINDS.map((k) => (
294
- <button key={k.id} type="button"
295
- onClick={() => ch.set({ selected: k.id })}
296
- style={{ textAlign: 'center', padding: '8px 12px', borderRadius: 10, border: ch.selected === k.id ? '2px solid #ffd76a' : '1px solid rgba(255,255,255,0.15)', background: ch.selected === k.id ? 'rgba(255,215,106,0.15)' : 'rgba(255,255,255,0.05)', color: '#fff', fontSize: 13, cursor: 'pointer', fontWeight: ch.selected === k.id ? 700 : 400 }}>
297
- {k.label}
298
- </button>
299
- ))}
300
- </div>
301
- {/* Nut dong */}
302
- <button type="button" onClick={() => ch.set({ active: false })}
303
- style={{ background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)', borderRadius: 8, padding: '6px 16px', color: '#fff', fontSize: 13, cursor: 'pointer', marginTop: 4 }}>
304
- ✕ Đóng (Esc)
305
- </button>
306
- </div>
307
- )
308
- }
309
-
310
- `
311
- s = s.slice(0, startIdx) + newBlock + s.slice(nextFn)
312
- return s
313
- })
314
-
315
- /* ============ 4. backend.py: fix duplicate + them decor attendance ============ */
316
- const BF = 'backend.py'
317
-
318
- /* 4a. Xoa duplicate christmas_decor handler — giu 1, them _att_bump */
319
- patch(BF, 'christmas-handler-fix', (s) => {
320
- const handler = ` elif t == "christmas_decor":
321
- # Trang tri cay thong — broadcast cho tat ca trong phong
322
- decor = {
323
- "type": "christmas_decor",
324
- "player_id": player_id,
325
- "kind": str(msg.get("kind", ""))[:20],
326
- "x": float(msg.get("x", 0)),
327
- "y": float(msg.get("y", 0)),
328
- "z": float(msg.get("z", 0)),
329
- "color": str(msg.get("color", "#e8262b"))[:20],
330
- }
331
- await broadcast(room_id, decor)
332
- # Gui lai cho nguoi gui de ho biet da nhan
333
- await send(ws, {"type": "christmas_ack", "seq": msg.get("seq", 0)})`
334
- const count = s.split(handler).length - 1
335
- if (count >= 2) {
336
- let idx = s.indexOf(handler)
337
- while (s.indexOf(handler, idx + handler.length) !== -1) {
338
- const idx2 = s.indexOf(handler, idx + handler.length)
339
- s = s.slice(0, idx2) + s.slice(idx2 + handler.length)
340
- }
341
- ok('christmas-handler: xoa duplicate (' + count + ' -> 1)')
342
- }
343
- return s
344
- })
345
-
346
- patch(BF, 'christmas-bump-decor', (s) => {
347
- const old = 'await send(ws, {"type": "christmas_ack", "seq": msg.get("seq", 0)})'
348
- const neu = `p = _player_of(player_id)
349
- if p:
350
- _att_bump(p.name, "decor")
351
- await send(ws, {"type": "christmas_ack", "seq": msg.get("seq", 0)})`
352
- if (!s.includes(old)) return s
353
- if (s.includes('_att_bump(p.name, "decor")')) return s
354
- s = s.replace(old, neu)
355
- return s
356
- })
357
-
358
- patch(BF, 'att-score-decor', (s) => {
359
- const old = 'return int(r.get("visits", 0)) * 20 + int(r.get("chats", 0)) * 2 + int(r.get("joins", 0)) + int(r.get("votes", 0)) * 3 # V116: + binh chon'
360
- const neu = 'return int(r.get("visits", 0)) * 20 + int(r.get("chats", 0)) * 2 + int(r.get("joins", 0)) + int(r.get("votes", 0)) * 3 + int(r.get("decor", 0)) * 5 # V116: + binh chon; V118: + trang tri'
361
- if (!s.includes(old)) return s
362
- s = s.replace(old, neu)
363
- return s
364
- })
365
-
366
- /* 4c. /api/attendance/top: them decor */
367
- patch(BF, 'att-top-decor', (s) => {
368
- /* Them decor vao dict comprehension */
369
- const old = '"votes": int(v.get("votes", 0))}'
370
- const neu = '"votes": int(v.get("votes", 0)), "decor": int(v.get("decor", 0))}'
371
- const count = s.split(old).length - 1
372
- if (count < 1) return s
373
- s = s.replace(old, neu)
374
- return s
375
- })
376
-
377
- /* 4d. _att_stats init: them decor vao default dict */
378
- patch(BF, 'att-init-decor', (s) => {
379
- const old = 'e = _att_stats.setdefault(nm, {"visits": 0, "chats": 0, "joins": 0, "votes": 0})'
380
- const neu = 'e = _att_stats.setdefault(nm, {"visits": 0, "chats": 0, "joins": 0, "votes": 0, "decor": 0})'
381
- if (!s.includes(old)) return s
382
- s = s.replace(old, neu)
383
- return s
384
- })
385
-
386
- /* ============ 5. cave3d.js: BangVangDiemDanh them cot TRANG TRI ============ */
387
- const C = 'frontend/cave3d.js'
388
-
389
- patch(C, 'board-decor-column', (s) => {
390
- /* V118: 5 cot — them "TRANG TRI" ben phai "BINH CHON" */
391
- const oldHeader = ` /* V116: 4 cot — them "BINH CHON" ben phai "TIN NHAN" */
392
- g.fillStyle = 'rgba(236,208,140,.75)'; g.font = '700 22px "Be Vietnam Pro", sans-serif'
393
- g.textAlign = 'left'; g.fillText('#', 54, 164); g.fillText('TÊN', 116, 164)
394
- g.textAlign = 'right'
395
- g.fillText('LẦN VÀO', W - 330, 164)
396
- g.fillText('TIN NHẮN', W - 190, 164)
397
- g.fillStyle = 'rgba(143,220,255,.85)'
398
- g.fillText('BÌNH CHỌN', W - 54, 164)`
399
-
400
- const newHeader = ` /* V118: 5 cot — them "TRANG TRI" */
401
- g.fillStyle = 'rgba(236,208,140,.75)'; g.font = '700 20px "Be Vietnam Pro", sans-serif'
402
- g.textAlign = 'left'; g.fillText('#', 54, 164); g.fillText('TÊN', 116, 164)
403
- g.textAlign = 'right'
404
- g.fillText('LẦN VÀO', W - 390, 164)
405
- g.fillText('TIN NHẮN', W - 270, 164)
406
- g.fillStyle = 'rgba(143,220,255,.85)'
407
- g.fillText('BÌNH CHỌN', W - 150, 164)
408
- g.fillStyle = 'rgba(125,223,154,.85)'
409
- g.fillText('TRANG TRÍ', W - 54, 164)`
410
-
411
- if (!s.includes(oldHeader)) return s
412
- s = s.replace(oldHeader, newHeader)
413
-
414
- /* Row values: them decor cot */
415
- const oldRow = ` g.fillText(String(r && r.visits != null ? r.visits : 0), W - 330, y)
416
- g.fillStyle = 'rgba(200,225,255,.92)'
417
- g.fillText(String(r && r.chats != null ? r.chats : 0), W - 190, y)
418
- /* V116: cot binh chon */
419
- g.fillStyle = i === 0 ? '#bfe9ff' : 'rgba(143,220,255,.92)'
420
- g.fillText(String(r && r.votes != null ? r.votes : 0), W - 54, y)`
421
-
422
- const newRow = ` g.fillText(String(r && r.visits != null ? r.visits : 0), W - 390, y)
423
- g.fillStyle = 'rgba(200,225,255,.92)'
424
- g.fillText(String(r && r.chats != null ? r.chats : 0), W - 270, y)
425
- /* V116: cot binh chon */
426
- g.fillStyle = i === 0 ? '#bfe9ff' : 'rgba(143,220,255,.92)'
427
- g.fillText(String(r && r.votes != null ? r.votes : 0), W - 150, y)
428
- /* V118: cot trang tri */
429
- g.fillStyle = i === 0 ? '#7ddf9a' : 'rgba(125,223,154,.92)'
430
- g.fillText(String(r && r.decor != null ? r.decor : 0), W - 54, y)`
431
-
432
- if (!s.includes(oldRow)) return s
433
- s = s.replace(oldRow, newRow)
434
-
435
- /* Legend line: them trang tri */
436
- const oldLegend = "g.fillText('Lần vào = số lần vào · Tin nhắn = số chat · Bình chọn = số lượt', W - 54, H - 30)"
437
- const newLegend = "g.fillText('Lần vào · Tin nhắn · Bình chọn · Trang trí', W - 54, H - 30)"
438
- if (s.includes(oldLegend)) {
439
- s = s.replace(oldLegend, newLegend)
440
- }
441
-
442
- return s
443
- })
444
-
445
- /* Version bump v117 -> v118 */
446
- {
447
- const BF = 'backend.py'
448
- let bs = readFileSync(BF, 'utf8')
449
- if (bs.includes('VERSION_ID = "v118"')) {
450
- console.log('V118 OK version-bump (already v118)')
451
- } else if (bs.includes('VERSION_ID = "v117"')) {
452
- bs = bs.replace('VERSION_ID = "v117"', 'VERSION_ID = "v118"')
453
- writeFileSync(BF, bs)
454
- console.log('V118 OK version-bump -> v118')
455
- } else {
456
- console.log('V118 WARN version-bump: VERSION_ID khong tim thay')
457
- }
458
- }
459
-
460
- console.log('[v118] DONE: ' + n + ' muc — so ao len logo, bang huong dan, modal trang tri, attendance decor')