diff --git a/Day38/Day38.xcodeproj/project.pbxproj b/Day38/Day38.xcodeproj/project.pbxproj new file mode 100644 index 0000000..012da58 --- /dev/null +++ b/Day38/Day38.xcodeproj/project.pbxproj @@ -0,0 +1,363 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 56; + objects = { + +/* Begin PBXBuildFile section */ + 8E79CF882B8E4CB800659833 /* Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E79CF872B8E4CB800659833 /* Utilities.swift */; }; + 8ED0DE002B8E0CDA00E6EA95 /* Day38App.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ED0DDFF2B8E0CDA00E6EA95 /* Day38App.swift */; }; + 8ED0DE022B8E0CDA00E6EA95 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ED0DE012B8E0CDA00E6EA95 /* ContentView.swift */; }; + 8ED0DE042B8E0CDA00E6EA95 /* ImmersiveView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ED0DE032B8E0CDA00E6EA95 /* ImmersiveView.swift */; }; + 8ED0DE062B8E0CDB00E6EA95 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8ED0DE052B8E0CDB00E6EA95 /* Assets.xcassets */; }; + 8ED0DE092B8E0CDB00E6EA95 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 8ED0DE082B8E0CDB00E6EA95 /* Preview Assets.xcassets */; }; + 8ED0DE112B8E0D1B00E6EA95 /* ViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ED0DE102B8E0D1B00E6EA95 /* ViewModel.swift */; }; + 8ED0DE132B8E269500E6EA95 /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ED0DE122B8E269500E6EA95 /* AppState.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 8E79CF872B8E4CB800659833 /* Utilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Utilities.swift; sourceTree = ""; }; + 8ED0DDF82B8E0CDA00E6EA95 /* Day38.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Day38.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 8ED0DDFF2B8E0CDA00E6EA95 /* Day38App.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Day38App.swift; sourceTree = ""; }; + 8ED0DE012B8E0CDA00E6EA95 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; + 8ED0DE032B8E0CDA00E6EA95 /* ImmersiveView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImmersiveView.swift; sourceTree = ""; }; + 8ED0DE052B8E0CDB00E6EA95 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 8ED0DE082B8E0CDB00E6EA95 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; + 8ED0DE0A2B8E0CDB00E6EA95 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 8ED0DE102B8E0D1B00E6EA95 /* ViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewModel.swift; sourceTree = ""; }; + 8ED0DE122B8E269500E6EA95 /* AppState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppState.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 8ED0DDF52B8E0CDA00E6EA95 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 8ED0DDEF2B8E0CDA00E6EA95 = { + isa = PBXGroup; + children = ( + 8ED0DDFA2B8E0CDA00E6EA95 /* Day38 */, + 8ED0DDF92B8E0CDA00E6EA95 /* Products */, + ); + sourceTree = ""; + }; + 8ED0DDF92B8E0CDA00E6EA95 /* Products */ = { + isa = PBXGroup; + children = ( + 8ED0DDF82B8E0CDA00E6EA95 /* Day38.app */, + ); + name = Products; + sourceTree = ""; + }; + 8ED0DDFA2B8E0CDA00E6EA95 /* Day38 */ = { + isa = PBXGroup; + children = ( + 8ED0DDFF2B8E0CDA00E6EA95 /* Day38App.swift */, + 8ED0DE122B8E269500E6EA95 /* AppState.swift */, + 8ED0DE012B8E0CDA00E6EA95 /* ContentView.swift */, + 8ED0DE032B8E0CDA00E6EA95 /* ImmersiveView.swift */, + 8ED0DE102B8E0D1B00E6EA95 /* ViewModel.swift */, + 8E79CF872B8E4CB800659833 /* Utilities.swift */, + 8ED0DE052B8E0CDB00E6EA95 /* Assets.xcassets */, + 8ED0DE0A2B8E0CDB00E6EA95 /* Info.plist */, + 8ED0DE072B8E0CDB00E6EA95 /* Preview Content */, + ); + path = Day38; + sourceTree = ""; + }; + 8ED0DE072B8E0CDB00E6EA95 /* Preview Content */ = { + isa = PBXGroup; + children = ( + 8ED0DE082B8E0CDB00E6EA95 /* Preview Assets.xcassets */, + ); + path = "Preview Content"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 8ED0DDF72B8E0CDA00E6EA95 /* Day38 */ = { + isa = PBXNativeTarget; + buildConfigurationList = 8ED0DE0D2B8E0CDB00E6EA95 /* Build configuration list for PBXNativeTarget "Day38" */; + buildPhases = ( + 8ED0DDF42B8E0CDA00E6EA95 /* Sources */, + 8ED0DDF52B8E0CDA00E6EA95 /* Frameworks */, + 8ED0DDF62B8E0CDA00E6EA95 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Day38; + packageProductDependencies = ( + ); + productName = Day38; + productReference = 8ED0DDF82B8E0CDA00E6EA95 /* Day38.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 8ED0DDF02B8E0CDA00E6EA95 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1520; + LastUpgradeCheck = 1520; + TargetAttributes = { + 8ED0DDF72B8E0CDA00E6EA95 = { + CreatedOnToolsVersion = 15.2; + }; + }; + }; + buildConfigurationList = 8ED0DDF32B8E0CDA00E6EA95 /* Build configuration list for PBXProject "Day38" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 8ED0DDEF2B8E0CDA00E6EA95; + productRefGroup = 8ED0DDF92B8E0CDA00E6EA95 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 8ED0DDF72B8E0CDA00E6EA95 /* Day38 */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 8ED0DDF62B8E0CDA00E6EA95 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8ED0DE092B8E0CDB00E6EA95 /* Preview Assets.xcassets in Resources */, + 8ED0DE062B8E0CDB00E6EA95 /* Assets.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 8ED0DDF42B8E0CDA00E6EA95 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 8E79CF882B8E4CB800659833 /* Utilities.swift in Sources */, + 8ED0DE022B8E0CDA00E6EA95 /* ContentView.swift in Sources */, + 8ED0DE132B8E269500E6EA95 /* AppState.swift in Sources */, + 8ED0DE002B8E0CDA00E6EA95 /* Day38App.swift in Sources */, + 8ED0DE112B8E0D1B00E6EA95 /* ViewModel.swift in Sources */, + 8ED0DE042B8E0CDA00E6EA95 /* ImmersiveView.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 8ED0DE0B2B8E0CDB00E6EA95 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = xros; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + XROS_DEPLOYMENT_TARGET = 1.0; + }; + name = Debug; + }; + 8ED0DE0C2B8E0CDB00E6EA95 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = xros; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + XROS_DEPLOYMENT_TARGET = 1.0; + }; + name = Release; + }; + 8ED0DE0E2B8E0CDB00E6EA95 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_ASSET_PATHS = "\"Day38/Preview Content\""; + DEVELOPMENT_TEAM = 247V527KAQ; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = "$(TARGET_NAME)/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = tokyo.shmdevelopment.Day38; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "xros xrsimulator"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2,7"; + }; + name = Debug; + }; + 8ED0DE0F2B8E0CDB00E6EA95 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_ASSET_PATHS = "\"Day38/Preview Content\""; + DEVELOPMENT_TEAM = 247V527KAQ; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = "$(TARGET_NAME)/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = tokyo.shmdevelopment.Day38; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "xros xrsimulator"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2,7"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 8ED0DDF32B8E0CDA00E6EA95 /* Build configuration list for PBXProject "Day38" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8ED0DE0B2B8E0CDB00E6EA95 /* Debug */, + 8ED0DE0C2B8E0CDB00E6EA95 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 8ED0DE0D2B8E0CDB00E6EA95 /* Build configuration list for PBXNativeTarget "Day38" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 8ED0DE0E2B8E0CDB00E6EA95 /* Debug */, + 8ED0DE0F2B8E0CDB00E6EA95 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 8ED0DDF02B8E0CDA00E6EA95 /* Project object */; +} diff --git a/Day38/Day38.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Day38/Day38.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/Day38/Day38.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Day38/Day38.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Day38/Day38.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/Day38/Day38.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Day38/Day38.xcodeproj/xcshareddata/xcschemes/Day38.xcscheme b/Day38/Day38.xcodeproj/xcshareddata/xcschemes/Day38.xcscheme new file mode 100644 index 0000000..ca0111a --- /dev/null +++ b/Day38/Day38.xcodeproj/xcshareddata/xcschemes/Day38.xcscheme @@ -0,0 +1,84 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Day38/Day38/AppState.swift b/Day38/Day38/AppState.swift new file mode 100644 index 0000000..bbeca5f --- /dev/null +++ b/Day38/Day38/AppState.swift @@ -0,0 +1,77 @@ +import ARKit + +@Observable +class AppState { + + var immersiveSpaceOpened: Bool { viewModel != nil } + private(set) weak var viewModel: ViewModel? = nil + + func immersiveSpaceOpened(with viewModel: ViewModel) { + self.viewModel = viewModel + } + + func didLeaveImmersiveSpace() { + if viewModel != nil { + arkitSession.stop() + } + viewModel = nil + } + + // MARK: - ARKit state + + var arkitSession = ARKitSession() + var providersStoppedWithError = false + var worldSensingAuthorizationStatus = ARKitSession.AuthorizationStatus.notDetermined + + var allRequiredAuthorizationsAreGranted: Bool { + worldSensingAuthorizationStatus == .allowed + } + + var allRequiredProvidersAreSupported: Bool { + WorldTrackingProvider.isSupported + } + + var canEnterImmersiveSpace: Bool { + allRequiredAuthorizationsAreGranted && allRequiredProvidersAreSupported + } + + func requestWorldSensingAuthorization() async { + let authorizationResult = await arkitSession.requestAuthorization(for: [.worldSensing]) + worldSensingAuthorizationStatus = authorizationResult[.worldSensing]! + } + + func queryWorldSensingAuthorization() async { + let authorizationResult = await arkitSession.queryAuthorization(for: [.worldSensing]) + worldSensingAuthorizationStatus = authorizationResult[.worldSensing]! + } + + func monitorSessionEvents() async { + for await event in arkitSession.events { + switch event { + case .dataProviderStateChanged(_, let newState, let error): + switch newState { + case .initialized: + break + case .running: + break + case .paused: + break + case .stopped: + if let error { + print("An error occurred: \(error)") + providersStoppedWithError = true + } + @unknown default: + break + } + case .authorizationChanged(let type, let status): + print("Authorization type \(type) changed to \(status)") + if type == .worldSensing { + worldSensingAuthorizationStatus = status + } + default: + print("An unknown event occured \(event)") + } + } + } +} diff --git a/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Back.solidimagestacklayer/Content.imageset/Contents.json b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Back.solidimagestacklayer/Content.imageset/Contents.json new file mode 100644 index 0000000..04056a5 --- /dev/null +++ b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Back.solidimagestacklayer/Content.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "idiom" : "vision", + "scale" : "2x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Back.solidimagestacklayer/Contents.json b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Back.solidimagestacklayer/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Back.solidimagestacklayer/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Contents.json b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Contents.json new file mode 100644 index 0000000..950af4d --- /dev/null +++ b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Contents.json @@ -0,0 +1,17 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "layers" : [ + { + "filename" : "Front.solidimagestacklayer" + }, + { + "filename" : "Middle.solidimagestacklayer" + }, + { + "filename" : "Back.solidimagestacklayer" + } + ] +} diff --git a/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Front.solidimagestacklayer/Content.imageset/Contents.json b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Front.solidimagestacklayer/Content.imageset/Contents.json new file mode 100644 index 0000000..04056a5 --- /dev/null +++ b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Front.solidimagestacklayer/Content.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "idiom" : "vision", + "scale" : "2x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Front.solidimagestacklayer/Contents.json b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Front.solidimagestacklayer/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Front.solidimagestacklayer/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Middle.solidimagestacklayer/Content.imageset/Contents.json b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Middle.solidimagestacklayer/Content.imageset/Contents.json new file mode 100644 index 0000000..04056a5 --- /dev/null +++ b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Middle.solidimagestacklayer/Content.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "idiom" : "vision", + "scale" : "2x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Middle.solidimagestacklayer/Contents.json b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Middle.solidimagestacklayer/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/Day38/Day38/Assets.xcassets/AppIcon.solidimagestack/Middle.solidimagestacklayer/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Day38/Day38/Assets.xcassets/Contents.json b/Day38/Day38/Assets.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/Day38/Day38/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Day38/Day38/ContentView.swift b/Day38/Day38/ContentView.swift new file mode 100644 index 0000000..bcdfb89 --- /dev/null +++ b/Day38/Day38/ContentView.swift @@ -0,0 +1,93 @@ +import SwiftUI + +struct ContentView: View { + + let appState: AppState + let immersiveSpaceIdentifier: String + + @Environment(\.openImmersiveSpace) private var openImmersiveSpace + @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace + @Environment(\.scenePhase) private var scenePhase + + var body: some View { + VStack { + if !appState.immersiveSpaceOpened { + Button("Enter") { + Task { + switch await openImmersiveSpace(id: immersiveSpaceIdentifier) { + case .opened: + break + case .error: + print("An error occurred when trying to open the immersive space \(immersiveSpaceIdentifier)") + case .userCancelled: + print("The user declined opening immersive space \(immersiveSpaceIdentifier)") + @unknown default: + break + } + } + } + .disabled(!appState.canEnterImmersiveSpace) + } else { + VStack { + Spacer() + + Button { + Task { + await appState.viewModel?.setupCubes() + } + } label: { + Label("Set Cubes", systemImage: "plus.circle") + .frame(minWidth: 200) + } + + Button { + Task { + await dismissImmersiveSpace() + appState.didLeaveImmersiveSpace() + } + } label: { + Label("Leave", systemImage: "xmark.circle") + .frame(minWidth: 200) + } + + Spacer() + } + } + } + .fixedSize() + .onChange(of: scenePhase, initial: true) { + print("Scene phase: \(scenePhase)") + if scenePhase == .active { + Task { + await appState.queryWorldSensingAuthorization() + } + } else { + if appState.immersiveSpaceOpened { + Task { + await dismissImmersiveSpace() + appState.didLeaveImmersiveSpace() + } + } + } + } + .onChange(of: appState.providersStoppedWithError, { _, providersStoppedWithError in + if providersStoppedWithError { + if appState.immersiveSpaceOpened { + Task { + await dismissImmersiveSpace() + appState.didLeaveImmersiveSpace() + } + } + appState.providersStoppedWithError = false + } + }) + .task { + if appState.allRequiredProvidersAreSupported { + await appState.requestWorldSensingAuthorization() + } + } + .task { + await appState.monitorSessionEvents() + } + } +} diff --git a/Day38/Day38/Day38App.swift b/Day38/Day38/Day38App.swift new file mode 100644 index 0000000..3179fde --- /dev/null +++ b/Day38/Day38/Day38App.swift @@ -0,0 +1,38 @@ +import SwiftUI + +@main +@MainActor +struct Day38App: App { + + @State private var appState = AppState() + + @Environment(\.dismissImmersiveSpace) private var dismissImmersiveSpace + @Environment(\.scenePhase) private var scenePhase + + var body: some SwiftUI.Scene { + WindowGroup { + ContentView( + appState: appState, + immersiveSpaceIdentifier: "ImmersiveSpace" + ) + } + .defaultSize(width: 360, height: 360) + .windowResizability(.contentSize) + + ImmersiveSpace(id: "ImmersiveSpace") { + ImmersiveView( + appState: appState + ) + } + .onChange(of: scenePhase, initial: true) { + if scenePhase != .active { + if appState.immersiveSpaceOpened { + Task { + await dismissImmersiveSpace() + appState.didLeaveImmersiveSpace() + } + } + } + } + } +} diff --git a/Day38/Day38/ImmersiveView.swift b/Day38/Day38/ImmersiveView.swift new file mode 100644 index 0000000..18c8a40 --- /dev/null +++ b/Day38/Day38/ImmersiveView.swift @@ -0,0 +1,32 @@ +import SwiftUI +import RealityKit + +@MainActor +struct ImmersiveView: View { + + let appState: AppState + + @State private var viewModel = ViewModel() + + var body: some View { + RealityView { content in + content.add(viewModel.setupContentEntity()) + viewModel.appState = appState + + Task { + await viewModel.runARKitSession() + } + } + .task { + await viewModel.processWorldAnchorUpdates() + } + .onAppear() { + print("Entering immersive space.") + appState.immersiveSpaceOpened(with: viewModel) + } + .onDisappear() { + print("Leaving immersive space.") + appState.didLeaveImmersiveSpace() + } + } +} diff --git a/Day38/Day38/Info.plist b/Day38/Day38/Info.plist new file mode 100644 index 0000000..ad40817 --- /dev/null +++ b/Day38/Day38/Info.plist @@ -0,0 +1,17 @@ + + + + + NSWorldSensingUsageDescription + Scan your environment to allow accurate object placement. + UIApplicationSceneManifest + + UIApplicationPreferredDefaultSceneSessionRole + UIWindowSceneSessionRoleApplication + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + + + diff --git a/Day38/Day38/Preview Content/Preview Assets.xcassets/Contents.json b/Day38/Day38/Preview Content/Preview Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/Day38/Day38/Preview Content/Preview Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Day38/Day38/Utilities.swift b/Day38/Day38/Utilities.swift new file mode 100644 index 0000000..48c12cc --- /dev/null +++ b/Day38/Day38/Utilities.swift @@ -0,0 +1,59 @@ +import RealityKit + +extension simd_float4x4 { + init(translation vector: SIMD3) { + self.init(SIMD4(1, 0, 0, 0), + SIMD4(0, 1, 0, 0), + SIMD4(0, 0, 1, 0), + SIMD4(vector.x, vector.y, vector.z, 1)) + } + + var translation: SIMD3 { + get { + columns.3.xyz + } + set { + self.columns.3 = [newValue.x, newValue.y, newValue.z, 1] + } + } + + var rotation: simd_quatf { + simd_quatf(rotationMatrix) + } + + var xAxis: SIMD3 { columns.0.xyz } + + var yAxis: SIMD3 { columns.1.xyz } + + var zAxis: SIMD3 { columns.2.xyz } + + var rotationMatrix: simd_float3x3 { + matrix_float3x3(xAxis, + yAxis, + zAxis) + } + + var gravityAligned: simd_float4x4 { + // Project the z-axis onto the horizontal plane and normalize to length 1. + let projectedZAxis: SIMD3 = [zAxis.x, 0.0, zAxis.z] + let normalizedZAxis = normalize(projectedZAxis) + + // Hardcode y-axis to point upward. + let gravityAlignedYAxis: SIMD3 = [0, 1, 0] + + let resultingXAxis = normalize(cross(gravityAlignedYAxis, normalizedZAxis)) + + return simd_matrix( + SIMD4(resultingXAxis.x, resultingXAxis.y, resultingXAxis.z, 0), + SIMD4(gravityAlignedYAxis.x, gravityAlignedYAxis.y, gravityAlignedYAxis.z, 0), + SIMD4(normalizedZAxis.x, normalizedZAxis.y, normalizedZAxis.z, 0), + columns.3 + ) + } +} + +extension SIMD4 { + var xyz: SIMD3 { + self[SIMD3(0, 1, 2)] + } +} diff --git a/Day38/Day38/ViewModel.swift b/Day38/Day38/ViewModel.swift new file mode 100644 index 0000000..e4bfe2b --- /dev/null +++ b/Day38/Day38/ViewModel.swift @@ -0,0 +1,178 @@ +import SwiftUI +import RealityKit +import ARKit + +@Observable +class ViewModel { + + var appState: AppState? = nil + + private let worldTracking = WorldTrackingProvider() + + private var rootEntity = Entity() + private var anchoredObjects: [UUID: Entity] = [:] + private var objectsBeingAnchored: [UUID: Entity] = [:] + private var worldAnchors: [UUID: WorldAnchor] = [:] + + private let boxSize: Float = 0.4 + + func getTargetEntity(name: String) -> Entity? { + return rootEntity.children.first { $0.name == name} + } + + func setupContentEntity() -> Entity { + clear() + return rootEntity + } + + func clear() { + if let entity = getTargetEntity(name: "notAnchored") { + entity.removeFromParent() + } + + if let entity = getTargetEntity(name: "anchored") { + entity.removeFromParent() + } + + anchoredObjects.removeAll() + objectsBeingAnchored.removeAll() + worldAnchors.removeAll() + } + + @MainActor + func setupCubes() async { + clear() + + let entity = makeCube(name: "notAnchored", posision: SIMD3(x: -0.6, y: 1, z: -2), color: .blue) + rootEntity.addChild(entity) + + let entity2 = makeCube(name: "anchored", posision: SIMD3(x: 0.6, y: 1, z: -2), color: .red) + entity2.addChild(makeText(text: "anchored")) + await attachObjectToWorldAnchor(entity2) + } + + private func makeCube(name: String, posision: SIMD3, color: UIColor) -> Entity { + let entity = ModelEntity( + mesh: .generateBox(size: boxSize, cornerRadius: 0), + materials: [SimpleMaterial(color: color, isMetallic: false)] + ) + + entity.name = name + entity.position = posision + entity.components.set(InputTargetComponent()) + entity.components.set(HoverEffectComponent()) + entity.generateCollisionShapes(recursive: true) + + return entity + } + + private func makeText(text: String) -> ModelEntity { + let fontSize: CGFloat = 0.06 + + let mesh = MeshResource.generateText( + text, + extrusionDepth: 0.001, + font: .systemFont(ofSize: fontSize), + containerFrame: CGRect(origin: .zero, size: CGSize(width: CGFloat(boxSize), height: CGFloat(boxSize))), + alignment: .center + ) + + let entity = ModelEntity( + mesh: mesh, + materials: [SimpleMaterial(color: .white, isMetallic: false)] + ) + + entity.position.x = -(boxSize / 2) + entity.position.y = -boxSize + Float(fontSize / 2) + entity.position.z = boxSize / 2 + 0.01 + + return entity + } + + // MARK: - ARKit and Anchor handlings + + @MainActor + func runARKitSession() async { + do { + try await appState!.arkitSession.run([worldTracking]) + } catch { + return + } + } + + @MainActor + func processWorldAnchorUpdates() async { + for await anchorUpdate in worldTracking.anchorUpdates { + process(anchorUpdate) + } + } + + @MainActor + func process(_ anchorUpdate: AnchorUpdate) { + let anchor = anchorUpdate.anchor + + if anchorUpdate.event != .removed { + worldAnchors[anchor.id] = anchor + } else { + worldAnchors.removeValue(forKey: anchor.id) + } + + switch anchorUpdate.event { + case .added: + if let objectBeingAnchored = objectsBeingAnchored[anchor.id] { + objectsBeingAnchored.removeValue(forKey: anchor.id) + anchoredObjects[anchor.id] = objectBeingAnchored + rootEntity.addChild(objectBeingAnchored) + } else { + if anchoredObjects[anchor.id] == nil { + Task { + //print("No object is attached to anchor \(anchor.id) - it can be deleted.") + await removeAnchorWithID(anchor.id) + } + } + } + fallthrough + case .updated: + let object = anchoredObjects[anchor.id] + object?.position = anchor.originFromAnchorTransform.translation + object?.orientation = anchor.originFromAnchorTransform.rotation + object?.isEnabled = anchor.isTracked + case .removed: + let object = anchoredObjects[anchor.id] + object?.removeFromParent() + anchoredObjects.removeValue(forKey: anchor.id) + } + } + + @MainActor + func attachObjectToWorldAnchor(_ object: Entity) async { + let anchor = WorldAnchor(originFromAnchorTransform: object.transformMatrix(relativeTo: nil)) + objectsBeingAnchored[anchor.id] = object + do { + try await worldTracking.addAnchor(anchor) + } catch { + if let worldTrackingError = error as? WorldTrackingProvider.Error, worldTrackingError.code == .worldAnchorLimitReached { + print( +""" +Unable to place object "\(object.name)". You’ve placed the maximum number of objects. +Remove old objects before placing new ones. +""" + ) + } else { + print("Failed to add world anchor \(anchor.id) with error: \(error).") + } + + objectsBeingAnchored.removeValue(forKey: anchor.id) + object.removeFromParent() + return + } + } + + func removeAnchorWithID(_ uuid: UUID) async { + do { + try await worldTracking.removeAnchor(forID: uuid) + } catch { + //print("Failed to delete world anchor \(uuid) with error \(error).") + } + } +}