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
|
// Copyright (C) 2024 Apple Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
#if os(visionOS)
import Combine
import Foundation
@_spi(RealityKit) import RealityKit
import WebKitSwift
import os
import simd
private extension Logger {
static let realityKitEntity = Logger(subsystem: "com.apple.WebKit", category: "RealityKitEntity")
}
@objc(WKSRKEntity)
public final class WKSRKEntity: NSObject {
let entity: Entity
@objc(delegate) weak var delegate: WKSRKEntityDelegate?
private var animationPlaybackController: AnimationPlaybackController? = nil
private var animationFinishedSubscription: Cancellable?
private var _duration: TimeInterval? = nil
private var _playbackRate: Float = 1.0
@objc(isLoadFromDataAvailable) public static func isLoadFromDataAvailable() -> Bool {
#if canImport(RealityKit, _version: 377)
return true
#else
return false
#endif
}
@objc(loadFromData:completionHandler:) public static func load(from data: Data, completionHandler: @MainActor @escaping (WKSRKEntity?) -> Void) {
#if canImport(RealityKit, _version: 377)
Task {
do {
let loadedEntity = try await Entity(fromData: data)
let result: WKSRKEntity = .init(with: loadedEntity)
await completionHandler(result)
} catch {
Logger.realityKitEntity.error("Failed to load entity from data")
await completionHandler(nil)
}
}
#else
Task {
await completionHandler(nil)
}
#endif
}
private init(with rkEntity: Entity) {
self.entity = rkEntity
}
@objc(initWithCoreEntity:) init(with coreEntity: REEntityRef) {
entity = Entity.__fromCore(__EntityRef.__fromCore(coreEntity))
}
@objc(name) public var name: String {
get {
entity.name
}
set {
entity.name = newValue
}
}
@objc(boundingBoxExtents) public var boundingBoxExtents: simd_float3 {
guard let boundingBox = self.boundingBox else { return SIMD3<Float>(0, 0, 0) }
return boundingBox.extents
}
@objc(boundingBoxCenter) public var boundingBoxCenter: simd_float3 {
guard let boundingBox = self.boundingBox else { return SIMD3<Float>(0, 0, 0) }
return boundingBox.center
}
private var boundingBox: BoundingBox? {
entity.visualBounds(relativeTo: entity)
}
@objc(transform) public var transform: WKEntityTransform {
get {
guard let transformComponent = entity.components[Transform.self] else {
Logger.realityKitEntity.error("No transform component available from entity")
return WKEntityTransform(scale: simd_float3.one, rotation: simd_quatf(ix: 0, iy: 0, iz: 0, r: 1), translation: simd_float3.zero)
}
return WKEntityTransform(scale: transformComponent.scale, rotation: transformComponent.rotation, translation: transformComponent.translation)
}
set {
entity.components[Transform.self] = Transform(scale: newValue.scale, rotation: newValue.rotation, translation: newValue.translation)
}
}
@objc(opacity) public var opacity: Float {
get {
guard let opacityComponent = entity.components[OpacityComponent.self] else {
return 1.0
}
return opacityComponent.opacity
}
set {
let clampedValue = max(0, newValue)
if clampedValue >= 1.0 {
entity.components[OpacityComponent.self] = nil
return
}
entity.components[OpacityComponent.self] = OpacityComponent(opacity: clampedValue)
}
}
@objc(duration) public var duration: TimeInterval {
guard let _duration else { return 0 }
return _duration
}
@objc(loop) public var loop: Bool = false
@objc(playbackRate) public var playbackRate: Float {
get {
guard let animationPlaybackController else { return _playbackRate }
return animationPlaybackController.speed
}
set {
// FIXME (280081): Support negative playback rate
_playbackRate = max(newValue, 0);
guard let animationPlaybackController else { return }
animationPlaybackController.speed = _playbackRate
animationPlaybackStateDidUpdate()
}
}
@objc(paused) public var paused: Bool {
get {
guard let animationPlaybackController else { return true }
return animationPlaybackController.isPaused
}
set {
guard let animationPlaybackController, animationPlaybackController.isPaused != newValue else { return }
if newValue {
animationPlaybackController.pause()
} else {
animationPlaybackController.resume()
}
animationPlaybackStateDidUpdate()
}
}
@objc(currentTime) public var currentTime: TimeInterval {
get {
guard let animationPlaybackController else { return 0 }
return animationPlaybackController.time
}
set {
guard let animationPlaybackController, let duration = _duration else { return }
let clampedTime = min(max(newValue, 0), duration)
animationPlaybackController.time = clampedTime
animationPlaybackStateDidUpdate()
}
}
@objc(setUpAnimationWithAutoPlay:) public func setUpAnimation(with autoplay: Bool) {
assert(animationPlaybackController == nil)
guard let animation = entity.availableAnimations.first else {
Logger.realityKitEntity.info("No animation found in entity to play")
return
}
animationPlaybackController = entity.playAnimation(animation, startsPaused: !autoplay)
guard let animationPlaybackController else {
Logger.realityKitEntity.error("Cannot play entity animation")
return
}
_duration = animationPlaybackController.duration
animationPlaybackController.speed = _playbackRate
animationPlaybackStateDidUpdate()
guard let scene = entity.scene else {
Logger.realityKitEntity.error("No scene to subscribe for animation events")
return
}
animationFinishedSubscription = scene.subscribe(to: AnimationEvents.PlaybackCompleted.self, on: entity) { [weak self] event in
guard let self,
let playbackController = self.animationPlaybackController,
event.playbackController == playbackController else {
Logger.realityKitEntity.error("Cannot schedule the next animation")
return
}
let startsPaused = !self.loop
let animationController = self.entity.playAnimation(animation, startsPaused: startsPaused)
animationController.speed = self._playbackRate
self.animationPlaybackController = animationController
self.animationPlaybackStateDidUpdate()
}
}
@objc(applyIBLData:withCompletion:) public func applyIBL(data: Data, completion: @escaping (Bool) -> Void) {
#if canImport(RealityKit, _version: 366)
guard let imageSource = CGImageSourceCreateWithData(data as CFData, nil) else {
Logger.realityKitEntity.error("Cannot get CGImageSource from IBL image data")
completion(false)
return
}
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, 0, nil) else {
Logger.realityKitEntity.error("Cannot get CGImage from CGImageSource")
completion(false)
return
}
Task {
do {
let textureResource = try await TextureResource(cubeFromEquirectangular: cgImage, options: TextureResource.CreateOptions(semantic: .hdrColor))
let environment = try await EnvironmentResource(cube: textureResource, options: .init())
await MainActor.run {
entity.components[ImageBasedLightComponent.self] = .init(source: .single(environment))
entity.components[ImageBasedLightReceiverComponent.self] = .init(imageBasedLight: entity)
}
completion(true)
} catch {
Logger.realityKitEntity.error("Cannot load environment resource from CGImage")
completion(false)
}
}
#endif
}
@objc(removeIBL) public func removeIBL() {
entity.components[ImageBasedLightComponent.self] = .init(source: .none)
entity.components[ImageBasedLightReceiverComponent.self] = nil
}
private func animationPlaybackStateDidUpdate() {
delegate?.entityAnimationPlaybackStateDidUpdate?(self)
}
@objc(setParentCoreEntity:) public func setParent(_ coreEntity: REEntityRef) {
let parentEntity = Entity.__fromCore(__EntityRef.__fromCore(coreEntity))
entity.setParent(parentEntity)
}
}
#endif // os(visionOS)
|