Skip to content

Instantly share code, notes, and snippets.

@drewolbrich
Last active August 7, 2024 23:51
Show Gist options
  • Save drewolbrich/b058b65c6d3e71f7ac611d9a505902e5 to your computer and use it in GitHub Desktop.
Save drewolbrich/b058b65c6d3e71f7ac611d9a505902e5 to your computer and use it in GitHub Desktop.
A wrapper around iOS Entity/loadAsync(named:in:) and visionOS Entity(named:in:) async that works on both platforms
//
// Entity+LoadFileAsync.swift
//
// Created by Drew Olbrich on 8/4/23.
// Copyright © 2023 Lunar Skydiving LLC. All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import RealityKit
import Combine
extension Entity {
/// Loads an entity from a file in a bundle asynchronously.
///
/// Unlike `Entity(named:in:) async` or `Entity.loadAsync(named:in:)`, this method
/// works on both iOS and visionOS.
///
/// If `flattened` is true, the entity hierarchy in the file will be flattened into
/// a single `ModelEntity`.
@MainActor static func loadFileAsync(named name: String, in bundle: Bundle? = nil, flattened: Bool) async throws -> Entity {
if #available(iOS 18.0, visionOS 1.0, *) {
if flattened {
return try await ModelEntity(named: name, in: bundle)
} else {
return try await Entity(named: name, in: bundle)
}
} else {
// The RealityKit `Entity(named:in:) async` initializer isn't available in iOS 17,
// so we implement our own replacement and wrap both implementations in
// `Entity/loadFileAsync(named:in:)`.
let entity: Entity = try await withCheckedThrowingContinuation { continuation in
func loadAsync<T: Entity>(with loadRequest: LoadRequest<T>) {
var cancellable: AnyCancellable?
cancellable = loadRequest.sink(receiveCompletion: { completion in
switch completion {
case .finished:
break
case .failure(let error):
continuation.resume(throwing: error)
}
cancellable?.cancel()
}, receiveValue: { entity in
continuation.resume(returning: entity)
cancellable?.cancel()
})
}
if flattened {
loadAsync(with: Entity.loadModelAsync(named: name, in: bundle))
} else {
loadAsync(with: Entity.loadAsync(named: name, in: bundle))
}
}
#if DEBUG
await entity.apply(recursive: true) { entity async in
if let modelEntity = entity as? ModelEntity {
// On iOS 17, RealityKit doesn't appear to be able to read USD files that contain
// primitive types like boxes. USD files must contain polygons.
assert(modelEntity.model != nil)
}
}
#endif
#if !os(visionOS)
// On iOS 17 and earlier, `Entity.loadModelAsync` doesn't assign a name to
// flattened entities. For consistency with visionOS, we assign the name.
if flattened {
assert(entity.name == "")
entity.name = name
}
#endif
return entity
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment