d3ro-voice/packages/ui/src/components/ds/CrtDisplay.tsx
yunchan8804 a041f1b6a9 feat(V2-1c): packages/ui 추출 — DS 컴포넌트 + theme + theme-vars 분리
packages/ui (@d3ro/ui) 신규:
- src/theme.ts (d3roPalette/d3roTypo/d3roShadow/d3roRadius SSOT)
- src/theme-vars.ts (팝업/main 프로세스용 CSS 변수 맵)
- src/components/ds/ (CrtDisplay, InstrumentPanel, Led, MetalCard,
  MetalDial, PhosphorText, PhysicalButton, ScreenPanel, ButtonGroup)
- src/index.ts barrel
- subpath exports: ./theme, ./theme-vars, ./components/ds
- React/MUI/Emotion은 peerDependencies로 선언
- @d3ro/core만 직접 의존성

apps/desktop/src/shared/ 디렉토리 완전 제거:
- theme-vars가 마지막 남은 파일이었음
- tsconfig include에서 src/shared/**/* 제거

일괄 치환 (renderer 전역):
- ../theme, ../../theme, ./theme → @d3ro/ui/theme
- ../components/ds, ../../components/ds, ./ds, ../ds → @d3ro/ui/components/ds
- ../ds/<Component>, ../../ds/<Component> → @d3ro/ui/components/ds
  (세부 파일 import는 barrel로 통합)
- @shared/theme-vars → @d3ro/ui/theme-vars (WindowManager)

apps/desktop 설정:
- package.json: @d3ro/ui: '*' dep 추가
- tsconfig.node/web.json: @shared/* paths 완전 제거, @d3ro/ui,
  @d3ro/ui/* paths 추가
- electron.vite.config.ts: @shared alias 제거, @d3ro/ui alias 추가,
  externalize exclude에 @d3ro/ui 추가
- vitest.config.ts: alias 교체

DS 컴포넌트 내부의 '../../theme' 상대 경로는 packages/ui 구조에서
동일하게 해결되어 그대로 유효.

검증: typecheck + build + dev 런타임 모두 통과.
2026-04-08 14:50:33 +09:00

298 lines
8.7 KiB
TypeScript

// src/renderer/components/ds/CrtDisplay.tsx
// 시안 A: CRT 디스플레이 — WebGL 셰이더 (스캔라인, 비네팅, 노이즈, 글리치, 파형)
import { useRef, useEffect, useCallback } from 'react'
import { Box } from '@mui/material'
import { useTheme } from '@mui/material/styles'
import { d3roPalette, d3roFontMono, d3roShadow } from '../../theme'
// ── WebGL 유틸 ─────────────────────────────────────────
function createShader(gl: WebGLRenderingContext, type: number, source: string): WebGLShader | null {
const shader = gl.createShader(type)
if (!shader) return null
gl.shaderSource(shader, source)
gl.compileShader(shader)
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
gl.deleteShader(shader)
return null
}
return shader
}
function createProgram(gl: WebGLRenderingContext, vsSource: string, fsSource: string): WebGLProgram | null {
const vs = createShader(gl, gl.VERTEX_SHADER, vsSource)
const fs = createShader(gl, gl.FRAGMENT_SHADER, fsSource)
if (!vs || !fs) return null
const prog = gl.createProgram()
if (!prog) return null
gl.attachShader(prog, vs)
gl.attachShader(prog, fs)
gl.linkProgram(prog)
return prog
}
const VERTEX_SHADER = `
attribute vec2 position;
varying vec2 vUv;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
vUv = position * 0.5 + 0.5;
}
`
const FRAGMENT_SHADER = `
precision highp float;
varying vec2 vUv;
uniform float u_time;
uniform float u_glitch;
uniform float u_amp;
uniform float u_freq;
float random(vec2 st) { return fract(sin(dot(st.xy, vec2(12.9898,78.233))) * 43758.5453123); }
void main() {
vec2 uv = vUv;
// Glitch displacement
if (u_glitch > 0.0) {
float gOffset = (random(vec2(uv.y * 5.0, u_time)) - 0.5) * u_glitch * 0.1;
uv.x += gOffset;
}
// Base phosphor background
vec3 color = vec3(0.02, 0.015, 0.01);
// Background Grid
float gridX = step(0.98, fract(uv.x * 15.0));
float gridY = step(0.98, fract(uv.y * 10.0));
color += vec3(0.1, 0.04, 0.02) * max(gridX, gridY) * (1.0 - u_glitch);
// Oscilloscope Waveform
float t = u_time * 0.5 + u_glitch * random(uv) * 0.1;
float waveY = sin((uv.x * u_freq) + t) * u_amp;
float waveDist = abs((uv.y - 0.5) - waveY);
float lineThick = 0.005 + (u_glitch * 0.02);
float waveGlow = smoothstep(lineThick * 4.0, 0.0, waveDist);
float waveCore = smoothstep(lineThick, 0.0, waveDist);
// Amber wave (#f25b29)
vec3 waveColor = vec3(0.95, 0.35, 0.16);
color += waveColor * waveCore;
color += waveColor * 0.4 * waveGlow;
// Scanlines
float scanline = sin(uv.y * 800.0 - u_time * 10.0) * 0.04;
color -= scanline;
// Noise
float noise = random(uv + u_time) * 0.08;
color += noise;
// Vignette
float dist = distance(vUv, vec2(0.5));
float vig = smoothstep(0.8, 0.4, dist);
color *= vig;
// Edge darkening
color *= smoothstep(0.0, 0.02, vUv.x) * smoothstep(1.0, 0.98, vUv.x);
color *= smoothstep(0.0, 0.05, vUv.y) * smoothstep(1.0, 0.95, vUv.y);
gl_FragColor = vec4(color, 1.0);
}
`
const QUAD = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1])
// ── Props ──────────────────────────────────────────────
interface CrtDisplayProps {
/** 파형 진폭 (0.0 ~ 1.0) */
amplitude?: number
/** 파형 주파수 */
frequency?: number
/** 글리치 트리거 (변경 시 글리치 발생) */
glitchTrigger?: number
/** 실시간 오디오 레벨 (0.0~1.0) — 파형 진폭에 반영 */
audioLevel?: number
/** 오버레이 콘텐츠 (인광 텍스트 등) */
children?: React.ReactNode
/** 높이 (기본 280px) */
height?: number | string
}
export function CrtDisplay({
amplitude = 0.1,
frequency = 8.0,
glitchTrigger = 0,
audioLevel = 0,
children,
height = 280,
}: CrtDisplayProps): React.ReactElement {
const theme = useTheme()
const isLight = theme.palette.mode === 'light'
const canvasRef = useRef<HTMLCanvasElement>(null)
const glRef = useRef<{
gl: WebGLRenderingContext
uTime: WebGLUniformLocation | null
uGlitch: WebGLUniformLocation | null
uAmp: WebGLUniformLocation | null
uFreq: WebGLUniformLocation | null
} | null>(null)
const animRef = useRef<number>(0)
const startTimeRef = useRef(Date.now())
const glitchRef = useRef(0)
const ampRef = useRef(amplitude)
const freqRef = useRef(frequency)
const audioLevelRef = useRef(audioLevel)
const currentAmpRef = useRef(amplitude)
const currentFreqRef = useRef(frequency)
// amplitude/frequency/audioLevel 변경 추적
useEffect(() => {
ampRef.current = amplitude
freqRef.current = frequency
}, [amplitude, frequency])
useEffect(() => {
audioLevelRef.current = audioLevel
}, [audioLevel])
// 글리치 트리거
useEffect(() => {
if (glitchTrigger > 0) {
glitchRef.current = 1.0
}
}, [glitchTrigger])
const render = useCallback(() => {
const ctx = glRef.current
if (!ctx) return
const { gl, uTime, uGlitch, uAmp, uFreq } = ctx
// audioLevel → amplitude 반영: 기본 amplitude + 오디오 레벨로 증폭
const targetAmp = ampRef.current + audioLevelRef.current * 0.35
// Smoothing
currentAmpRef.current += (targetAmp - currentAmpRef.current) * 0.15
currentFreqRef.current += (freqRef.current - currentFreqRef.current) * 0.1
glitchRef.current *= 0.85
gl.uniform1f(uTime, (Date.now() - startTimeRef.current) / 1000)
gl.uniform1f(uGlitch, glitchRef.current)
gl.uniform1f(uAmp, currentAmpRef.current)
gl.uniform1f(uFreq, currentFreqRef.current)
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
animRef.current = requestAnimationFrame(render)
}, [])
useEffect(() => {
const canvas = canvasRef.current
if (!canvas) return
const gl = canvas.getContext('webgl', { alpha: true })
if (!gl) return
canvas.width = canvas.clientWidth * 2
canvas.height = canvas.clientHeight * 2
gl.viewport(0, 0, canvas.width, canvas.height)
const prog = createProgram(gl, VERTEX_SHADER, FRAGMENT_SHADER)
if (!prog) return
gl.useProgram(prog)
const buffer = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
gl.bufferData(gl.ARRAY_BUFFER, QUAD, gl.STATIC_DRAW)
const posLoc = gl.getAttribLocation(prog, 'position')
gl.enableVertexAttribArray(posLoc)
gl.vertexAttribPointer(posLoc, 2, gl.FLOAT, false, 0, 0)
glRef.current = {
gl,
uTime: gl.getUniformLocation(prog, 'u_time'),
uGlitch: gl.getUniformLocation(prog, 'u_glitch'),
uAmp: gl.getUniformLocation(prog, 'u_amp'),
uFreq: gl.getUniformLocation(prog, 'u_freq'),
}
startTimeRef.current = Date.now()
animRef.current = requestAnimationFrame(render)
return () => {
cancelAnimationFrame(animRef.current)
}
}, [render])
return (
<Box
sx={{
position: 'relative',
height,
bgcolor: d3roPalette.bg.crtBezel,
borderRadius: '8px',
boxShadow: d3roShadow.insetDeep,
overflow: 'hidden',
}}
>
{/* Glass surface */}
<Box
sx={{
position: 'absolute',
inset: '2px',
borderRadius: '6px',
bgcolor: d3roPalette.bg.crtGlass,
overflow: 'hidden',
boxShadow: d3roShadow.screenGlow,
}}
>
<canvas
ref={canvasRef}
style={{
position: 'absolute',
inset: 0,
width: '100%',
height: '100%',
// 라이트 모드에서 WebGL 셰이더(다크 전용)를 반전하여 밝은 배경에 어울리게 조정
...(isLight && { filter: 'invert(0.88) hue-rotate(180deg)', opacity: 0.9 }),
}}
/>
{/* Glass reflection */}
<Box
sx={{
position: 'absolute',
top: 0, left: 0, right: 0, bottom: '50%',
background: isLight
? 'linear-gradient(180deg, rgba(255,255,255,0.30) 0%, rgba(255,255,255,0) 100%)'
: 'linear-gradient(180deg, rgba(255,255,255,0.03) 0%, rgba(255,255,255,0) 100%)',
pointerEvents: 'none',
zIndex: 10,
}}
/>
</Box>
{/* Content overlay (phosphor text) */}
<Box
sx={{
position: 'absolute',
inset: '16px',
zIndex: 2,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between',
color: d3roPalette.accent.amber,
textShadow: '0 0 6px rgba(242, 91, 41, 0.4)',
pointerEvents: 'none',
fontFamily: d3roFontMono,
}}
>
{children}
</Box>
</Box>
)
}