splitScreen.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import type { SplitLayout } from './types'
  2. /** Slot rects as screen fractions, mirrors the engine's splitSlotRects */
  3. export interface SlotRect {
  4. x: number
  5. y: number
  6. width: number
  7. height: number
  8. }
  9. /** aspects: width / height, 0 for any size (web) */
  10. export function splitSlotRects(
  11. screen: { width: number; height: number },
  12. aspects: number[],
  13. layout: SplitLayout
  14. ): SlotRect[] {
  15. if (aspects.length === 0 || screen.width <= 0 || screen.height <= 0) return []
  16. const columns = screen.width >= screen.height
  17. const length = columns ? screen.width : screen.height
  18. const across = columns ? screen.height : screen.width
  19. const known = aspects.filter((a) => a > 0 && Number.isFinite(a)).map((a) => (columns ? a : 1 / a))
  20. const fallback =
  21. known.length > 0 ? known.reduce((sum, a) => sum + a, 0) / known.length : length / across / aspects.length
  22. const weights = aspects.map((a) => {
  23. if (layout === 'equal') return 1
  24. return a > 0 && Number.isFinite(a) ? (columns ? a : 1 / a) : fallback
  25. })
  26. const total = weights.reduce((sum, w) => sum + w, 0)
  27. let scale = length / total
  28. let edge = 0
  29. if (layout === 'center' && total * across <= length) {
  30. scale = across
  31. edge = (length - total * across) / 2
  32. }
  33. return weights.map((weight) => {
  34. const from = edge
  35. edge += weight * scale
  36. const start = from / length
  37. const size = (weight * scale) / length
  38. return columns
  39. ? { x: start, y: 0, width: size, height: 1 }
  40. : { x: 0, y: start, width: 1, height: size }
  41. })
  42. }
  43. const SIZE_RE = /(\d+)\s*x\s*(\d+)/
  44. /** from resolution tags, 16:9 when they say nothing */
  45. export function aspectFromResolutions(resolutions: string[] | undefined): number {
  46. for (const tag of resolutions ?? []) {
  47. const match = SIZE_RE.exec(tag)
  48. if (match && Number(match[2]) > 0) return Number(match[1]) / Number(match[2])
  49. if (tag.startsWith('Portrait')) return 9 / 16
  50. }
  51. return 16 / 9
  52. }