forked from RikuKunMS2/moonlight-ios-vision
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathRealityKitStreamView.swift
More file actions
1976 lines (1732 loc) · 87.4 KB
/
RealityKitStreamView.swift
File metadata and controls
1976 lines (1732 loc) · 87.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// RealityKitStreamView.swift
// Moonlight Vision
//
// Created by tht7 on 29/12/2024.
// Copyright © 2024 Moonlight Game Streaming Project. All rights reserved.
//
import GameController
import RealityKit
import RealityKitContent
import SwiftUI
import simd
let MAX_WIDTH_METERS: Float = 2
// Limited to ~75 degrees (1.3 rad) to prevent distortion
let MAX_CURVE_ANGLE: Float = 1.3
// Studio docking surface dimensions (meters) derived from CustomDockingRegion bounds
let STUDIO_DOCK_WIDTH_METERS: Float = 8.5
let STUDIO_DOCK_HEIGHT_METERS: Float = 3.5416667
// MARK: - Delegate
@objc
class DummyControllerDelegate: NSObject, ControllerSupportDelegate {
func gamepadPresenceChanged() {}
func mousePresenceChanged() {}
func streamExitRequested() {}
}
// MARK: - Wrapper View
struct RealityKitStreamView: View {
@Environment(\.dismissWindow) private var dismissWindow
@Environment(\.openWindow) private var openWindow
@Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace
@Binding var streamConfig: StreamConfiguration?
var needsHdr: Bool
var isImmersive: Bool
var body: some View {
if streamConfig != nil {
_RealityKitStreamView(
streamConfig: Binding<StreamConfiguration>(
get: { streamConfig ?? StreamConfiguration() },
set: { streamConfig = $0 }
),
needsHdr: needsHdr,
isImmersive: isImmersive
) {
// --- CLOSE ACTION ---
print("[RealityKitStreamView] Close Action Triggered.")
// Reset immersion style before closing
ImmersionStyleManager.shared.currentStyle = .mixed
// 1. Dismiss the current space/window
if isImmersive {
Task { await dismissImmersiveSpace() }
} else {
dismissWindow(id: "realitykitStreamingWindow")
}
// 2. Clear config to trigger the 'else' block below
streamConfig = nil
}
} else {
// Cleanup View (Triggers when streamConfig becomes nil)
ProgressView().onAppear {
print("[RealityKitStreamView] Stream Ended. Cleaning up.")
// Redundant safety dismissal
if isImmersive {
Task { await dismissImmersiveSpace() }
} else {
dismissWindow(id: "realitykitStreamingWindow")
}
}
}
}
}
// MARK: - Main Logic View
struct _RealityKitStreamView: View {
@Environment(\.openWindow) private var openWindow
@Environment(\.dismissWindow) private var dismissWindow
@Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace
@Environment(\.scenePhase) private var scenePhase
@EnvironmentObject private var viewModel: MainViewModel
@EnvironmentObject private var controlState: StreamControlState
@Binding var streamConfig: StreamConfiguration
var needsHdr: Bool
var isImmersive: Bool
let closeAction: () -> Void
// UI State
@State private var showVirtualKeyboard = false
@State var curveMagnitudeMemory: Float = 0
@State var curveAnimationMultiplier: Float = 1
@State var controllerSupport: ControllerSupport?
// Tracks when the texture instance has been replaced
@State private var textureId: UUID = UUID()
// Interaction State
@State private var isInteractive: Bool = false
// Controls State
@State private var isControlsVisible: Bool = true
@State private var controlsEntity: Entity?
// Volumetric Position State
@State var height: Float = 0
@State private var depthOffset: Float = 0.0
@State private var yLimits: ClosedRange<Float> = -0.5...0.5
@State private var zLimits: ClosedRange<Float> = -0.5...0.5
// Immersive Transform State
@State private var immersiveScale: Float = 1.8
@State private var immersivePosition: SIMD3<Float> = SIMD3<Float>(0, 1.5, -2.0)
@State private var startDragPosition: SIMD3<Float>? = nil
// Immersion State
@State private var immersionAmount: Float = 0.0
@State private var blackOutSphere: ModelEntity = ModelEntity()
// HDR Settings (Thread Safe)
@State private var safeHDRSettings = ThreadSafeHDRSettings(
params: HDRParams(boost: 2.0, contrast: 1.0, saturation: 1.0, brightness: 0.0)
)
@State var shouldClose: Bool = false
@State var hasPerformedTeardown = false
@State var needsResume = false
@State var didPerformFullClose = false
@State var animationTimer: Timer?
@State var _streamMan: StreamManager?
@ObservedObject var connectionCallbacks: ObservableConnectionManager = .init()
@State var texture: TextureResource
@State var screen: ModelEntity = ModelEntity()
// Environment Entity Tracking
@State var currentEnvEntity: Entity?
@State private var screenOriginalParent: Entity?
@State var videoMode: VideoMode = .standard2D
@State private var surfaceMaterial: ShaderGraphMaterial?
// Environment State
// Use @State to hold the reference, but we need to treat it carefully in closure contexts
// to avoid the dynamic member lookup on the wrapper.
@State private var immersiveEnvironment = ImmersiveEnvironment()
// Track environment state separately for Picker binding
@State private var selectedEnvironmentState: EnvironmentStateType = .none
// Environment preload for immersive mode
@State private var environmentPreloaded: Bool = false
// Prevent rapid toggling of immersion style
@State private var isUpdatingImmersion: Bool = false
// Pinning (Studio stage) state
@State private var isPinnedToStage: Bool = false
@State private var isPinningTransitioning: Bool = false
@State private var lastFreeformTransform: Transform?
@State private var pinnedStageScale: Float = 1.0
@State private var wasInteractiveBeforePin: Bool = false
@State private var pinStartScale: Float = 1.0
var isSBSVideo: Bool {
let ratio = Float(streamConfig.width) / Float(streamConfig.height)
return abs(ratio - (32.0 / 9.0)) < 0.01
}
var aspectRatio: Float {
if videoMode == .sideBySide3D && isSBSVideo {
return Float(streamConfig.height) / Float(streamConfig.width / 2)
} else {
return Float(streamConfig.height) / Float(streamConfig.width)
}
}
init(streamConfig: Binding<StreamConfiguration>, needsHdr: Bool, isImmersive: Bool, closeAction: @escaping () -> Void) {
self.closeAction = closeAction
self._streamConfig = streamConfig
self.needsHdr = needsHdr
self.isImmersive = isImmersive
self.controllerSupport = ControllerSupport(config: streamConfig.wrappedValue, delegate: DummyControllerDelegate())
// ADAPTIVE PIXEL FORMAT: Fixes Cyan screen on SDR and enables HDR on AV1/HEVC
let bytesPerPixel = needsHdr ? 8 : 4
let data = Data.init(count: bytesPerPixel * Int(streamConfig.wrappedValue.width) * Int(streamConfig.wrappedValue.height))
self.texture = try! TextureResource(
dimensions: .dimensions(width: Int(streamConfig.wrappedValue.width), height: Int(streamConfig.wrappedValue.height)),
format: .raw(pixelFormat: needsHdr ? .rgba16Float : .bgra8Unorm_srgb), // Adaptive format
contents: .init(
mipmapLevels: [
.mip(data: data, bytesPerRow: bytesPerPixel * Int(streamConfig.wrappedValue.width)),
]
)
)
}
// MARK: - Main Body
var body: some View {
// 1. Base Content Group
let baseContent = Group {
if viewModel.activelyStreaming {
activeStreamView
} else {
streamStoppedOverlay
}
}
// 2. Apply Visual Modifiers
let visualContent = baseContent
.task {
await setupMaterial()
}
.ornament(visibility: connectionCallbacks.showAlert ? .visible : .hidden , attachmentAnchor: .scene(.bottomFront), contentAlignment: .bottom) {
errorOrnament
}
.modifier(VolumetricWindowControls(isImmersive: isImmersive, content: { controlsView }))
.persistentSystemOverlays(viewModel.streamSettings.dimPassthrough ? .hidden : .automatic)
.preferredSurroundingsEffect(
// Apply dimming effect when dimPassthrough is enabled, or use environment effect in immersive mode
viewModel.streamSettings.dimPassthrough
? .systemDark
: (isImmersive && immersiveEnvironment.environmentStateHandler.activeState != .none
? immersiveEnvironment.surroundingsEffect
: nil)
)
.volumeBaseplateVisibility(viewModel.streamSettings.dimPassthrough ? .hidden : .automatic)
.supportedVolumeViewpoints(.front)
func updateHDRParams() {
safeHDRSettings.value = HDRParams(
boost: viewModel.streamSettings.brightness,
contrast: viewModel.streamSettings.gamma,
saturation: viewModel.streamSettings.saturation,
brightness: 0.0
)
}
// 3. Apply Logic/Lifecycle Modifiers
let withHDRSync = visualContent
.onChange(of: viewModel.streamSettings.brightness) { _, _ in updateHDRParams() }
.onChange(of: viewModel.streamSettings.gamma) { _, _ in updateHDRParams() }
.onChange(of: viewModel.streamSettings.saturation) { _, _ in updateHDRParams() }
// 4. Apply Lifecycle Modifiers
let withLifecycle = withHDRSync
.task { await handleImmersiveSetupTask() }
.onAppear { handleOnAppear() }
.onChange(of: shouldClose) { _, val in if val { triggerCloseSequence() } }
.onChange(of: scenePhase) { _, phase in handleScenePhaseChange(phase) }
// 5. Apply Control State Sync (only needed in immersive mode)
return withLifecycle
.modifier(ControlStateSyncModifier(
isImmersive: isImmersive,
controlState: controlState,
immersiveScale: $immersiveScale,
immersivePosition: $immersivePosition,
immersionAmount: $immersionAmount,
isInteractive: $isInteractive,
selectedEnvironmentState: $selectedEnvironmentState,
isUpdatingImmersion: isUpdatingImmersion,
showVirtualKeyboard: showVirtualKeyboard,
videoMode: videoMode,
isPinnedToStage: isPinnedToStage,
isPinningTransitioning: isPinningTransitioning,
syncToLocal: syncControlStateToLocal,
syncFromLocal: syncLocalStateToControlState
))
}
// MARK: - Lifecycle Handlers
private func handleImmersiveSetupTask() async {
if isImmersive {
immersiveEnvironment.clearEnvironment()
environmentPreloaded = false
selectedEnvironmentState = .none
print("Preloading environment assets...")
immersiveEnvironment.loadEnvironment()
environmentPreloaded = true
updateImmersionStyle(state: .none, semi: false, shouldLock: false)
}
}
private func handleOnAppear() {
safeHDRSettings.value = HDRParams(
boost: viewModel.streamSettings.brightness,
contrast: viewModel.streamSettings.gamma,
saturation: viewModel.streamSettings.saturation,
brightness: 0.0
)
// Load saved settings before setting up state
loadRealityKitSettings()
if isImmersive {
setupControlStateCallbacks()
// Sync loaded values to controlState
controlState.immersiveScale = immersiveScale
controlState.immersivePositionX = immersivePosition.x
controlState.immersivePositionY = immersivePosition.y
controlState.immersivePositionZ = immersivePosition.z
controlState.immersionAmount = immersionAmount
controlState.pinnedStageScale = pinnedStageScale
syncLocalStateToControlState()
}
if !viewModel.activelyStreaming {
print("_RealityKitStreamView: Detected appearance without active stream state.")
openWindow(id: "mainView")
self.closeAction()
} else {
startStreamIfNeeded()
}
}
// MARK: - Subviews
@ViewBuilder
var activeStreamView: some View {
GeometryReader3D { proxy in
ZStack {
// 1. GLOBAL INPUT CAPTURE (NON-IMMERSIVE ONLY)
if !isImmersive, let support = controllerSupport {
RealityKitInputView(
streamConfig: streamConfig,
controllerSupport: support,
showKeyboard: $showVirtualKeyboard
)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.opacity(0.01)
}
// 2. The 3D Screen
makeRealityView(proxy: proxy)
// 3. Keyboard Overlay
if showVirtualKeyboard {
virtualKeyboardOverlay
}
// 4. Environment Loading Indicator (Immersive only, shown when entering quickly)
if isImmersive && immersiveEnvironment.isLoading {
environmentLoadingIndicator
}
}
}
}
@ViewBuilder
func makeRealityView(proxy: GeometryProxy3D) -> some View {
RealityView { content, attachments in
setupRealityView(content: content, attachments: attachments)
} update: { content, attachments in
updateStreamEntity(content: content, attachments: attachments, proxy: proxy)
} attachments: {
// Control panel Attachment (freely movable)
Attachment(id: "controls") {
if isImmersive && controlState.isControlPanelVisible {
ImmersiveControlPanelView()
.environmentObject(viewModel)
.environmentObject(controlState)
}
}
// Global Dock Attachment (independent of screen, fixed in front of user)
Attachment(id: "dock") {
if isImmersive {
ImmersiveDockView()
.environmentObject(controlState)
.environmentObject(viewModel)
}
}
// INPUT ATTACHMENT (IMMERSIVE ONLY)
Attachment(id: "input_overlay") {
if isImmersive, let support = controllerSupport {
RealityKitInputView(
streamConfig: streamConfig,
controllerSupport: support,
showKeyboard: $showVirtualKeyboard
)
.frame(width: 1920, height: 1920 / CGFloat(aspectRatio))
.opacity(0.01)
}
}
}
// Gestures
.gesture(dragGesture)
.gesture(magnifyGesture)
}
// MARK: - Logic Helpers
func triggerCloseSequence() {
// Reset immersion style to mixed before closing
ImmersionStyleManager.shared.currentStyle = .mixed
viewModel.currentImmersionStyle = .mixed
// Hide control panel
controlState.isControlPanelVisible = false
openWindow(id: "mainView")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.closeAction()
}
}
// MARK: - Control State Sync
func setupControlStateCallbacks() {
controlState.needsHdr = needsHdr
controlState.controllerSupport = controllerSupport
controlState.closeAction = { [self] in
if streamConfig != nil { viewModel.savedStreamConfigForResume = streamConfig }
needsResume = false
hasPerformedTeardown = false
viewModel.activelyStreaming = false
_streamMan?.stopStream()
controllerSupport?.cleanup()
triggerCloseSequence()
}
controlState.toggleKeyboardAction = { [self] in
showVirtualKeyboard.toggle()
}
controlState.onEnvironmentChange = { [self] newState in
selectedEnvironmentState = newState
immersiveEnvironment.requestEnvironmentState(newState)
let needsLock = (selectedEnvironmentState == .none || newState == .none)
updateImmersionStyle(state: newState, semi: immersiveEnvironment.isSemiImmersionEnabled, shouldLock: needsLock)
if newState == .none && isPinnedToStage {
unpinStreamFromStage(animated: false)
}
}
controlState.onSemiImmersionToggle = { [self] enabled in
immersiveEnvironment.isSemiImmersionEnabled = enabled
updateImmersionStyle(state: immersiveEnvironment.activeState, semi: enabled, shouldLock: true)
}
controlState.onPinToggle = { [self] in
if isPinnedToStage {
unpinStreamFromStage(animated: true)
} else {
pinStreamToStage()
}
}
controlState.saveSettings = { [self] in
// Sync local state to controlState before saving (for immersive mode)
if isImmersive {
syncLocalStateToControlState()
}
saveRealityKitSettings()
}
controlState.toggle3DMode = { [self] in
if videoMode == .sideBySide3D {
videoMode = .standard2D
screen.model?.materials = [UnlitMaterial(texture: texture)]
} else {
videoMode = .sideBySide3D
if let mat = surfaceMaterial {
screen.model?.materials = [mat]
}
}
}
}
func syncLocalStateToControlState() {
controlState.immersiveScale = immersiveScale
controlState.immersivePositionX = immersivePosition.x
controlState.immersivePositionY = immersivePosition.y
controlState.immersivePositionZ = immersivePosition.z
controlState.immersionAmount = immersionAmount
controlState.isInteractive = isInteractive
controlState.selectedEnvironmentState = selectedEnvironmentState
controlState.isSemiImmersionEnabled = immersiveEnvironment.isSemiImmersionEnabled
controlState.isUpdatingImmersion = isUpdatingImmersion
controlState.isKeyboardActive = showVirtualKeyboard
controlState.videoMode = videoMode
controlState.isPinnedToStage = isPinnedToStage
controlState.isPinningTransitioning = isPinningTransitioning
controlState.canPinToStage = immersiveEnvironment.dockingAnchor != nil
// Sync pinned scale and height (only when pinned, to avoid overwriting user adjustments)
if isPinnedToStage {
controlState.pinnedStageScale = pinnedStageScale
// Height value is only maintained in controlState, no reverse sync needed
}
}
func syncControlStateToLocal() {
immersiveScale = controlState.immersiveScale
immersivePosition = SIMD3<Float>(
controlState.immersivePositionX,
controlState.immersivePositionY,
controlState.immersivePositionZ
)
immersionAmount = controlState.immersionAmount
isInteractive = controlState.isInteractive
if selectedEnvironmentState != controlState.selectedEnvironmentState {
selectedEnvironmentState = controlState.selectedEnvironmentState
}
videoMode = controlState.videoMode
// Sync pinned scale value (only when pinned)
if isPinnedToStage && !isPinningTransitioning {
pinnedStageScale = controlState.pinnedStageScale
}
}
func setupMaterial() async {
if surfaceMaterial == nil {
do {
var material = try await ShaderGraphMaterial(named: "/Root/SBSMaterial", from: "SBSMaterial.usda")
try material.setParameter(name: "texture", value: .textureResource(self.texture))
self.surfaceMaterial = material
} catch { print("Material Error: \(error)") }
}
}
func setupRealityView(content: RealityViewContent, attachments: RealityViewAttachments) {
let mesh = try! Self.generateCurvedPlane(
width: MAX_WIDTH_METERS,
aspectRatio: aspectRatio,
resolution: (100,100),
curveMagnitude: viewModel.streamSettings.realitykitRendererCurvature * curveAnimationMultiplier
)
let colDepth: Float = isImmersive ? 0.1 : 0.001
let colBox = ShapeResource.generateBox(width: 2, height: 2 * aspectRatio, depth: colDepth)
.offsetBy(translation: .init(x: 0, y: -0.43, z: 0))
screen = ModelEntity(mesh: mesh, materials: [])
if videoMode == .sideBySide3D, let material = surfaceMaterial {
screen.model?.materials = [material]
} else {
screen.model?.materials = [UnlitMaterial(texture: self.texture)]
}
screen.collision = CollisionComponent(shapes: [colBox], mode: .colliding)
screen.components.set(InputTargetComponent())
content.add(screen)
if screenOriginalParent == nil {
screenOriginalParent = screen.parent
}
if isImmersive {
let sphereMesh = MeshResource.generateSphere(radius: 100)
let blackMaterial = UnlitMaterial(color: .black)
blackOutSphere = ModelEntity(mesh: sphereMesh, materials: [blackMaterial])
blackOutSphere.scale = SIMD3<Float>(-1, 1, 1)
blackOutSphere.components.set(OpacityComponent(opacity: 0.0))
content.add(blackOutSphere)
}
// Global Dock - fixed below user's line of sight
if isImmersive, let dock = attachments.entity(for: "dock") {
content.add(dock)
// Fixed position in front and below user
dock.position = SIMD3<Float>(0, 0.6, -1.0)
}
// Control panel - independent of screen, freely movable
if isImmersive, let controls = attachments.entity(for: "controls") {
self.controlsEntity = controls
content.add(controls)
// Initial position: in front and slightly below user
controls.position = SIMD3<Float>(0, 1.0, -1.3)
controls.components.set(InputTargetComponent())
}
if isImmersive, let inputEnt = attachments.entity(for: "input_overlay") {
screen.addChild(inputEnt)
inputEnt.position = [0, 0, 0.01]
}
}
func updateStreamEntity(content: RealityViewContent, attachments: RealityViewAttachments, proxy: GeometryProxy3D) {
// CRITICAL: Ensure screen is in scene (handles re-entry after returning from main menu)
if screen.parent == nil && screen.model?.mesh != nil {
content.add(screen)
if screenOriginalParent == nil {
screenOriginalParent = screen.parent
}
print("🔄 Re-added screen entity to scene after re-entry")
}
// Environment Management
if isImmersive {
let envRoot = immersiveEnvironment.rootEntity
let currentState = immersiveEnvironment.environmentStateHandler.activeState
if let envRoot = envRoot {
let isInScene = envRoot.parent != nil
if currentState != .none {
// Add environment only when not in None state
if !isInScene {
content.add(envRoot)
print("➕ Added environment entity to scene (state: \(currentState))")
}
// Ensure it's enabled
if !envRoot.isEnabled {
envRoot.isEnabled = true
print("Enabled environment entity")
}
} else {
// CRITICAL: Remove environment COMPLETELY when in None state for full passthrough
if isInScene {
content.remove(envRoot)
print("REMOVED environment entity from scene (state: None) - PASSTHROUGH ACTIVE")
}
// Ensure it's disabled
if envRoot.isEnabled {
envRoot.isEnabled = false
print("Disabled environment entity - PASSTHROUGH ACTIVE")
}
}
} else {
// Entity not loaded yet - this is normal on first frame
if currentState != .none {
// If we want an environment but it's not loaded, trigger load if not already loading
if !immersiveEnvironment.isLoading && !immersiveEnvironment.isLoaded {
print("Environment needed but not loaded, triggering load...")
immersiveEnvironment.loadEnvironment()
}
}
}
}
let currentCurve = viewModel.streamSettings.realitykitRendererCurvature * curveAnimationMultiplier
// Decide whether to increase mesh resolution when pinned based on settings
let baseResolution: UInt32 = 100
let resolutionMultiplier: UInt32
if isPinnedToStage && viewModel.streamSettings.realitykitHighResPinnedScreen {
// If high resolution setting is enabled, increase resolution based on scale (up to 2x, i.e., 200x200)
let scaleFactor = min(controlState.pinnedStageScale / 1.0, 2.0)
resolutionMultiplier = UInt32(max(1, min(2, Int(scaleFactor))))
} else {
resolutionMultiplier = 1
}
let meshResolution = (baseResolution * resolutionMultiplier, baseResolution * resolutionMultiplier)
if let mesh = try? Self.generateCurvedPlane(
width: MAX_WIDTH_METERS,
aspectRatio: aspectRatio,
resolution: meshResolution,
curveMagnitude: currentCurve
) {
try? screen.model!.mesh.replace(with: mesh.contents)
}
let totalAngle = MAX_CURVE_ANGLE * currentCurve.clamped(to: 0...1)
let radius = totalAngle < 0.001 ? Float.infinity : (MAX_WIDTH_METERS / totalAngle)
let curveDepth = totalAngle < 0.001 ? 0 : radius * (1.0 - cos(totalAngle / 2.0))
let zCorrection = -curveDepth
if isImmersive {
if isPinnedToStage {
// When pinning transition is in progress, do NOT touch the transform at all.
// Let the move() animation handle everything.
if !isPinningTransitioning {
// Use adjustable scale and height values from controlState
// If screen is a child of anchor, need to update transform
if let anchor = immersiveEnvironment.dockingAnchor, screen.parent == anchor {
// Update transform's scale and translation
// Note: Screen is rotated -90 degrees (around X axis), so:
// - Local Y axis corresponds to world's forward/backward direction
// - Local Z axis corresponds to world's vertical direction (but reversed, down is positive)
var currentTransform = screen.transform
currentTransform.scale = SIMD3<Float>(repeating: controlState.pinnedStageScale)
// Update height: In rotated coordinate system, Z axis corresponds to vertical direction, need to negate
let forwardOffset: Float = 0.05
currentTransform.translation = SIMD3<Float>(0, forwardOffset, -controlState.pinnedStageHeight)
screen.transform = currentTransform
} else {
// If not yet a child node, directly set scale
screen.scale = SIMD3<Float>(repeating: controlState.pinnedStageScale)
}
// If scale value changed, update mesh resolution to maintain clarity
if abs(pinnedStageScale - controlState.pinnedStageScale) > 0.01 {
pinnedStageScale = controlState.pinnedStageScale
updateMeshResolutionForPinning()
} else {
pinnedStageScale = controlState.pinnedStageScale
}
}
// else: animation is running, hands off!
} else {
// Apply user-controlled transform only when not pinned
screen.scale = SIMD3<Float>(repeating: immersiveScale)
screen.position = immersivePosition + SIMD3<Float>(0, 0, zCorrection)
}
// Immersion Amount Logic
// If using Custom Environment (Studio), 'immersionAmount' might control
// something else or be ignored in favor of the environment's own state.
// But if in Passthrough (None), we might want the black sphere for dimming.
let isUsingCustomEnv = immersiveEnvironment.environmentStateHandler.activeState != .none
if isUsingCustomEnv {
// In Studio mode, we don't use the black sphere for immersion
blackOutSphere.components.set(OpacityComponent(opacity: 0.0))
} else {
// In Passthrough mode, use the sphere for simple dimming if desired
// Or if 'immersion' slider is used to dim passthrough.
blackOutSphere.components.set(OpacityComponent(opacity: immersionAmount))
}
blackOutSphere.position = .zero
if let inputEnt = attachments.entity(for: "input_overlay") {
let bounds = inputEnt.visualBounds(relativeTo: nil)
if bounds.extents.x > 0 {
let inputBuffer: Float = 1.15
let scale = (MAX_WIDTH_METERS / bounds.extents.x) * inputBuffer
inputEnt.scale = SIMD3<Float>(scale, scale, 1)
}
}
} else {
let volSize = content.convert(proxy.frame(in: .local), from: .local, to: .scene).extents
let scaleFactor = volSize.x / 2.0
screen.scale = SIMD3<Float>(repeating: scaleFactor)
updateWindowedLimits(volSize: volSize, scaleFactor: scaleFactor, curveDepth: curveDepth)
screen.position = SIMD3<Float>(0, height, depthOffset + zCorrection)
}
updateAttachments(attachments: attachments)
}
func updateWindowedLimits(volSize: SIMD3<Float>, scaleFactor: Float, curveDepth: Float) {
Task { @MainActor in
let screenHalfHeight = (MAX_WIDTH_METERS * self.aspectRatio * scaleFactor) / 2
let volHalfHeight = volSize.y / 2
let safePadding: Float = 0.05
let maxY = max(0, volHalfHeight - screenHalfHeight - safePadding)
let newYLimits = -maxY...maxY
let volHalfDepth = volSize.z / 2
let maxZ = volHalfDepth - safePadding
let scaledCurveDepth = curveDepth * scaleFactor
let minZ = -volHalfDepth + scaledCurveDepth + safePadding
let safeMaxZ = max(minZ, maxZ)
let newZLimits = minZ...safeMaxZ
if self.yLimits != newYLimits {
self.yLimits = newYLimits
if self.height < newYLimits.lowerBound { self.height = newYLimits.lowerBound }
else if self.height > newYLimits.upperBound { self.height = newYLimits.upperBound }
}
if self.zLimits != newZLimits {
self.zLimits = newZLimits
if self.depthOffset < newZLimits.lowerBound { self.depthOffset = newZLimits.lowerBound }
else if self.depthOffset > newZLimits.upperBound { self.depthOffset = newZLimits.upperBound }
}
}
}
func updateAttachments(attachments: RealityViewAttachments) {
// Attachments handled in RealityViewBuilder
}
var dragGesture: some Gesture {
DragGesture()
.targetedToEntity(screen)
.onChanged { value in
guard isImmersive, !isInteractive else { return }
if startDragPosition == nil { startDragPosition = immersivePosition }
let translation = value.convert(value.translation3D, from: .local, to: .scene)
immersivePosition = startDragPosition! + SIMD3<Float>(translation.x, translation.y, translation.z)
}
.onEnded { _ in
startDragPosition = nil
if viewModel.streamSettings.rememberStreamSettings { saveRealityKitSettings() }
}
}
var magnifyGesture: some Gesture {
MagnifyGesture()
.targetedToEntity(screen)
.onChanged { value in
guard isImmersive, !isInteractive else { return }
let newScale = immersiveScale * Float(value.magnification)
immersiveScale = min(max(newScale, 0.05), 10.0)
}
.onEnded { _ in
if viewModel.streamSettings.rememberStreamSettings { saveRealityKitSettings() }
}
}
// MARK: - Stream Management
private func startStreamIfNeeded() {
guard _streamMan == nil else {
needsResume = false
return
}
dismissWindow(id: "mainView")
dismissWindow(id: "dummy")
self.curveAnimationMultiplier = viewModel.streamSettings.realitykitRendererAnimateOpening ? 0 : 1
didPerformFullClose = false
self._streamMan = StreamManager(
config: self.streamConfig,
rendererProvider: {
DrawableVideoDecoder(
texture: self.texture,
callbacks: self.connectionCallbacks,
aspectRatio: Float(self.streamConfig.width) / Float(self.streamConfig.height),
useFramePacing: self.streamConfig.useFramePacing,
enableHDR: self.viewModel.streamSettings.enableHdr,
hdrSettingsProvider: { [safeHDRSettings] in
return safeHDRSettings.value
},
callbackToRender: { texture, correctedResultion in
DispatchQueue.main.async {
if let correctedResultion = correctedResultion {
streamConfig.width = Int32(correctedResultion.0)
streamConfig.height = Int32(correctedResultion.1)
}
self.texture.replace(withDrawables: texture)
self.controllerSupport!.connectionEstablished()
if self.curveAnimationMultiplier == 0 { animateOpening() }
}
})
},
connectionCallbacks: self.connectionCallbacks
)
let operationQueue = OperationQueue()
operationQueue.addOperation(_streamMan!)
needsResume = false
}
private func pauseStreamForBackground() {
guard _streamMan != nil else { return }
stopStream(teardownCompletely: false)
}
private func handleUserRequestedClose() {
stopStream(teardownCompletely: true)
DispatchQueue.main.async {
openWindow(id: "mainView")
}
}
private func stopStream(teardownCompletely: Bool) {
_streamMan?.stopStream()
_streamMan = nil
controllerSupport?.cleanup()
if teardownCompletely {
if didPerformFullClose { return }
didPerformFullClose = true
viewModel.activelyStreaming = false
needsResume = false
self.closeAction()
} else {
needsResume = true
}
}
private func handleSceneDisappearance() {
guard !didPerformFullClose else { return }
guard !needsResume else { return }
handleUserRequestedClose()
}
func handleScenePhaseChange(_ phase: ScenePhase) {
switch phase {
case .background:
guard !hasPerformedTeardown else { return }
guard !shouldClose else { return }
needsResume = true
hasPerformedTeardown = true
viewModel.activelyStreaming = false
_streamMan?.stopStream()
controllerSupport?.cleanup()
case .active:
guard needsResume else { return }
guard !shouldClose else { return }
guard streamConfig != nil else { return }
Task {
try? await Task.sleep(nanoseconds: 100_000_000)
await MainActor.run {
guard needsResume else { return }
guard !shouldClose else { return }
guard streamConfig != nil else { return }
needsResume = false
hasPerformedTeardown = false
viewModel.activelyStreaming = true
startStreamIfNeeded()
}
}
default:
break
}
}
func animateOpening() {
Task {
self.animationTimer = Timer.scheduledTimer(withTimeInterval: 0.04, repeats: true) { _ in
Task { @MainActor in
if self.curveAnimationMultiplier < 1 {
self.curveAnimationMultiplier = min(self.curveAnimationMultiplier + 0.01, 1)
} else {
self.animationTimer?.invalidate(); self.animationTimer = nil
}
}
}
self.animationTimer?.fire()
}
}
private func loadRealityKitSettings() {
let defaults = UserDefaults.standard
if let savedHeight = defaults.object(forKey: "realitykitHeight") as? Float { height = savedHeight }
if let savedDepthOffset = defaults.object(forKey: "realitykitDepthOffset") as? Float { depthOffset = savedDepthOffset }
if let savedScale = defaults.object(forKey: "realitykitImmersiveScale") as? Float { immersiveScale = savedScale }
if let savedPosX = defaults.object(forKey: "realitykitImmersivePosX") as? Float,
let savedPosY = defaults.object(forKey: "realitykitImmersivePosY") as? Float,
let savedPosZ = defaults.object(forKey: "realitykitImmersivePosZ") as? Float {
immersivePosition = SIMD3<Float>(savedPosX, savedPosY, savedPosZ)
}
if let savedImmersion = defaults.object(forKey: "realitykitImmersionAmount") as? Float { immersionAmount = savedImmersion }
if let savedGamma = defaults.object(forKey: "realitykitGamma") as? Float { viewModel.streamSettings.gamma = savedGamma }
if let savedSat = defaults.object(forKey: "realitykitSaturation") as? Float { viewModel.streamSettings.saturation = savedSat }
// Load pinned screen settings
if let savedPinnedScale = defaults.object(forKey: "realitykitPinnedStageScale") as? Float {
pinnedStageScale = savedPinnedScale
controlState.pinnedStageScale = savedPinnedScale
}
if let savedPinnedHeight = defaults.object(forKey: "realitykitPinnedStageHeight") as? Float {
controlState.pinnedStageHeight = savedPinnedHeight
}
}
private func saveRealityKitSettings() {
guard viewModel.streamSettings.rememberStreamSettings else { return }
let defaults = UserDefaults.standard
defaults.set(viewModel.streamSettings.gamma, forKey: "realitykitGamma")
defaults.set(viewModel.streamSettings.saturation, forKey: "realitykitSaturation")
defaults.set(height, forKey: "realitykitHeight")
defaults.set(depthOffset, forKey: "realitykitDepthOffset")
// Use controlState values for immersive mode, local values for non-immersive mode
if isImmersive {
defaults.set(controlState.immersiveScale, forKey: "realitykitImmersiveScale")
defaults.set(controlState.immersivePositionX, forKey: "realitykitImmersivePosX")
defaults.set(controlState.immersivePositionY, forKey: "realitykitImmersivePosY")
defaults.set(controlState.immersivePositionZ, forKey: "realitykitImmersivePosZ")
defaults.set(controlState.immersionAmount, forKey: "realitykitImmersionAmount")
} else {
defaults.set(immersiveScale, forKey: "realitykitImmersiveScale")
defaults.set(immersivePosition.x, forKey: "realitykitImmersivePosX")
defaults.set(immersivePosition.y, forKey: "realitykitImmersivePosY")
defaults.set(immersivePosition.z, forKey: "realitykitImmersivePosZ")
defaults.set(immersionAmount, forKey: "realitykitImmersionAmount")
}
// Save pinned screen settings
defaults.set(controlState.pinnedStageScale, forKey: "realitykitPinnedStageScale")
defaults.set(controlState.pinnedStageHeight, forKey: "realitykitPinnedStageHeight")
}
// MARK: - View Components
@ViewBuilder
var environmentLoadingIndicator: some View {
VStack(spacing: 16) {
ProgressView()
.scaleEffect(1.5)
Text(viewModel.localized("loading_environment") ?? "正在加载环境...")
.font(.headline)
.foregroundStyle(.secondary)
}
.padding(30)
.background(.regularMaterial)