This commit is contained in:
yuqucheng 2026-06-23 09:54:30 +08:00
commit fa7c338ea5
4303 changed files with 7880937 additions and 0 deletions

32
Classes/CrashReporter.h Normal file
View File

@ -0,0 +1,32 @@
#pragma once
// Enabling this will force app to do a hard crash instead of a nice exit when UnhandledException
// is thrown. This will force iOS to generate a standard crash report, that can be submitted to
// iTunes by app users and inspected by developers.
#define ENABLE_IOS_CRASH_REPORTING 1
// Enabling this will add a custom Objective-C Uncaught Exception handler, which will print out
// exception information to console.
#define ENABLE_OBJC_UNCAUGHT_EXCEPTION_HANDLER 1
// Enable custom crash reporter to capture crashes. Crash logs will be available to scripts via
// CrashReport API.
#define ENABLE_CUSTOM_CRASH_REPORTER 0
// Enable submission of custom crash reports to Unity servers. This will enable custom crash
// reporter.
#define ENABLE_CRASH_REPORT_SUBMISSION 0
#if ENABLE_CRASH_REPORT_SUBMISSION && !ENABLE_CUSTOM_CRASH_REPORTER
#undef ENABLE_CUSTOM_CRASH_REPORTER
#define ENABLE_CUSTOM_CRASH_REPORTER 0
#endif
#if PLATFORM_TVOS
#undef ENABLE_CUSTOM_CRASH_REPORTER
#define ENABLE_CUSTOM_CRASH_REPORTER 0
#endif
extern "C" void UnityInstallPostCrashCallback();
void InitCrashHandling();

108
Classes/CrashReporter.mm Normal file
View File

@ -0,0 +1,108 @@
#import "PLCrashReporter.h"
#import "CrashReporter.h"
#include "UndefinePlatforms.h"
#include <mach-o/ldsyms.h>
#include "RedefinePlatforms.h"
extern "C" NSString* UnityGetCrashReportsPath();
static NSUncaughtExceptionHandler* gsCrashReporterUEHandler = NULL;
static decltype(_mh_execute_header) * sExecuteHeader = NULL;
extern "C" void UnitySetExecuteMachHeader(const decltype(_mh_execute_header)* header)
{
sExecuteHeader = header;
}
extern "C" const decltype(_mh_execute_header) * UnityGetExecuteMachHeader() {
return sExecuteHeader;
}
static void SavePendingCrashReport()
{
if (![[UnityPLCrashReporter sharedReporter] hasPendingCrashReport])
return;
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error;
if (![fm createDirectoryAtPath: UnityGetCrashReportsPath() withIntermediateDirectories: YES attributes: nil error: &error])
{
::printf("CrashReporter: could not create crash report directory: %s\n", [[error localizedDescription] UTF8String]);
return;
}
NSData *data = [[UnityPLCrashReporter sharedReporter] loadPendingCrashReportDataAndReturnError: &error];
if (data == nil)
{
::printf("CrashReporter: failed to load crash report data: %s\n", [[error localizedDescription] UTF8String]);
return;
}
NSString* file = [UnityGetCrashReportsPath() stringByAppendingPathComponent: @"crash-"];
unsigned long long seconds = (unsigned long long)[[NSDate date] timeIntervalSince1970];
file = [file stringByAppendingString: [NSString stringWithFormat: @"%llu", seconds]];
file = [file stringByAppendingString: @".plcrash"];
if ([data writeToFile: file atomically: YES])
{
::printf("CrashReporter: saved pending crash report.\n");
if (![[UnityPLCrashReporter sharedReporter] purgePendingCrashReportAndReturnError: &error])
{
::printf("CrashReporter: couldn't remove pending report: %s\n", [[error localizedDescription] UTF8String]);
}
}
else
{
::printf("CrashReporter: couldn't save crash report.\n");
}
// Now copy out a pending version that we can delete if/when we send it
file = [UnityGetCrashReportsPath() stringByAppendingPathComponent: @"crash-pending.plcrash"];
if ([data writeToFile: file atomically: YES])
{
::printf("CrashReporter: saved copy of pending crash report.\n");
}
else
{
::printf("CrashReporter: couldn't save copy of pending crash report.\n");
}
}
static void InitCrashReporter()
{
NSError *error;
UnityInstallPostCrashCallback();
if ([[UnityPLCrashReporter sharedReporter] enableCrashReporterAndReturnError: &error])
::printf("CrashReporter: initialized\n");
else
NSLog(@"CrashReporter: could not enable crash reporter: %@", error);
SavePendingCrashReport();
}
static void UncaughtExceptionHandler(NSException *exception)
{
NSLog(@"Uncaught exception: %@: %@\n%@", [exception name], [exception reason], [exception callStackSymbols]);
if (gsCrashReporterUEHandler)
gsCrashReporterUEHandler(exception);
}
static void InitObjCUEHandler()
{
// Crash reporter sets its own handler, so we have to save it and call it manually
gsCrashReporterUEHandler = NSGetUncaughtExceptionHandler();
NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
}
void InitCrashHandling()
{
#if ENABLE_CUSTOM_CRASH_REPORTER
InitCrashReporter();
#endif
#if ENABLE_OBJC_UNCAUGHT_EXCEPTION_HANDLER
InitObjCUEHandler();
#endif
}

102
Classes/PLCrashReporter.h Normal file
View File

@ -0,0 +1,102 @@
/*
* Author: Landon Fuller <landonf@plausiblelabs.com>
*
* Copyright (c) 2008-2009 Plausible Labs Cooperative, Inc.
* All rights reserved.
*
* 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/Foundation.h>
/**
* @ingroup functions
*
* Prototype of a callback function used to execute additional user code with signal information as provided
* by PLCrashReporter. Called upon completion of crash handling, after the crash report has been written to disk.
*
* @param info The signal info.
* @param uap The crash's threads context.
* @param context The API client's supplied context value.
*
* @sa @ref async_safety
* @sa PLCrashReporter::setPostCrashCallbacks:
*/
typedef void (*UnityPLCrashReporterPostCrashSignalCallback)(siginfo_t *info, ucontext_t *uap, void *context);
/**
* @ingroup types
*
* This structure contains callbacks supported by PLCrashReporter to allow the host application to perform
* additional tasks prior to program termination after a crash has occured.
*
* @sa @ref async_safety
*/
typedef struct UnityPLCrashReporterCallbacks
{
/** The version number of this structure. If not one of the defined version numbers for this type, the behavior
* is undefined. The current version of this structure is 0. */
uint16_t version;
/** An arbitrary user-supplied context value. This value may be NULL. */
void *context;
/** The callback used to report caught signal information. In version 0 of this structure, all crashes will be
* reported via this function. */
UnityPLCrashReporterPostCrashSignalCallback handleSignal;
} UnityPLCrashReporterCallbacks;
@interface UnityPLCrashReporter : NSObject
{
@private
/** YES if the crash reporter has been enabled */
BOOL _enabled;
/** Application identifier */
NSString *_applicationIdentifier;
/** Application version */
NSString *_applicationVersion;
/** Path to the crash reporter internal data directory */
NSString *_crashReportDirectory;
}
+ (UnityPLCrashReporter *)sharedReporter;
- (BOOL)hasPendingCrashReport;
- (NSData *)loadPendingCrashReportData;
- (NSData *)loadPendingCrashReportDataAndReturnError:(NSError **)outError;
- (NSData *)generateLiveReport;
- (NSData *)generateLiveReportAndReturnError:(NSError **)outError;
- (BOOL)purgePendingCrashReport;
- (BOOL)purgePendingCrashReportAndReturnError:(NSError **)outError;
- (BOOL)enableCrashReporter;
- (BOOL)enableCrashReporterAndReturnError:(NSError **)outError;
- (void)setCrashCallbacks:(UnityPLCrashReporterCallbacks *)callbacks;
@end

View File

@ -0,0 +1,39 @@
#pragma once
#include "LifeCycleListener.h"
@protocol AppDelegateListener<LifeCycleListener>
@optional
// these do not have apple defined notifications, so we use our own notifications
// notification will be posted from
// - (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
// notification user data is the NSDictionary containing all the params
- (void)onOpenURL:(NSNotification*)notification;
// notification will be posted from
// - (BOOL)application:(UIApplication*)application willFinishLaunchingWithOptions:(NSDictionary*)launchOptions
// notification user data is the NSDictionary containing launchOptions
- (void)applicationWillFinishLaunchingWithOptions:(NSNotification*)notification;
// notification will be posted from
// - (void)application:(UIApplication*)application handleEventsForBackgroundURLSession:(nonnull NSString *)identifier completionHandler:(nonnull void (^)())completionHandler
// notification user data is NSDictionary with one item where key is session identifier and value is completion handler
- (void)onHandleEventsForBackgroundURLSession:(NSNotification*)notification;
// these are just hooks to existing notifications
- (void)applicationDidReceiveMemoryWarning:(NSNotification*)notification;
- (void)applicationSignificantTimeChange:(NSNotification*)notification;
- (void)applicationWillChangeStatusBarFrame:(NSNotification*)notification;
- (void)applicationWillChangeStatusBarOrientation:(NSNotification*)notification;
@end
void UnityRegisterAppDelegateListener(id<AppDelegateListener> obj);
void UnityUnregisterAppDelegateListener(id<AppDelegateListener> obj);
extern "C" __attribute__((visibility("default"))) NSString* const kUnityDidRegisterForRemoteNotificationsWithDeviceToken;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityDidFailToRegisterForRemoteNotificationsWithError;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityDidReceiveRemoteNotification;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityOnOpenURL;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityWillFinishLaunchingWithOptions;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityHandleEventsForBackgroundURLSession;

View File

@ -0,0 +1,53 @@
#include "AppDelegateListener.h"
#define DEFINE_NOTIFICATION(name) extern "C" __attribute__((visibility ("default"))) NSString* const name = @#name;
DEFINE_NOTIFICATION(kUnityDidRegisterForRemoteNotificationsWithDeviceToken);
DEFINE_NOTIFICATION(kUnityDidFailToRegisterForRemoteNotificationsWithError);
DEFINE_NOTIFICATION(kUnityDidReceiveRemoteNotification);
DEFINE_NOTIFICATION(kUnityOnOpenURL);
DEFINE_NOTIFICATION(kUnityWillFinishLaunchingWithOptions);
DEFINE_NOTIFICATION(kUnityHandleEventsForBackgroundURLSession);
#undef DEFINE_NOTIFICATION
void UnityRegisterAppDelegateListener(id<AppDelegateListener> obj)
{
#define REGISTER_SELECTOR(sel, notif_name) \
if([obj respondsToSelector:sel]) \
[[NSNotificationCenter defaultCenter] addObserver:obj \
selector:sel \
name:notif_name \
object:nil \
]; \
UnityRegisterLifeCycleListener(obj);
REGISTER_SELECTOR(@selector(onOpenURL:), kUnityOnOpenURL);
REGISTER_SELECTOR(@selector(applicationDidReceiveMemoryWarning:), UIApplicationDidReceiveMemoryWarningNotification);
REGISTER_SELECTOR(@selector(applicationSignificantTimeChange:), UIApplicationSignificantTimeChangeNotification);
#if !PLATFORM_TVOS && !PLATFORM_VISIONOS
REGISTER_SELECTOR(@selector(applicationWillChangeStatusBarFrame:), UIApplicationWillChangeStatusBarFrameNotification);
REGISTER_SELECTOR(@selector(applicationWillChangeStatusBarOrientation:), UIApplicationWillChangeStatusBarOrientationNotification);
#endif
REGISTER_SELECTOR(@selector(applicationWillFinishLaunchingWithOptions:), kUnityWillFinishLaunchingWithOptions);
REGISTER_SELECTOR(@selector(onHandleEventsForBackgroundURLSession:), kUnityHandleEventsForBackgroundURLSession);
#undef REGISTER_SELECTOR
}
void UnityUnregisterAppDelegateListener(id<AppDelegateListener> obj)
{
UnityUnregisterLifeCycleListener(obj);
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityOnOpenURL object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidReceiveMemoryWarningNotification object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationSignificantTimeChangeNotification object: nil];
#if !PLATFORM_TVOS && !PLATFORM_VISIONOS
[[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillChangeStatusBarFrameNotification object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillChangeStatusBarOrientationNotification object: nil];
#endif
}

View File

@ -0,0 +1,29 @@
#pragma once
// important app life-cycle events
@protocol LifeCycleListener<NSObject>
@optional
- (void)didFinishLaunching:(NSNotification*)notification;
- (void)didBecomeActive:(NSNotification*)notification;
- (void)willResignActive:(NSNotification*)notification;
- (void)didEnterBackground:(NSNotification*)notification;
- (void)willEnterForeground:(NSNotification*)notification;
- (void)willTerminate:(NSNotification*)notification;
- (void)unityDidUnload:(NSNotification*)notification;
- (void)unityDidQuit:(NSNotification*)notification;
@end
void UnityRegisterLifeCycleListener(id<LifeCycleListener> obj);
void UnityUnregisterLifeCycleListener(id<LifeCycleListener> obj);
#ifdef __cplusplus
extern "C" {
#endif
extern __attribute__((visibility("default"))) NSString* const kUnityDidUnload;
extern __attribute__((visibility("default"))) NSString* const kUnityDidQuit;
#ifdef __cplusplus
} // extern "C"
#endif

View File

@ -0,0 +1,39 @@
#include "LifeCycleListener.h"
#define DEFINE_NOTIFICATION(name) extern "C" __attribute__((visibility ("default"))) NSString* const name = @#name;
DEFINE_NOTIFICATION(kUnityDidUnload);
DEFINE_NOTIFICATION(kUnityDidQuit);
void UnityRegisterLifeCycleListener(id<LifeCycleListener> obj)
{
#define REGISTER_SELECTOR(sel, notif_name) \
if([obj respondsToSelector:sel]) \
[[NSNotificationCenter defaultCenter] addObserver:obj \
selector:sel \
name:notif_name \
object:nil \
]; \
REGISTER_SELECTOR(@selector(didFinishLaunching:), UIApplicationDidFinishLaunchingNotification);
REGISTER_SELECTOR(@selector(didBecomeActive:), UIApplicationDidBecomeActiveNotification);
REGISTER_SELECTOR(@selector(willResignActive:), UIApplicationWillResignActiveNotification);
REGISTER_SELECTOR(@selector(didEnterBackground:), UIApplicationDidEnterBackgroundNotification);
REGISTER_SELECTOR(@selector(willEnterForeground:), UIApplicationWillEnterForegroundNotification);
REGISTER_SELECTOR(@selector(willTerminate:), UIApplicationWillTerminateNotification);
REGISTER_SELECTOR(@selector(unityDidUnload:), kUnityDidUnload);
REGISTER_SELECTOR(@selector(unityDidQuit:), kUnityDidQuit);
#undef REGISTER_SELECTOR
}
void UnityUnregisterLifeCycleListener(id<LifeCycleListener> obj)
{
[[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidFinishLaunchingNotification object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidBecomeActiveNotification object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillResignActiveNotification object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationDidEnterBackgroundNotification object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillEnterForegroundNotification object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: UIApplicationWillTerminateNotification object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityDidUnload object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityDidQuit object: nil];
}

View File

@ -0,0 +1,68 @@
#pragma once
#include "LifeCycleListener.h"
struct UnityDisplaySurfaceBase; // Unity/UnityRendering.h
struct RenderingSurfaceParams; // Unity/DisplayManager.h
// due to delicate nature of render loop we have just one delegate in app
// if you need to use several rendering delegates you need to do one of:
// 1. create custom delegate that will have code to combine effects by itself
// 2. use helper that simply holds array of delegates (which will work only in easiest cases)
@protocol RenderPluginDelegate<LifeCycleListener, NSObject>
@required
// this will be called right after gles intialization.
// surface pointer will never be changed, so you should keep it.
// the only valid fields in there as of now are layer and context
- (void)mainDisplayInited:(struct UnityDisplaySurfaceBase*)surface;
@optional
// this will be called before recreating main display surface (from [UnityView recreateRenderingSurface])
// you can tweak params here.
// use it for enabling CVTextureCache support and the likes
- (void)onBeforeMainDisplaySurfaceRecreate:(struct RenderingSurfaceParams*)params;
// this will be called right after recreating main display surface (from [UnityView recreateRenderingSurface])
// as [UnityView recreateRenderingSurface] is the only place where unity itself will trigger surface recreate
// you can use this method to update your rendering depending on changes
- (void)onAfterMainDisplaySurfaceRecreate;
// this will be called after frame render and msaa resolve but before blitting to system FB
// you can expect that frame contents are ready (though still in target resolution)
// use it for anylizing/postprocessing rendered frame, taking screenshot and the like
// you should use targetFB if it is not 0
// otherwise use systemFB (covers case of intermediate fb not needed: no msaa, native res, no CVTextureCache involved)
- (void)onFrameResolved;
@end
// simple helper for common plugin stuff
// you can implement protocol directly, but subclassing this will provide some common implementation
@interface RenderPluginDelegate : NSObject<RenderPluginDelegate>
{
struct UnityDisplaySurfaceBase* mainDisplaySurface;
}
- (void)mainDisplayInited:(struct UnityDisplaySurfaceBase*)surface;
@end
// simple helper to have an array of render delegates.
// be warned that it works in simplest cases only, when there is no interop between delegates
@interface RenderPluginArrayDelegate : RenderPluginDelegate
{
NSArray* delegateArray;
}
@property(nonatomic, retain) NSArray* delegateArray;
- (void)mainDisplayInited:(struct UnityDisplaySurfaceBase*)surface;
- (void)onBeforeMainDisplaySurfaceRecreate:(struct RenderingSurfaceParams*)params;
- (void)onAfterMainDisplaySurfaceRecreate;
- (void)onFrameResolved;
- (void)didBecomeActive:(NSNotification*)notification;
- (void)willResignActive:(NSNotification*)notification;
- (void)didEnterBackground:(NSNotification*)notification;
- (void)willEnterForeground:(NSNotification*)notification;
- (void)willTerminate:(NSNotification*)notification;
@end

View File

@ -0,0 +1,90 @@
#include "RenderPluginDelegate.h"
@implementation RenderPluginDelegate
- (void)mainDisplayInited:(struct UnityDisplaySurfaceBase*)surface
{
mainDisplaySurface = surface;
// TODO: move lifecycle to init?
UnityRegisterLifeCycleListener(self);
}
@end
#define CALL_METHOD_ON_ARRAY(method) \
do{ \
for(id<RenderPluginDelegate> del in delegateArray) \
{ \
if([del respondsToSelector:@selector(method)]) \
[del method]; \
} \
} while(0)
#define CALL_METHOD_ON_ARRAY_ARG(method, arg) \
do{ \
for(id<RenderPluginDelegate> del in delegateArray) \
{ \
if([del respondsToSelector:@selector(method:)]) \
[del method:arg]; \
} \
} while(0)
@implementation RenderPluginArrayDelegate
@synthesize delegateArray;
- (void)mainDisplayInited:(struct UnityDisplaySurfaceBase*)surface
{
[super mainDisplayInited: surface];
CALL_METHOD_ON_ARRAY_ARG(mainDisplayInited, surface);
}
- (void)onBeforeMainDisplaySurfaceRecreate:(struct RenderingSurfaceParams*)params
{
CALL_METHOD_ON_ARRAY_ARG(onBeforeMainDisplaySurfaceRecreate, params);
}
- (void)onAfterMainDisplaySurfaceRecreate;
{
CALL_METHOD_ON_ARRAY(onAfterMainDisplaySurfaceRecreate);
}
- (void)onFrameResolved;
{
CALL_METHOD_ON_ARRAY(onFrameResolved);
}
- (void)didBecomeActive:(NSNotification*)notification
{
CALL_METHOD_ON_ARRAY_ARG(didBecomeActive, notification);
}
- (void)willResignActive:(NSNotification*)notification
{
CALL_METHOD_ON_ARRAY_ARG(willResignActive, notification);
}
- (void)didEnterBackground:(NSNotification*)notification
{
CALL_METHOD_ON_ARRAY_ARG(didEnterBackground, notification);
}
- (void)willEnterForeground:(NSNotification*)notification
{
CALL_METHOD_ON_ARRAY_ARG(willEnterForeground, notification);
}
- (void)willTerminate:(NSNotification*)notification
{
CALL_METHOD_ON_ARRAY_ARG(willTerminate, notification);
}
@end
#undef CALL_METHOD_ON_ARRAY
#undef CALL_METHOD_ON_ARRAY_ARG

View File

@ -0,0 +1,51 @@
#pragma once
#import <Foundation/NSNotification.h>
// view changes on the main view controller
@protocol UnityViewControllerListener<NSObject>
@optional
- (void)viewWillLayoutSubviews:(NSNotification*)notification;
- (void)viewDidLayoutSubviews:(NSNotification*)notification;
- (void)viewWillDisappear:(NSNotification*)notification;
- (void)viewDidDisappear:(NSNotification*)notification;
- (void)viewWillAppear:(NSNotification*)notification;
- (void)viewDidAppear:(NSNotification*)notification;
- (void)interfaceWillChangeOrientation:(NSNotification*)notification;
- (void)interfaceDidChangeOrientation:(NSNotification*)notification;
@end
@protocol UnityViewControllerNotifications<NSObject>
@optional
- (void)onViewWillLayoutSubviews;
- (void)onViewDidLayoutSubviews;
- (void)onViewDidDisappear:(BOOL)animated;
- (void)onViewWillDisappear:(BOOL)animated;
- (void)onViewDidAppear:(BOOL)animated;
- (void)onViewWillAppear:(BOOL)animated;
@end
// this default delegate will send notifications for UnityViewControllerListener
@interface UnityViewControllerNotificationsDefaultSender : NSObject<UnityViewControllerNotifications>
- (void)onViewWillLayoutSubviews;
- (void)onViewDidLayoutSubviews;
- (void)onViewDidDisappear:(BOOL)animated;
- (void)onViewWillDisappear:(BOOL)animated;
- (void)onViewDidAppear:(BOOL)animated;
- (void)onViewWillAppear:(BOOL)animated;
@end
void UnityRegisterViewControllerListener(id<UnityViewControllerListener> obj);
void UnityUnregisterViewControllerListener(id<UnityViewControllerListener> obj);
extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewWillLayoutSubviews;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewDidLayoutSubviews;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewWillDisappear;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewDidDisappear;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewWillAppear;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityViewDidAppear;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityInterfaceWillChangeOrientation;
extern "C" __attribute__((visibility("default"))) NSString* const kUnityInterfaceDidChangeOrientation;

View File

@ -0,0 +1,80 @@
#include "UnityViewControllerListener.h"
#include <UIKit/UIApplication.h>
#define DEFINE_NOTIFICATION(name) extern "C" __attribute__((visibility ("default"))) NSString* const name = @#name;
DEFINE_NOTIFICATION(kUnityViewWillLayoutSubviews);
DEFINE_NOTIFICATION(kUnityViewDidLayoutSubviews);
DEFINE_NOTIFICATION(kUnityViewWillDisappear);
DEFINE_NOTIFICATION(kUnityViewDidDisappear);
DEFINE_NOTIFICATION(kUnityViewWillAppear);
DEFINE_NOTIFICATION(kUnityViewDidAppear);
DEFINE_NOTIFICATION(kUnityInterfaceWillChangeOrientation);
DEFINE_NOTIFICATION(kUnityInterfaceDidChangeOrientation);
#undef DEFINE_NOTIFICATION
void UnityRegisterViewControllerListener(id<UnityViewControllerListener> obj)
{
#define REGISTER_SELECTOR(sel, notif_name) \
if([obj respondsToSelector:sel]) \
[[NSNotificationCenter defaultCenter] addObserver:obj selector:sel name:notif_name object:nil]; \
REGISTER_SELECTOR(@selector(viewWillLayoutSubviews:), kUnityViewWillLayoutSubviews);
REGISTER_SELECTOR(@selector(viewDidLayoutSubviews:), kUnityViewDidLayoutSubviews);
REGISTER_SELECTOR(@selector(viewWillDisappear:), kUnityViewWillDisappear);
REGISTER_SELECTOR(@selector(viewDidDisappear:), kUnityViewDidDisappear);
REGISTER_SELECTOR(@selector(viewWillAppear:), kUnityViewWillAppear);
REGISTER_SELECTOR(@selector(viewDidAppear:), kUnityViewDidAppear);
REGISTER_SELECTOR(@selector(interfaceWillChangeOrientation:), kUnityInterfaceWillChangeOrientation);
REGISTER_SELECTOR(@selector(interfaceDidChangeOrientation:), kUnityInterfaceDidChangeOrientation);
#undef REGISTER_SELECTOR
}
void UnityUnregisterViewControllerListener(id<UnityViewControllerListener> obj)
{
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewWillLayoutSubviews object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewDidLayoutSubviews object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewWillDisappear object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewDidDisappear object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewWillAppear object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityViewDidAppear object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityInterfaceWillChangeOrientation object: nil];
[[NSNotificationCenter defaultCenter] removeObserver: obj name: kUnityInterfaceDidChangeOrientation object: nil];
}
extern void AppController_SendUnityViewControllerNotification(NSString* name);
@implementation UnityViewControllerNotificationsDefaultSender
- (void)onViewWillLayoutSubviews
{
AppController_SendUnityViewControllerNotification(kUnityViewWillLayoutSubviews);
}
- (void)onViewDidLayoutSubviews
{
AppController_SendUnityViewControllerNotification(kUnityViewDidLayoutSubviews);
}
- (void)onViewDidDisappear:(BOOL)animated
{
AppController_SendUnityViewControllerNotification(kUnityViewDidDisappear);
}
- (void)onViewWillDisappear:(BOOL)animated
{
AppController_SendUnityViewControllerNotification(kUnityViewWillDisappear);
}
- (void)onViewDidAppear:(BOOL)animated
{
AppController_SendUnityViewControllerNotification(kUnityViewDidAppear);
}
- (void)onViewWillAppear:(BOOL)animated
{
AppController_SendUnityViewControllerNotification(kUnityViewWillAppear);
}
@end

27
Classes/Prefix.pch Normal file
View File

@ -0,0 +1,27 @@
//
// Prefix header
//
#include "Preprocessor.h"
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#endif
#include "UnityTrampolineConfigure.h"
#include "UnityInterface.h"
#ifndef __OBJC__
#if defined(__cplusplus)
#include "pch-cpp.hpp"
#else
#include "pch-c.h"
#endif
#endif
#ifndef TARGET_IPHONE_SIMULATOR
#define TARGET_IPHONE_SIMULATOR 0
#endif
#define printf_console printf

214
Classes/Preprocessor.h Normal file
View File

@ -0,0 +1,214 @@
#pragma once
#include <Availability.h>
#include <TargetConditionals.h>
//------------------------------------------------------------------------------
//
// ensuring proper compiler/xcode/whatever selection
//
#ifndef __clang__
#error Please use clang compiler.
#endif
#if __clang_major__ < 13
#error Please use Xcode 13.0 or newer
#endif
#if !defined(__IPHONE_15_0) || __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_15_0
#error Please use iOS SDK 15.0 or newer
#endif
#if defined(TARGET_OS_TV) && TARGET_OS_TV && !defined(__TVOS_15_0)
#error Please use tvOS SDK 15.0 or newer
#endif
#if TARGET_OS_IOS && (!defined(__IPHONE_12_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_12_0)
#error Please target iOS 12.0 or newer
#endif
#if TARGET_OS_TV && (!defined(__TVOS_12_0) || __TV_OS_VERSION_MIN_REQUIRED < __TVOS_12_0)
#error Please target tvOS 12.0 or newer
#endif
//------------------------------------------------------------------------------
//
// defines for target platform
//
#define UNITY_TRAMPOLINE_IN_USE 1
#if defined(TARGET_OS_VISION) && TARGET_OS_VISION
#define PLATFORM_IOS 1
#define PLATFORM_OSX 0
#define PLATFORM_TVOS 0
#define PLATFORM_VISIONOS 0
#elif defined(TARGET_OS_IOS) && TARGET_OS_IOS
#define PLATFORM_IOS 1
#define PLATFORM_OSX 0
#define PLATFORM_TVOS 0
#define PLATFORM_VISIONOS 0
#elif defined(TARGET_OS_OSX) && TARGET_OS_OSX
#define PLATFORM_IOS 1
#define PLATFORM_OSX 1
#define PLATFORM_TVOS 0
#define PLATFORM_VISIONOS 0
#elif defined(TARGET_OS_TV) && TARGET_OS_TV
#define PLATFORM_IOS 1
#define PLATFORM_OSX 0
#define PLATFORM_TVOS 0
#define PLATFORM_VISIONOS 0
#else
#error one of TARGET_OS_IOS, TARGET_OS_OSX, TARGET_OS_TV, TARGET_OS_VISION should be defined
#endif
//------------------------------------------------------------------------------
//
// defines for sdk/target version
//
// It's hard to figure out which SDK we are using as the availability macros defined in the SDK
// have various quirks.
//
// It's not possible to use *_VERSION_MAX_ALLOWED macros because they not always corresponded to
// the SDK version. In particular, __TV_OS_VERSION_MAX_ALLOWED was out of sync in all Xcode dot
// releases except the first so far.
//
// The highest __IPHONE_X_Y or __TVOS_X_Y macro that is defined in Availability.h correctly
// corresponds to the version of the SDK (at least in each Xcode version since 6.0 up to 9.0).
// However, some other headers (e.g. System/Library/Frameworks/QuartzCore.framework/Headers/CABase.h
// in SDKs up to 9.3) may define the macros itself and this does not correspond to the what's in
// Availability.h. Thus we make sure to include "Preprocessor.h" before the CABase.h header.
#if defined(CABASE_H)
#error "Please include Preprocessor.h before other includes"
#endif
#if defined(__IPHONE_10_0)
#define UNITY_HAS_IOSSDK_10_0 1
#else
#define UNITY_HAS_IOSSDK_10_0 0
#endif
#if defined(__IPHONE_10_2)
#define UNITY_HAS_IOSSDK_10_2 1
#else
#define UNITY_HAS_IOSSDK_10_2 0
#endif
#if defined(__IPHONE_10_3)
#define UNITY_HAS_IOSSDK_10_3 1
#else
#define UNITY_HAS_IOSSDK_10_3 0
#endif
#if defined(__IPHONE_11_0)
#define UNITY_HAS_IOSSDK_11_0 1
#else
#define UNITY_HAS_IOSSDK_11_0 0
#endif
#if defined(__IPHONE_11_1)
#define UNITY_HAS_IOSSDK_11_1 1
#else
#define UNITY_HAS_IOSSDK_11_1 0
#endif
#if defined(__IPHONE_12_0)
#define UNITY_HAS_IOSSDK_12_0 1
#else
#define UNITY_HAS_IOSSDK_12_0 0
#endif
#if defined(__IPHONE_13_0)
#define UNITY_HAS_IOSSDK_13_0 1
#else
#define UNITY_HAS_IOSSDK_13_0 0
#endif
#if defined(__IPHONE_14_0)
#define UNITY_HAS_IOSSDK_14_0 1
#else
#define UNITY_HAS_IOSSDK_14_0 0
#endif
#if defined(__IPHONE_15_0)
#define UNITY_HAS_IOSSDK_15_0 1
#else
#define UNITY_HAS_IOSSDK_15_0 0
#endif
#if defined(__TVOS_10_0)
#define UNITY_HAS_TVOSSDK_10_0 1
#else
#define UNITY_HAS_TVOSSDK_10_0 0
#endif
#if defined(__TVOS_10_2)
#define UNITY_HAS_TVOSSDK_10_2 1
#else
#define UNITY_HAS_TVOSSDK_10_2 0
#endif
#if defined(__TVOS_11_0)
#define UNITY_HAS_TVOSSDK_11_0 1
#else
#define UNITY_HAS_TVOSSDK_11_0 0
#endif
#if defined(__TVOS_12_0)
#define UNITY_HAS_TVOSSDK_12_0 1
#else
#define UNITY_HAS_TVOSSDK_12_0 0
#endif
#if defined(__TVOS_13_0)
#define UNITY_HAS_TVOSSDK_13_0 1
#else
#define UNITY_HAS_TVOSSDK_13_0 0
#endif
#if defined(__TVOS_14_0)
#define UNITY_HAS_TVOSSDK_14_0 1
#else
#define UNITY_HAS_TVOSSDK_14_0 0
#endif
#if defined(__TVOS_15_0)
#define UNITY_HAS_TVOSSDK_15_0 1
#else
#define UNITY_HAS_TVOSSDK_15_0 0
#endif
//------------------------------------------------------------------------------
//
// defines for used unity features
//
// The following UNITY_USES_* flags disable functionality in the trampoline project whenever the user does not use it from his scripts.
// We detect the API usage and adjust the value of these flags whenever the project is built (including "append")
#define UNITY_USES_REMOTE_NOTIFICATIONS 0
#define UNITY_USES_WEBCAM 1
#define UNITY_USES_MICROPHONE 0
#define UNITY_USES_REPLAY_KIT 0
#define UNITY_USES_DYNAMIC_PLAYER_LIB 0
#define UNITY_USES_LOCATION 1
#define UNITY_USES_GLES 0
#define UNITY_USES_IAD 0
//------------------------------------------------------------------------------
//
// defines for used features
//
#define UNITY_DEVELOPER_BUILD 1
#define USE_IL2CPP_PCH 0
#define UNITY_SNAPSHOT_VIEW_ON_APPLICATION_PAUSE 0
// we now support metal always everywhere, but we keep the define for native plugins using it
#define UNITY_CAN_USE_METAL 1
#define UNITY_SUPPORT_ROTATION PLATFORM_IOS
#if PLATFORM_TVOS
#define UNITY_TVOS_ORIENTATION landscapeLeft
#endif
#if PLATFORM_VISIONOS
#define UNITY_VISIONOS_ORIENTATION landscapeLeft
#endif
#if PLATFORM_IOS || PLATFORM_TVOS || PLATFORM_VISIONOS
#define UNITY_REPLAY_KIT_AVAILABLE UNITY_USES_REPLAY_KIT
#else
#define UNITY_REPLAY_KIT_AVAILABLE 0
#endif
// On tvOS simulator we implement a fake remote as tvOS simulator does not support controllers (yet)
#define UNITY_TVOS_SIMULATOR_FAKE_REMOTE (PLATFORM_TVOS && TARGET_TVOS_SIMULATOR)

118
Classes/Quaternion4.h Normal file
View File

@ -0,0 +1,118 @@
#pragma once
struct Quaternion4f
{
float x, y, z, w;
};
static Quaternion4f gQuatRot[4] =
{ // { x*sin(theta/2), y*sin(theta/2), z*sin(theta/2), cos(theta/2) }
// => { 0, 0, sin(theta/2), cos(theta/2) } (since <vec> = { 0, 0, +/-1})
{ 0.f, 0.f, 0.f /*sin(0)*/, 1.f /*cos(0)*/}, // ROTATION_0, theta = 0 rad
{ 0.f, 0.f, (float)sqrt(2) * 0.5f /*sin(pi/4)*/, -(float)sqrt(2) * 0.5f /*cos(pi/4)*/}, // ROTATION_90, theta = pi/4 rad
{ 0.f, 0.f, 1.f /*sin(pi/2)*/, 0.f /*cos(pi/2)*/}, // ROTATION_180, theta = pi rad
{ 0.f, 0.f, -(float)sqrt(2) * 0.5f /*sin(3pi/4)*/, -(float)sqrt(2) * 0.5f /*cos(3pi/4)*/} // ROTATION_270, theta = 3pi/2 rad
};
inline void QuatMultiply(Quaternion4f& result, const Quaternion4f& lhs, const Quaternion4f& rhs)
{
result.x = lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y;
result.y = lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z;
result.z = lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x;
result.w = lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z;
}
inline Quaternion4f QuatMultiply(const Quaternion4f& lhs, const Quaternion4f& rhs)
{
Quaternion4f output;
QuatMultiply(output, lhs, rhs);
return output;
}
inline Quaternion4f QuatMake(float x, float y, float z, float w)
{
Quaternion4f q = {x, y, z, w};
return q;
}
inline Quaternion4f QuatIdentity()
{
return gQuatRot[0];
}
inline Quaternion4f QuatScale(const Quaternion4f& q, float s)
{
return QuatMake(s * q.x, s * q.y, s * q.z, s * q.w);
}
inline float QuatNormSquared(const Quaternion4f& q)
{
return q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
}
inline Quaternion4f QuatConjugate(const Quaternion4f& q)
{
return QuatMake(-q.x, -q.y, -q.z, q.w);
}
inline Quaternion4f QuatInverse(const Quaternion4f& q)
{
return QuatScale(QuatConjugate(q), 1.0f / QuatNormSquared(q));
}
inline Vector3f QuatToEuler(const Quaternion4f& q)
{
return VecMake(
atan2f(2.0f * (q.w * q.y + q.x * q.z),
1.0f - 2.0f * (q.y * q.y + q.x * q.x)),
asinf(2.0f * (q.w * q.x - q.z * q.y)),
atan2f(2.0f * (q.w * q.z + q.y * q.x),
1.0f - 2.0f * (q.x * q.x + q.z * q.z)));
}
inline float QuatNorm(const Quaternion4f& q)
{
return sqrtf(QuatNormSquared(q));
}
inline Quaternion4f QuatNormalize(const Quaternion4f& q)
{
return QuatScale(q, 1.0f / QuatNorm(q));
}
inline Quaternion4f QuatDifference(const Quaternion4f& a, const Quaternion4f& b)
{
return QuatMultiply(QuatInverse(b), a);
}
inline Quaternion4f QuatRotationFromTo(const Vector3f& src, const Vector3f& dest)
{
// Based on Stan Melax's article in Game Programming Gems
float mag0 = VecMagnitude(src);
if (mag0 < FLT_EPSILON)
return QuatIdentity();
float mag1 = VecMagnitude(dest);
if (mag1 < FLT_EPSILON)
return QuatIdentity();
Vector3f v0 = VecScale(1.0f / mag0, src);
Vector3f v1 = VecScale(1.0f / mag1, dest);
float d = VecDotProduct(v0, v1);
// If dot == 1, vectors are the same
if (d >= (1.0f - 1e-6f))
return QuatIdentity();
if (d < (1e-6f - 1.0f))
return gQuatRot[2];
float s = sqrtf((1.0f + d) * 2.0f);
float i = 1.0f / s;
Vector3f c = VecCrossProduct(v0, v1);
return QuatNormalize(QuatMake(
c.x * i, c.y * i, c.z * i, s * 0.5f));
}

186
Classes/RedefinePlatforms.h Normal file
View File

@ -0,0 +1,186 @@
// DO NOT PUT #pragma once or include guard check here
// This header is designed to be able to be included multiple times
// This header is used to redefine platforms after they were temporary undefined by UndefinePlatforms.h
// Please make sure to always use this paired with the UndefinePlatforms.h header.
//
// ex.
//
// #include "UndefinePlatforms.h"
// #include "Some3rdParty.h"
// #include "RedefinePlatforms.h"
#ifndef DETAIL__PLATFORMS_HAD_BEEN_UNDEFINED_BY_UNDEFINEPLATFORMS_H
#error "RedefinePlatforms.h can only be used after UndefinePlatforms.h got included before."
#endif
#undef DETAIL__PLATFORMS_HAD_BEEN_UNDEFINED_BY_UNDEFINEPLATFORMS_H
// define all other platforms to 0
#undef PLATFORM_WIN
#if defined(DETAIL__TEMP_PLATFORM_WIN_WAS_1)
#undef DETAIL__TEMP_PLATFORM_WIN_WAS_1
#define PLATFORM_WIN 1
#else
#define PLATFORM_WIN 0
#endif
#undef PLATFORM_OSX
#if defined(DETAIL__TEMP_PLATFORM_OSX_WAS_1)
#undef DETAIL__TEMP_PLATFORM_OSX_WAS_1
#define PLATFORM_OSX 1
#else
#define PLATFORM_OSX 0
#endif
#undef PLATFORM_LINUX
#if defined(DETAIL__TEMP_PLATFORM_LINUX_WAS_1)
#undef DETAIL__TEMP_PLATFORM_LINUX_WAS_1
#define PLATFORM_LINUX 1
#else
#define PLATFORM_LINUX 0
#endif
#undef PLATFORM_WINRT
#if defined(DETAIL__TEMP_PLATFORM_WINRT_WAS_1)
#undef DETAIL__TEMP_PLATFORM_WINRT_WAS_1
#define PLATFORM_WINRT 1
#else
#define PLATFORM_WINRT 0
#endif
#undef PLATFORM_FAMILY_WINDOWSGAMES
#if defined(DETAIL__TEMP_PLATFORM_FAMILY_WINDOWSGAMES_WAS_1)
#undef DETAIL__TEMP_PLATFORM_FAMILY_WINDOWSGAMES_WAS_1
#define PLATFORM_FAMILY_WINDOWSGAMES 1
#else
#define PLATFORM_FAMILY_WINDOWSGAMES 0
#endif
#undef PLATFORM_WEBGL
#if defined(DETAIL__TEMP_PLATFORM_WEBGL_WAS_1)
#undef DETAIL__TEMP_PLATFORM_WEBGL_WAS_1
#define PLATFORM_WEBGL 1
#else
#define PLATFORM_WEBGL 0
#endif
#undef PLATFORM_WASI
#if defined(DETAIL__TEMP_PLATFORM_WASI_WAS_1)
#undef DETAIL__TEMP_PLATFORM_WASI_WAS_1
#define PLATFORM_WASI 1
#else
#define PLATFORM_WASI 0
#endif
#undef PLATFORM_ANDROID
#if defined(DETAIL__TEMP_PLATFORM_ANDROID_WAS_1)
#undef DETAIL__TEMP_PLATFORM_ANDROID_WAS_1
#define PLATFORM_ANDROID 1
#else
#define PLATFORM_ANDROID 0
#endif
#undef PLATFORM_PS4
#if defined(DETAIL__TEMP_PLATFORM_PS4_WAS_1)
#undef DETAIL__TEMP_PLATFORM_PS4_WAS_1
#define PLATFORM_PS4 1
#else
#define PLATFORM_PS4 0
#endif
#undef PLATFORM_PS5
#if defined(DETAIL__TEMP_PLATFORM_PS5_WAS_1)
#undef DETAIL__TEMP_PLATFORM_PS5_WAS_1
#define PLATFORM_PS5 1
#else
#define PLATFORM_PS5 0
#endif
#undef PLATFORM_IPHONE
#if defined(DETAIL__TEMP_PLATFORM_IPHONE_WAS_1)
#undef DETAIL__TEMP_PLATFORM_IPHONE_WAS_1
#define PLATFORM_IPHONE 1
#else
#define PLATFORM_IPHONE 0
#endif
#undef PLATFORM_IOS
#if defined(DETAIL__TEMP_PLATFORM_IOS_WAS_1)
#undef DETAIL__TEMP_PLATFORM_IOS_WAS_1
#define PLATFORM_IOS 1
#else
#define PLATFORM_IOS 0
#endif
#undef PLATFORM_TVOS
#if defined(DETAIL__TEMP_PLATFORM_TVOS_WAS_1)
#undef DETAIL__TEMP_PLATFORM_TVOS_WAS_1
#define PLATFORM_TVOS 1
#else
#define PLATFORM_TVOS 0
#endif
#undef PLATFORM_VISIONOS
#if defined(DETAIL__TEMP_PLATFORM_VISIONOS_WAS_1)
#undef DETAIL__TEMP_PLATFORM_VISIONOS_WAS_1
#define PLATFORM_VISIONOS 1
#else
#define PLATFORM_VISIONOS 0
#endif
#undef PLATFORM_XBOXONE
#if defined(DETAIL__TEMP_PLATFORM_XBOXONE_WAS_1)
#undef DETAIL__TEMP_PLATFORM_XBOXONE_WAS_1
#define PLATFORM_XBOXONE 1
#else
#define PLATFORM_XBOXONE 0
#endif
#undef PLATFORM_SWITCH
#if defined(DETAIL__TEMP_PLATFORM_SWITCH_WAS_1)
#undef DETAIL__TEMP_PLATFORM_SWITCH_WAS_1
#define PLATFORM_SWITCH 1
#else
#define PLATFORM_SWITCH 0
#endif
#undef PLATFORM_LUMIN
#if defined(DETAIL__TEMP_PLATFORM_LUMIN_WAS_1)
#undef DETAIL__TEMP_PLATFORM_LUMIN_WAS_1
#define PLATFORM_LUMIN 1
#else
#define PLATFORM_LUMIN 0
#endif
#undef PLATFORM_STADIA
#if defined(DETAIL__TEMP_PLATFORM_STADIA_WAS_1)
#undef DETAIL__TEMP_PLATFORM_STADIA_WAS_1
#define PLATFORM_STADIA 1
#else
#define PLATFORM_STADIA 0
#endif
#undef PLATFORM_NETBSD
#if defined(DETAIL__TEMP_PLATFORM_NETBSD_WAS_1)
#undef DETAIL__TEMP_PLATFORM_NETBSD_WAS_1
#define PLATFORM_NETBSD 1
#else
#define PLATFORM_NETBSD 0
#endif
#undef PLATFORM_EMBEDDED_LINUX
#if defined(DETAIL__TEMP_PLATFORM_EMBEDDED_LINUX_WAS_1)
#undef DETAIL__TEMP_PLATFORM_EMBEDDED_LINUX_WAS_1
#define PLATFORM_EMBEDDED_LINUX 1
#else
#define PLATFORM_EMBEDDED_LINUX 0
#endif
#undef PLATFORM_QNX
#if defined(DETAIL__TEMP_PLATFORM_QNX_WAS_1)
#undef DETAIL__TEMP_PLATFORM_QNX_WAS_1
#define PLATFORM_QNX 1
#else
#define PLATFORM_QNX 0
#endif

View File

@ -0,0 +1,5 @@
#pragma once
void ShowActivityIndicator(UIView* parent, int style);
void ShowActivityIndicator(UIView* parent);
void HideActivityIndicator();

View File

@ -0,0 +1,49 @@
#include "ActivityIndicator.h"
static UIActivityIndicatorView* _activityIndicator = nil;
void ShowActivityIndicator(UIView* parent, int style)
{
if (_activityIndicator != nil)
return;
if (style >= 0)
{
_activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: (UIActivityIndicatorViewStyle)style];
#if !PLATFORM_VISIONOS
_activityIndicator.contentScaleFactor = [UIScreen mainScreen].scale;
#endif
}
if (_activityIndicator != nil)
{
[parent addSubview: _activityIndicator];
_activityIndicator.center = CGPointMake(parent.bounds.size.width / 2, parent.bounds.size.height / 2);
[_activityIndicator startAnimating];
}
}
void ShowActivityIndicator(UIView* parent)
{
ShowActivityIndicator(parent, UnityGetShowActivityIndicatorOnLoading());
}
void HideActivityIndicator()
{
if (_activityIndicator)
{
[_activityIndicator stopAnimating];
[_activityIndicator removeFromSuperview];
_activityIndicator = nil;
}
}
extern "C" void UnityStartActivityIndicator()
{
ShowActivityIndicator(UnityGetGLView());
}
extern "C" void UnityStopActivityIndicator()
{
HideActivityIndicator();
}

70
Classes/UI/Keyboard.h Normal file
View File

@ -0,0 +1,70 @@
#pragma once
#import <AVFoundation/AVFoundation.h>
typedef struct
{
const char* text;
const char* placeholder;
UIKeyboardType keyboardType;
UITextAutocorrectionType autocorrectionType;
UITextSpellCheckingType spellcheckingType;
UIKeyboardAppearance appearance;
BOOL multiline;
BOOL secure;
int characterLimit;
BOOL oneTimeCode;
}
KeyboardShowParam;
@interface KeyboardDelegate : NSObject<UITextFieldDelegate, UITextViewDelegate>
{
}
- (void)setPendingSelectionRequest;
- (BOOL)textFieldShouldReturn:(UITextField*)textField;
- (void)textInputDone:(id)sender;
- (void)textInputCancel:(id)sender;
- (void)textInputLostFocus;
- (void)textViewDidChange:(UITextView *)textView;
- (void)keyboardWillShow:(NSNotification*)notification;
- (void)keyboardDidShow:(NSNotification*)notification;
- (void)keyboardWillHide:(NSNotification*)notification;
- (void)keyboardDidHide:(NSNotification*)notification;
- (void)becomeFirstResponder;
// on older devices initial keyboard creation might be slow, so it is good to init in on initial loading.
// on the other hand, if you dont use keyboard (or use it rarely), you can avoid having all related stuff in memory:
// keyboard will be created on demand anyway (in Instance method)
+ (void)Initialize;
+ (KeyboardDelegate*)Instance;
+ (void)Destroy;
- (id)init;
- (void)setKeyboardParams:(KeyboardShowParam)param;
- (void)show;
- (void)hide;
- (void)positionInput:(CGRect)keyboardRect x:(float)x y:(float)y;
- (void)shouldHideInput:(BOOL)hide;
+ (void)StartReorientation;
+ (void)FinishReorientation;
- (CGRect)queryArea;
- (NSString*)getText;
- (void)setText:(NSString*)newText;
- (BOOL)hasExternalKeyboard;
- (UITextField*)getTextField;
@property (readonly, nonatomic, getter = queryArea) CGRect area;
@property (readonly, nonatomic) BOOL active;
@property (readonly, nonatomic) KeyboardStatus status;
@property (retain, nonatomic, getter = getText, setter = setText:) NSString* text;
@property (assign, nonatomic) int characterLimit;
@property (readonly, nonatomic) BOOL canGetSelection;
@property (nonatomic, getter = querySelection, setter = assignSelection:) NSRange selection;
@property (nonatomic) BOOL hasUsedDictation;
@end

1101
Classes/UI/Keyboard.mm Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,20 @@
#pragma once
#include <CoreGraphics/CGAffineTransform.h>
#if !PLATFORM_TVOS
ScreenOrientation ConvertToUnityScreenOrientation(UIInterfaceOrientation hwOrient);
UIInterfaceOrientation ConvertToIosScreenOrientation(ScreenOrientation orient);
#endif
#if !PLATFORM_TVOS
UIInterfaceOrientation UIViewControllerInterfaceOrientation(UIViewController* controller);
#endif
ScreenOrientation UIViewControllerOrientation(UIViewController* controller);
CGAffineTransform TransformForOrientation(ScreenOrientation curOrient);
CGAffineTransform TransformBetweenOrientations(ScreenOrientation fromOrient, ScreenOrientation toOrient);
ScreenOrientation OrientationAfterTransform(ScreenOrientation curOrient, CGAffineTransform transform);
void OrientView(UIViewController* host, UIView* view, ScreenOrientation to);

View File

@ -0,0 +1,165 @@
#include "OrientationSupport.h"
#include <math.h>
CGAffineTransform TransformForOrientation(ScreenOrientation orient)
{
switch (orient)
{
case portrait: return CGAffineTransformIdentity;
case portraitUpsideDown: return CGAffineTransformMakeRotation(M_PI);
case landscapeLeft: return CGAffineTransformMakeRotation(M_PI_2);
case landscapeRight: return CGAffineTransformMakeRotation(-M_PI_2);
default: return CGAffineTransformIdentity;
}
return CGAffineTransformIdentity;
}
CGAffineTransform TransformBetweenOrientations(ScreenOrientation fromOrient, ScreenOrientation toOrient)
{
CGAffineTransform fromTransform = TransformForOrientation(fromOrient);
CGAffineTransform toTransform = TransformForOrientation(toOrient);
return CGAffineTransformConcat(CGAffineTransformInvert(fromTransform), toTransform);
}
#if !PLATFORM_TVOS
UIInterfaceOrientation ConvertToIosScreenOrientation(ScreenOrientation orient)
{
switch (orient)
{
case portrait: return UIInterfaceOrientationPortrait;
case portraitUpsideDown: return UIInterfaceOrientationPortraitUpsideDown;
// landscape left/right have switched values in device/screen orientation
// though unity docs are adjusted with device orientation values, so swap here
case landscapeLeft: return UIInterfaceOrientationLandscapeRight;
case landscapeRight: return UIInterfaceOrientationLandscapeLeft;
case orientationUnknown: return (UIInterfaceOrientation)UIInterfaceOrientationUnknown;
default: return UIInterfaceOrientationPortrait;
}
return UIInterfaceOrientationPortrait;
}
ScreenOrientation ConvertToUnityScreenOrientation(UIInterfaceOrientation orient)
{
switch (orient)
{
case UIInterfaceOrientationPortrait: return portrait;
case UIInterfaceOrientationPortraitUpsideDown: return portraitUpsideDown;
// landscape left/right have switched values in device/screen orientation
// though unity docs are adjusted with device orientation values, so swap here
case UIInterfaceOrientationLandscapeLeft: return landscapeRight;
case UIInterfaceOrientationLandscapeRight: return landscapeLeft;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wswitch"
case UIInterfaceOrientationUnknown: return orientationUnknown;
#pragma clang diagnostic pop
default: return portrait;
}
}
// Replacement for UIViewController.interfaceOrientation which is obsolete since iOS 8.0
UIInterfaceOrientation UIViewControllerInterfaceOrientation(UIViewController* c)
{
#if !PLATFORM_VISIONOS
CGPoint fixedPoint = [c.view.window.screen.coordinateSpace convertPoint: CGPointMake(0.0, 0.0) toCoordinateSpace: c.view.window.screen.fixedCoordinateSpace];
if (fabs(fixedPoint.x) < FLT_EPSILON)
{
if (fabs(fixedPoint.y) < FLT_EPSILON)
return UIInterfaceOrientationPortrait;
else
return UIInterfaceOrientationLandscapeLeft;
}
else
{
if (fabs(fixedPoint.y) < FLT_EPSILON)
return UIInterfaceOrientationLandscapeRight;
else
return UIInterfaceOrientationPortraitUpsideDown;
}
#else
return UIInterfaceOrientationLandscapeLeft;
#endif
}
#endif
ScreenOrientation UIViewControllerOrientation(UIViewController* controller)
{
#if PLATFORM_TVOS
return UNITY_TVOS_ORIENTATION;
#elif PLATFORM_VISIONOS
return UNITY_VISIONOS_ORIENTATION;
#else
return ConvertToUnityScreenOrientation(UIViewControllerInterfaceOrientation(controller));
#endif
}
ScreenOrientation OrientationAfterTransform(ScreenOrientation curOrient, CGAffineTransform transform)
{
int rotDeg = (int)::roundf(::atan2f(transform.b, transform.a) * (180 / M_PI));
assert(rotDeg == 0 || rotDeg == 90 || rotDeg == -90 || rotDeg == 180 || rotDeg == -180);
if (rotDeg == 0)
{
return curOrient;
}
else if ((rotDeg == 180) || (rotDeg == -180))
{
if (curOrient == portrait)
return portraitUpsideDown;
else if (curOrient == portraitUpsideDown)
return portrait;
else if (curOrient == landscapeRight)
return landscapeLeft;
else if (curOrient == landscapeLeft)
return landscapeRight;
}
else if (rotDeg == 90)
{
if (curOrient == portrait)
return landscapeLeft;
else if (curOrient == portraitUpsideDown)
return landscapeRight;
else if (curOrient == landscapeRight)
return portrait;
else if (curOrient == landscapeLeft)
return portraitUpsideDown;
}
else if (rotDeg == -90)
{
if (curOrient == portrait)
return landscapeRight;
else if (curOrient == portraitUpsideDown)
return landscapeLeft;
else if (curOrient == landscapeRight)
return portraitUpsideDown;
else if (curOrient == landscapeLeft)
return portrait;
}
::printf("rotation unhandled: %d\n", rotDeg);
return curOrient;
}
void OrientView(UIViewController* host, UIView* view, ScreenOrientation to)
{
ScreenOrientation fromController = UIViewControllerOrientation(host);
CGAffineTransform transform = TransformBetweenOrientations(fromController, to);
// this is for unity-inited orientation. In that case we need to manually adjust bounds if changing portrait/landscape
// the easiest way would be to manually rotate current bounds (to acknowledge the fact that we do NOT rotate controller itself)
// NB: as we use current view bounds we need to use view transform to properly adjust them
CGRect rect = view.bounds;
CGSize ext = CGSizeApplyAffineTransform(rect.size, CGAffineTransformConcat(CGAffineTransformInvert(view.transform), transform));
view.transform = transform;
view.bounds = CGRectMake(0, 0, ::fabs(ext.width), ::fabs(ext.height));
}

18
Classes/UI/StoreReview.m Normal file
View File

@ -0,0 +1,18 @@
#if PLATFORM_IOS || PLATFORM_VISIONOS
// This definition is here only for compiler to know about selector requestReview
@interface UnityStoreReviewController
+ requestReview;
@end
bool UnityRequestStoreReview()
{
Class classSKStoreReviewController = NSClassFromString(@"SKStoreReviewController");
if (!classSKStoreReviewController || ![classSKStoreReviewController respondsToSelector: @selector(requestReview)])
return false;
[classSKStoreReviewController performSelector: @selector(requestReview)];
return true;
}
#endif // PLATFORM_IOS || PLATFORM_VISIONOS

View File

@ -0,0 +1,105 @@
#pragma once
#include "UnityAppController.h"
#include <AvailabilityMacros.h>
@interface UnityAppController (ViewHandling)
// tweaking view hierarchy and handling of orientation
// there are 3 main uses cases regarding UI handling:
//
// 1. normal game case: you shouldnt care about all this at all
//
// 2. you need some not-so-trivial overlayed views and/or minor UI tweaking
// most likely all you need is to subscribe to "orientation changed" notification
// or in case you have per-orientation UI logic override willTransitionToViewController
//
// 3. you create UI-rich app where unity view is just one of many
// in that case you might want to create your own controllers and implement transitions on top
// also instead of orientUnity: (and Screen.orientation in script) you should use orientInterface
// override this if you need customized unityview (subclassing)
// if you simply want different root view, tweak view hierarchy in createAutorotatingUnityViewController
- (UnityView*)createUnityView;
// for view controllers we discern between platforms that do support orientation (e.g. iOS) and the ones that dont (e.g. tvOS)
// both have concept of "default" view controller: for iOS it will be auto-rotating one (with possible constraints) and "simple" controller otherwise
// in case of supporting orientation we will discern case of fixed-orientation view controller (that seems to be the only way to handle it robustly)
// _unityView will be inited at the point of calling any of "create view controller" methods
// please note that these are actual "create" methods: there is no need to tweak hierarchy right away
- (UIViewController*)createUnityViewControllerDefault;
#if UNITY_SUPPORT_ROTATION
- (UIViewController*)createUnityViewControllerForOrientation:(UIInterfaceOrientation)orient;
#endif
#if UNITY_SUPPORT_ROTATION
// if you override these you need to call super
// if your root controller is not subclassed from UnityViewControllerBase, call these when rotation is happening
- (void)interfaceWillChangeOrientationTo:(UIInterfaceOrientation)toInterfaceOrientation;
- (void)interfaceDidChangeOrientationFrom:(UIInterfaceOrientation)fromInterfaceOrientation;
#endif
// handling of changing ViewControllers:
// willStartWithViewController: will be called on startup, when creating view hierarchy
// willTransitionToViewController:fromViewController: didTransitionToViewController:fromViewController:
// are called before/after we are doing some magic to switch to new root controller due to forced orientation change
// by default:
// willStartWithViewController: will make _unityView as root view
// willTransitionToViewController:fromViewController: will do nothing
// didTransitionToViewController:fromViewController: will send orientation events to unity view
// you can use them to tweak view hierarchy if needed
- (void)willStartWithViewController:(UIViewController*)controller;
- (void)willTransitionToViewController:(UIViewController*)toController fromViewController:(UIViewController*)fromController;
- (void)didTransitionToViewController:(UIViewController*)toController fromViewController:(UIViewController*)fromController;
// override this if you want to have custom snapshot view.
// by default it will capture the frame drawn inside applicationWillResignActive specifically to let app respond to OnApplicationPause
// will be called on every applicationWillResignActive; returned view will be released in applicationDidBecomeActive
// NB: case of returning nil will be handled gracefully
- (UIView*)createSnapshotView;
// you should not override these methods
// creates initial UI hierarchy (e.g. splash screen) and calls willStartWithViewController
- (void)createUI;
// shows game itself (hides splash, and bring _rootView to front)
- (void)showGameUI;
// returns the topmost presentedViewController if there is one, or just rootViewController
- (UIViewController*)topMostController;
// will create the correct view controller for requested orientation/autorotation
- (UIViewController*)createRootViewController;
// old deprecated methods: no longer used
// the caveat is: there are some issues in clang related to method deprecation
// which results in warnings not being generated for overriding deprecated methods (in some circumstances).
// so instead of deprecating these methods we just remove them and will check at runtime if user have them and whine about it
//- (UnityView*)createUnityViewImpl DEPRECATED_MSG_ATTRIBUTE("Will not be called. Override createUnityView");
//- (void)createViewHierarchyImpl DEPRECATED_MSG_ATTRIBUTE("Will not be called. Override willStartWithViewController");
//- (void)createViewHierarchy DEPRECATED_MSG_ATTRIBUTE("Is not implemented. Use createUI");
@end
#if UNITY_SUPPORT_ROTATION
@interface UnityAppController (OrientationSupport)
// will create the correct view controller for given orientation
- (UIViewController*)createRootViewControllerForOrientation:(UIInterfaceOrientation)orientation;
// forcibly orient interface
- (void)orientInterface:(UIInterfaceOrientation)orient;
// check unity requested orientation and applies it
- (void)checkOrientationRequest;
- (void)orientUnity:(UIInterfaceOrientation)orient __deprecated_msg("use orientInterface instead.");
@end
#endif

View File

@ -0,0 +1,459 @@
#include "UnityAppController+ViewHandling.h"
#include "UnityAppController+Rendering.h"
#include "UI/OrientationSupport.h"
#include "UI/UnityView.h"
#include "UI/UnityViewControllerBase.h"
#include "Unity/DisplayManager.h"
// TEMP: ?
#include "UI/ActivityIndicator.h"
#include "UI/Keyboard.h"
#include <utility>
extern bool _skipPresent;
extern bool _unityAppReady;
static BOOL _shouldUseDefaultViewControllerForFixedOrientations = NO;
@implementation UnityAppController (ViewHandling)
#if UNITY_SUPPORT_ROTATION
// special case for when we DO know the app orientation, but dont get it through normal mechanism (UIViewController orientation handling)
// how can this happen:
// 1. On startup: ios is not sending "change orientation" notifications on startup (but rather we "start" in correct one already)
// 2. When using presentation controller it can override orientation constraints, so on dismissing we need to tweak app orientation;
// pretty much like startup situation UIViewController would have correct orientation, and app will be out-of-sync
- (void)updateAppOrientation:(UIInterfaceOrientation)orientation
{
// update our (AppContoller) view of orientation
_curOrientation = orientation;
// do unity view "orientation magic"
[_unityView willRotateToOrientation: orientation fromOrientation: (UIInterfaceOrientation)UIInterfaceOrientationUnknown];
[_unityView didRotate];
// after we have updated unity view, this will poke unity itself about the changes in orient/extents
[_unityView boundsUpdated];
}
#endif
- (UnityView*)createUnityView
{
return [[UnityView alloc] initFromMainScreen];
}
- (UIViewController*)createUnityViewControllerDefault
{
#if PLATFORM_IOS
UnityViewControllerBase* ret = [[UnityDefaultViewController alloc] initShouldHandleFixedOrientation: _shouldUseDefaultViewControllerForFixedOrientations];
#else
UnityViewControllerBase* ret = [[UnityDefaultViewController alloc] init];
#endif
ret.notificationDelegate = [[UnityViewControllerNotificationsDefaultSender alloc] init];
#if PLATFORM_TVOS
ret.controllerUserInteractionEnabled = YES;
#endif
return ret;
}
#if UNITY_SUPPORT_ROTATION
- (UIViewController*)createUnityViewControllerForOrientation:(UIInterfaceOrientation)orient
{
UnityViewControllerBase* ret = [AllocUnitySingleOrientationViewController(orient) init];
ret.notificationDelegate = [[UnityViewControllerNotificationsDefaultSender alloc] init];
return ret;
}
#endif
- (UIViewController*)createRootViewController
{
UIViewController* ret = nil;
if (!UNITY_SUPPORT_ROTATION || UnityShouldAutorotate() || _shouldUseDefaultViewControllerForFixedOrientations)
ret = [self createUnityViewControllerDefault];
#if UNITY_SUPPORT_ROTATION
if (ret == nil)
ret = [self createRootViewControllerForOrientation: ConvertToIosScreenOrientation((ScreenOrientation)UnityRequestedScreenOrientation())];
#endif
return ret;
}
- (UIViewController*)topMostController
{
UIViewController *topController = self.window.rootViewController;
while (topController.presentedViewController)
topController = topController.presentedViewController;
return topController;
}
- (void)willStartWithViewController:(UIViewController*)controller
{
#if !PLATFORM_VISIONOS
_unityView.contentScaleFactor = UnityScreenScaleFactor([UIScreen mainScreen]);
#else
_unityView.contentScaleFactor = 1.0f;
#endif
_unityView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
_rootController.view = _rootView = _unityView;
}
- (void)willTransitionToViewController:(UIViewController*)toController fromViewController:(UIViewController*)fromController
{
}
- (void)didTransitionToViewController:(UIViewController*)toController fromViewController:(UIViewController*)fromController
{
#if UNITY_SUPPORT_ROTATION && !PLATFORM_VISIONOS
// when transitioning between view controllers ios will not send reorient events (because they are bound to controllers, not view)
// so we imitate them here so unity view can update its size/orientation
UIInterfaceOrientation newOrientation = UIViewControllerInterfaceOrientation(toController);
[_unityView willRotateToOrientation: newOrientation fromOrientation: ConvertToIosScreenOrientation(_unityView.contentOrientation)];
[_unityView didRotate];
// NB: this is both important and insane at the same time (that we have several places to keep current orentation and we need to sync them)
_curOrientation = newOrientation;
#endif
}
- (UIView*)createSnapshotView
{
// Note that on iPads with iOS 9 or later (up to iOS 10.2 at least) there's a bug in the iOS compositor: any use of -[UIView snapshotViewAfterScreenUpdates]
// causes black screen being shown temporarily when 4 finger gesture to swipe to another app in the task switcher is being performed slowly
return [_rootView snapshotViewAfterScreenUpdates: YES];
}
- (void)createUI
{
NSAssert(_unityView != nil, @"_unityView should be inited at this point");
NSAssert(_window != nil, @"_window should be inited at this point");
if (@available(iOS 16.0, *)) _shouldUseDefaultViewControllerForFixedOrientations = YES;
else _shouldUseDefaultViewControllerForFixedOrientations = NO;
_rootController = [self createRootViewController];
[self willStartWithViewController: _rootController];
NSAssert(_rootView != nil, @"_rootView should be inited at this point");
NSAssert(_rootController != nil, @"_rootController should be inited at this point");
// CODE ARCHEOLOGY: We used to add _rootView (unityView) to the subviews of _window so that unityView would get its
// initial actual device values (e.g. safeAreaInsets) before initializing graphics. This is not needed anymore after
// we made a change where iOS is handling splash screen. Now unityView will be configured at
// [_window makeKeyAndVisible] call. makeKeyAndVisible will configure _window.rootViewController.view, which is
// _rootController.view, which is unityView (_rootView)
// We should have rootViewController set always, otherwise UIKit might trow exception when doing anything with UI
_window.rootViewController = _rootController;
[UIView setAnimationsEnabled: NO];
// make window visible only after we have set up initial controller we want to show
[_window makeKeyAndVisible];
#if UNITY_SUPPORT_ROTATION
// to be able to query orientation from view controller we should actually show it.
// at this point we can only show splash screen, so update app orientation after we started showing it
// NB: _window.rootViewController = splash view controller (not _rootController)
[self updateAppOrientation: ConvertToIosScreenOrientation(UIViewControllerOrientation(_window.rootViewController))];
#endif
NSNumber* style = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"Unity_LoadingActivityIndicatorStyle"];
ShowActivityIndicator(_rootView, style ? [style intValue] : -1);
NSNumber* vcControlled = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"UIViewControllerBasedStatusBarAppearance"];
if (vcControlled && ![vcControlled boolValue])
printf_console("\nSetting UIViewControllerBasedStatusBarAppearance to NO is no longer supported.\n"
"Apple actively discourages that, and all application-wide methods of changing status bar appearance are deprecated\n\n"
);
}
- (void)showGameUI
{
HideActivityIndicator();
// make sure that we start up with correctly created/inited rendering surface
// NB: recreateRenderingSurface won't go into rendering because _unityAppReady is false
#if UNITY_SUPPORT_ROTATION
[self checkOrientationRequest];
#endif
[_unityView recreateRenderingSurface];
// UI hierarchy
_window.rootViewController = _rootController;
[_window bringSubviewToFront: _rootView];
#if UNITY_SUPPORT_ROTATION
// to be able to query orientation from view controller we should actually show it.
// at this point we finally started to show game view controller. Just in case update orientation again
[self updateAppOrientation: ConvertToIosScreenOrientation(UIViewControllerOrientation(_rootController))];
#endif
// why we set level ready only now:
// surface recreate will try to repaint if this var is set (poking unity to do it)
// but this frame now is actually the first one we want to process/draw
// so all the recreateSurface before now (triggered by reorientation) should simply change extents
_unityAppReady = true;
// why we skip present:
// this will be the first frame to draw, so Start methods will be called
// and we want to properly handle resolution request in Start (which might trigger surface recreate)
// NB: we want to draw right after showing window, to avoid black frame creeping in
_skipPresent = true;
if (!UnityIsPaused())
UnityRepaint();
_skipPresent = false;
[self repaint];
[UIView setAnimationsEnabled: YES];
}
#if UNITY_SUPPORT_ROTATION
- (void)transitionToViewController:(UIViewController*)vc
{
[self willTransitionToViewController: vc fromViewController: _rootController];
// first: remove from view hierarchy.
// if we simply hide the window before assigning the new view controller, it will cause black frame flickering
// on the other hand, hiding the window is important by itself to better signal the intent to iOS
// e.g. unless we hide the window view, safeArea might stop working (due to bug in iOS if we're to speculate)
// due to that we do this hide/unhide sequence: we want to to make it hidden, but still unhide it before changing window view controller.
_window.hidden = YES;
_window.hidden = NO;
_rootController.view = nil;
_window.rootViewController = nil;
// second: assign new root controller (and view hierarchy with that), restore bounds
// this is very important to first set _rootController, and only then window root controller
// as the latter will poke [UIApplicationDelegate application:supportedInterfaceOrientationsForWindow:]
// and unity implementation expects _rootController to be already set
_window.rootViewController = _rootController = vc;
_rootController.view = _rootView;
// CODE ARCHEOLOGY: in here we were tweaking window bounds to agree with screen bounds (and did some iOS8 specific workaround)
// This is no longer needed it seems, and is actually harmful for the "split view" supporting apps
// If you have fullscreen window, it will be automatically resized to take the whole screen
// and otherwise we must not touch it, as it will be controlled by multitasking
// third: restore window as key and layout subviews to finalize size changes
[_window makeKeyAndVisible];
[_window layoutSubviews];
// In iOS16+ after we setup a new contoller and when we have multiple windows visible, iOS not fully prepares
// view controller according it's orientation requirements. And then inside didTransitionToViewController:
// from UIViewControllerInterfaceOrientation we get bad orientation as it uses scree.coordinationSpace which is not
// yet changed. So we want to delay didTransitionToViewController call. And in this case we get a call to view
// controllers -viewWillTransitionToSize: method and at this time the orientation change is already happened and
// then we send didTransitionToViewController. If view controller changes are setup correctly from iOS, then iOS do
// not call -viewWillTransitionToSize:.
UIInterfaceOrientation newOrientation = UIViewControllerInterfaceOrientation(vc);
BOOL orientationChangedToSupported = vc.supportedInterfaceOrientations & (1 << newOrientation);
if (!UnityiOS160orNewer() || orientationChangedToSupported)
{
[self didTransitionToViewController: vc fromViewController: _rootController];
}
}
- (void)interfaceWillChangeOrientationTo:(UIInterfaceOrientation)toInterfaceOrientation
{
UIInterfaceOrientation fromInterfaceOrientation = _curOrientation;
_curOrientation = toInterfaceOrientation;
[_unityView willRotateToOrientation: toInterfaceOrientation fromOrientation: fromInterfaceOrientation];
}
- (void)interfaceDidChangeOrientationFrom:(UIInterfaceOrientation)fromInterfaceOrientation
{
[_unityView didRotate];
}
#endif
- (void)notifyHideHomeButtonChange
{
#if PLATFORM_IOS || PLATFORM_VISIONOS
// setNeedsUpdateOfHomeIndicatorAutoHidden is not implemented on iOS 11.0.
// The bug has been fixed in iOS 11.0.1. See http://www.openradar.me/35127134
if ([_rootController respondsToSelector: @selector(setNeedsUpdateOfHomeIndicatorAutoHidden)])
[_rootController setNeedsUpdateOfHomeIndicatorAutoHidden];
#endif
}
- (void)notifyDeferSystemGesturesChange
{
#if PLATFORM_IOS || PLATFORM_VISIONOS
[_rootController setNeedsUpdateOfScreenEdgesDeferringSystemGestures];
#endif
}
@end
#if UNITY_SUPPORT_ROTATION
@implementation UnityAppController (OrientationSupport)
- (UIViewController*)createRootViewControllerForOrientation:(UIInterfaceOrientation)orientation
{
return [self createUnityViewControllerForOrientation: orientation];
}
- (void)checkOrientationRequest
{
// if no orientation/allowed-orientation change - do nothing
if (!UnityHasOrientationRequest() && !UnityShouldChangeAllowedOrientations())
return;
// if there is a presentation controller, it takes over orientation control
// in this case we should completely ignore all orientation changes
// mind you, we just *delay* them, and they will be satisfied once presentation controller is dismissed
// extra care like this is needed, because below we might recreate ViewController completely breaking
// presentation controller dismissal
if (_rootController.presentedViewController)
return;
// to reiterate: we have different processing on newish iOS where we stick to just one view controller
// in this case we leave all the processing to iOS
if(_shouldUseDefaultViewControllerForFixedOrientations)
{
NSAssert([self.rootViewController isKindOfClass: [UnityDefaultViewController class]],
@"UnityDefaultViewController should be root controller");
[(UnityDefaultViewController*)self.rootViewController updateSupportedOrientations];
[UIViewController attemptRotationToDeviceOrientation];
// note that we could have a big if-else block and call it once at the end of the method
// but it was deemed too ugly
UnityOrientationRequestWasCommitted();
return;
}
// normally we want to call attemptRotationToDeviceOrientation to tell iOS that we changed orientation constraints
// but if the current orientation is disabled we need special processing, as iOS will simply ignore us
// the only good/robust way is to simply recreate "autorotating" view controller and transition to it if needed
// please note that we want to trigger "orientation request" code path if we recreate autorotating view controller
bool changeOrient = UnityHasOrientationRequest();
// if we should recreate autorotating view controller - see below
bool shouldTransferToNewAutorotVC = false;
// first we check if we need to update orientations enabled for autorotation
// this needs to be done *only* if we are to continue autorotating
// otherwise we will transition from this view controller
// and iOS will reread enabled orientations on next ViewController activation
const bool autorot = UnityShouldAutorotate(), autorotChanged = UnityAutorotationStatusChanged();
if (UnityShouldChangeAllowedOrientations() && autorot)
{
NSUInteger rootOrient = 1 << UIViewControllerInterfaceOrientation(self.rootViewController);
if (!autorotChanged && (rootOrient & EnabledAutorotationInterfaceOrientations()))
{
// instead of querying unity for supported orientations, we keep them in the default (autorotating) controller
// this is THE place where we should update those (otherwise, filled on creation)
if ([self.rootViewController isKindOfClass: [UnityDefaultViewController class]])
[(UnityDefaultViewController*)self.rootViewController updateSupportedOrientations];
// if we are currently autorotating AND changed allowed orientations while keeping current interface orientation allowed:
// we can simply trigger attemptRotationToDeviceOrientation and we are done
// please note that this can happen when current *device* orientation is disabled (and we want to enable it)
[UIViewController attemptRotationToDeviceOrientation];
}
else
{
// otherwise we recreate default autorotating view controller
// to spell it out, we recreate if:
// - we continue doing autorotation, but the current orientation is disabled
// - we were not autorotating but start now
shouldTransferToNewAutorotVC = true;
changeOrient = true;
}
}
if (changeOrient)
{
// on some devices like iPhone XS layoutSubview is not called when transitioning from different orientations with the same resolution
// therefore forcing layoutSubview on all orientation changes
[_unityView setNeedsLayout];
if (autorot)
{
// just started autorotating or decided to recreate autorot controller above
if (autorotChanged || shouldTransferToNewAutorotVC)
[self transitionToViewController: [self createUnityViewControllerDefault]];
[UIViewController attemptRotationToDeviceOrientation];
}
else
{
UIInterfaceOrientation requestedOrient = ConvertToIosScreenOrientation((ScreenOrientation)UnityRequestedScreenOrientation());
// on one hand orientInterface: should be perfectly fine "reorienting" to current orientation
// in reality, ios might be confused by transitionToViewController: shenanigans coupled with "nothing have changed actually"
// as an example: prior to ios12 that might result in status bar going "bad" (becoming transparent)
// NOTE: if we have switched from autorotation to fixed orientation, we must do the switch to pick new VC
if (_curOrientation != requestedOrient || autorotChanged)
[self orientInterface: requestedOrient];
}
}
UnityOrientationRequestWasCommitted();
}
- (void)orientInterface:(UIInterfaceOrientation)orient
{
if (_unityAppReady)
UnityFinishRendering();
[KeyboardDelegate StartReorientation];
[CATransaction begin];
{
UIInterfaceOrientation oldOrient = _curOrientation;
UIInterfaceOrientation newOrient = orient;
[self interfaceWillChangeOrientationTo: newOrient];
// TODO: we should handle _shouldUseDefaultViewControllerForFixedOrientations = YES
// TODO: though i am not sure how this should be done
// TODO: currently in normal orientation processing this will not be called when _shouldUseDefaultViewControllerForFixedOrientations is true
// TODO: but native plugins can still call it directly
[self transitionToViewController: [self createRootViewControllerForOrientation: newOrient]];
[self interfaceDidChangeOrientationFrom: oldOrient];
#if !PLATFORM_VISIONOS
[UIApplication sharedApplication].statusBarOrientation = orient;
#endif
}
[CATransaction commit];
[KeyboardDelegate FinishReorientation];
}
- (void)orientUnity:(UIInterfaceOrientation)orient
{
[self orientInterface: orient];
}
@end
#endif
extern "C" void UnityNotifyHideHomeButtonChange()
{
[GetAppController() notifyHideHomeButtonChange];
}
extern "C" void UnityNotifyDeferSystemGesturesChange()
{
[GetAppController() notifyDeferSystemGesturesChange];
}

View File

@ -0,0 +1,269 @@
#import "UnityView.h"
#include "UI/Keyboard.h"
#include <sys/time.h>
#include <map>
#include <vector>
static NSArray* keyboardCommands = nil;
extern "C" int UnityGetAppleTVRemoteAllowExitToMenu();
extern "C" void UnitySetAppleTVRemoteAllowExitToMenu(int val);
@implementation UnityView (Keyboard)
// Keyboard shortcuts don't provide events for key up
// Keyboard shortcut callbacks are called with 0.4 (first time) and 0.1 (following times) seconds interval while pressing the key
// Below we implement key expiration mechanism where key up event is generated if shortcut callback
// is not called for specific key for more than <kKeyTimeoutInSeconds>
typedef std::map<int, double> KeyMap;
static const double kKeyTimeoutInSeconds = 0.5;
static KeyMap& GetKeyMap()
{
static KeyMap s_Map;
return s_Map;
}
static double GetTimeInSeconds()
{
timeval now;
gettimeofday(&now, NULL);
return now.tv_sec + now.tv_usec / 1000000.0;
}
- (void)createKeyboard
{
// only English keyboard layout is supported
NSString* baseLayout = @"1234567890-=qwertyuiop[]asdfghjkl;'\\`zxcvbnm,./!@#$%^&*()_+{}:\"|<>?~ \t\r\b\\";
NSString* numpadLayout = @"1234567890-=*+/.\r";
NSString* upperCaseLetters = @"QWERTYUIOPASDFGHJKLZXCVBNM";
NSString* shortcutCharacters = @"axcv";
size_t sizeOfKeyboardCommands = baseLayout.length + numpadLayout.length + upperCaseLetters.length + 11;
NSMutableArray* commands = [NSMutableArray arrayWithCapacity: sizeOfKeyboardCommands];
void (^addKey)(NSString *keyName, UIKeyModifierFlags modifierFlags) = ^(NSString *keyName, UIKeyModifierFlags modifierFlags)
{
UIKeyCommand* command = [UIKeyCommand keyCommandWithInput: keyName modifierFlags: modifierFlags action: @selector(handleCommand:)];
if (@available(iOS 15.0, tvOS 15.0, *))
command.wantsPriorityOverSystemBehavior = YES;
[commands addObject: command];
};
for (NSInteger i = 0; i < baseLayout.length; ++i)
{
NSString* input = [baseLayout substringWithRange: NSMakeRange(i, 1)];
addKey(input, kNilOptions);
}
for (NSInteger i = 0; i < shortcutCharacters.length; ++i)
{
NSString* input = [shortcutCharacters substringWithRange: NSMakeRange(i, 1)];
[commands addObject: [UIKeyCommand keyCommandWithInput: input modifierFlags: UIKeyModifierCommand action: @selector(handleCommand:)]];
}
for (NSInteger i = 0; i < numpadLayout.length; ++i)
{
NSString* input = [numpadLayout substringWithRange: NSMakeRange(i, 1)];
addKey(input, UIKeyModifierNumericPad);
}
for (NSInteger i = 0; i < upperCaseLetters.length; ++i)
{
NSString* input = [upperCaseLetters substringWithRange: NSMakeRange(i, 1)];
addKey(input, UIKeyModifierShift);
}
// pageUp, pageDown
addKey(UIKeyInputPageUp, kNilOptions);
addKey(UIKeyInputPageDown, kNilOptions);
// up, down, left, right, esc
addKey(UIKeyInputUpArrow, kNilOptions);
addKey(UIKeyInputDownArrow, kNilOptions);
addKey(UIKeyInputLeftArrow, kNilOptions);
addKey(UIKeyInputRightArrow, kNilOptions);
addKey(UIKeyInputEscape, kNilOptions);
// caps Lock, shift, control, option, command
addKey(@"", UIKeyModifierAlphaShift);
addKey(@"", UIKeyModifierShift);
addKey(@"", UIKeyModifierControl);
addKey(@"", UIKeyModifierAlternate);
addKey(@"", UIKeyModifierCommand);
keyboardCommands = commands.copy;
}
- (NSArray*)keyCommands
{
//keyCommands take control of buttons over UITextView, that's why need to return nil if text input field is active or we have an external keyboard attached AND a first responder
if ([[KeyboardDelegate Instance] status] == Visible || ([[KeyboardDelegate Instance] hasExternalKeyboard] && [self hasFirstResponderInHeirachy: UnityGetGLView()]))
return nil;
if (keyboardCommands == nil)
{
[self createKeyboard];
}
return keyboardCommands;
}
- (bool)hasFirstResponderInHeirachy:(UIView*)view
{
if (view.isFirstResponder)
return true;
for (UIView* subview in view.subviews)
{
if ([self hasFirstResponderInHeirachy: subview])
return true;
}
return false;
}
- (bool)isValidCodeForButton:(int)code
{
return (code > 0 && code < 128);
}
- (void)handleCommand:(UIKeyCommand *)command
{
NSString* input = command.input;
UIKeyModifierFlags modifierFlags = command.modifierFlags;
char inputChar = ([input length] == 1) ? [input characterAtIndex: 0] : 0;
int code = (int)inputChar; // ASCII code
if (![self isValidCodeForButton: code])
{
code = 0;
}
if ((modifierFlags & UIKeyModifierAlphaShift) != 0)
code = UnityStringToKey("caps lock");
if ((modifierFlags & UIKeyModifierShift) != 0)
code = UnityStringToKey("left shift");
if ((modifierFlags & UIKeyModifierControl) != 0)
code = UnityStringToKey("left ctrl");
if ((modifierFlags & UIKeyModifierAlternate) != 0)
code = UnityStringToKey("left alt");
if ((modifierFlags & UIKeyModifierCommand) != 0)
code = UnityStringToKey("left cmd");
if ((modifierFlags & UIKeyModifierNumericPad) != 0)
{
switch (inputChar)
{
case '0':
code = UnityStringToKey("[0]");
break;
case '1':
code = UnityStringToKey("[1]");
break;
case '2':
code = UnityStringToKey("[2]");
break;
case '3':
code = UnityStringToKey("[3]");
break;
case '4':
code = UnityStringToKey("[4]");
break;
case '5':
code = UnityStringToKey("[5]");
break;
case '6':
code = UnityStringToKey("[6]");
break;
case '7':
code = UnityStringToKey("[7]");
break;
case '8':
code = UnityStringToKey("[8]");
break;
case '9':
code = UnityStringToKey("[9]");
break;
case '-':
code = UnityStringToKey("[-]");
break;
case '=':
code = UnityStringToKey("equals");
break;
case '*':
code = UnityStringToKey("[*]");
break;
case '+':
code = UnityStringToKey("[+]");
break;
case '/':
code = UnityStringToKey("[/]");
break;
case '.':
code = UnityStringToKey("[.]");
break;
case '\r':
code = UnityStringToKey("enter");
break;
default:
break;
}
}
if (input == UIKeyInputUpArrow)
code = UnityStringToKey("up");
else if (input == UIKeyInputDownArrow)
code = UnityStringToKey("down");
else if (input == UIKeyInputRightArrow)
code = UnityStringToKey("right");
else if (input == UIKeyInputLeftArrow)
code = UnityStringToKey("left");
else if (input == UIKeyInputEscape)
code = UnityStringToKey("escape");
else if ([input isEqualToString: @"UIKeyInputPageUp"])
code = UnityStringToKey("page up");
else if ([input isEqualToString: @"UIKeyInputPageDown"])
code = UnityStringToKey("page down");
UnitySendKeyboardCommand(command, code);
KeyMap::iterator item = GetKeyMap().find(code);
if (item == GetKeyMap().end())
{
// New key is down, register it and its time
UnitySetKeyboardKeyState(code, true);
GetKeyMap()[code] = GetTimeInSeconds();
}
else
{
// Still holding the key, update its time
item->second = GetTimeInSeconds();
}
}
- (void)processKeyboard
{
KeyMap& map = GetKeyMap();
if (map.size() == 0)
return;
std::vector<int> keysToUnpress;
double nowTime = GetTimeInSeconds();
for (KeyMap::iterator item = map.begin();
item != map.end();
item++)
{
// Key has expired, register it for key up event
if (nowTime - item->second > kKeyTimeoutInSeconds)
keysToUnpress.push_back(item->first);
}
for (std::vector<int>::iterator item = keysToUnpress.begin();
item != keysToUnpress.end();
item++)
{
map.erase(*item);
UnitySetKeyboardKeyState(*item, false);
}
}
@end

View File

@ -0,0 +1,15 @@
#pragma once
@interface UnityView (iOS)
// will simply update content orientation (it might be tweaked in layoutSubviews, due to disagreement between unity and view controller)
- (void)willRotateToOrientation:(UIInterfaceOrientation)toOrientation fromOrientation:(UIInterfaceOrientation)fromOrientation;
// will recreate gles backing if needed and repaint once to make sure we dont have black frame creeping in
- (void)didRotate;
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event;
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event;
- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event;
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event;
@end

View File

@ -0,0 +1,47 @@
#if PLATFORM_IOS || PLATFORM_VISIONOS
#import "UnityView.h"
#import "UnityAppController+Rendering.h"
#include "OrientationSupport.h"
@interface UnityView ()
@property (nonatomic, readwrite) ScreenOrientation contentOrientation;
@end
@implementation UnityView (iOS)
- (void)willRotateToOrientation:(UIInterfaceOrientation)toOrientation fromOrientation:(UIInterfaceOrientation)fromOrientation;
{
// to support the case of interface and unity content orientation being different
// we will cheat a bit:
// we will calculate transform between interface orientations and apply it to unity view orientation
// you can still tweak unity view as you see fit in AppController, but this is what you want in 99% of cases
ScreenOrientation to = ConvertToUnityScreenOrientation(toOrientation);
ScreenOrientation from = ConvertToUnityScreenOrientation(fromOrientation);
if (fromOrientation == UIInterfaceOrientationUnknown)
_curOrientation = to;
else
_curOrientation = OrientationAfterTransform(_curOrientation, TransformBetweenOrientations(from, to));
_viewIsRotating = YES;
}
- (void)didRotate
{
if (_shouldRecreateView)
{
[self recreateRenderingSurface];
}
_viewIsRotating = NO;
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { UnitySendTouchesBegin(touches, event); }
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { UnitySendTouchesEnded(touches, event); }
- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { UnitySendTouchesCancelled(touches, event); }
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { UnitySendTouchesMoved(touches, event); }
@end
#endif // PLATFORM_IOS || PLATFORM_VISIONOS

View File

@ -0,0 +1,15 @@
#pragma once
@interface UnityView (tvOS)
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event;
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event;
- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event;
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event;
#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
- (void)pressesBegan:(NSSet<UIPress*>*)presses withEvent:(UIEvent*)event;
- (void)pressesEnded:(NSSet<UIPress*>*)presses withEvent:(UIEvent*)event;
#endif
@end

View File

@ -0,0 +1,66 @@
#if PLATFORM_TVOS
#import "UnityView.h"
#include "iphone_Sensors.h"
@implementation UnityView (tvOS)
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
ReportSimulatedRemoteTouchesBegan(self, touches);
#endif
if (UnityGetAppleTVRemoteTouchesEnabled())
UnitySendTouchesBegin(touches, event);
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
ReportSimulatedRemoteTouchesEnded(self, touches);
#endif
if (UnityGetAppleTVRemoteTouchesEnabled())
UnitySendTouchesEnded(touches, event);
}
- (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event
{
#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
ReportSimulatedRemoteTouchesEnded(self, touches);
#endif
if (UnityGetAppleTVRemoteTouchesEnabled())
UnitySendTouchesCancelled(touches, event);
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
ReportSimulatedRemoteTouchesMoved(self, touches);
#endif
if (UnityGetAppleTVRemoteTouchesEnabled())
UnitySendTouchesMoved(touches, event);
}
#if UNITY_TVOS_SIMULATOR_FAKE_REMOTE
- (void)pressesBegan:(NSSet<UIPress*>*)presses withEvent:(UIEvent*)event
{
for (UIPress *press in presses)
ReportSimulatedRemoteButtonPress(press.type);
}
- (void)pressesEnded:(NSSet<UIPress*>*)presses withEvent:(UIEvent*)event
{
for (UIPress *press in presses)
ReportSimulatedRemoteButtonRelease(press.type);
}
#endif
@end
#endif // PLATFORM_TVOS

61
Classes/UI/UnityView.h Normal file
View File

@ -0,0 +1,61 @@
#pragma once
@interface UnityRenderingView : UIView
{
}
+ (void)InitializeForAPI:(UnityRenderingAPI)api;
@end
@interface UnityView : UnityRenderingView
{
@private ScreenOrientation _curOrientation;
@private BOOL _shouldRecreateView;
@private BOOL _viewIsRotating;
}
// we take scale factor into account because gl backbuffer size depends on it
- (id)initWithFrame:(CGRect)frame scaleFactor:(CGFloat)scale;
- (id)initWithFrame:(CGRect)frame;
- (id)initFromMainScreen;
- (void)resumeRendering;
// in here we will go through subviews and call onUnityUpdateViewLayout selector (if present)
// that allows to handle simple overlay child view layout without doing view controller magic
- (void)layoutSubviews;
- (void)recreateRenderingSurfaceIfNeeded;
- (void)recreateRenderingSurface;
// will match script-side Screen.orientation
@property (nonatomic, readonly) ScreenOrientation contentOrientation;
@property BOOL skipRendering;
@end
@interface UnityView (Deprecated)
- (void)recreateGLESSurfaceIfNeeded __deprecated_msg("use recreateRenderingSurfaceIfNeeded instead.");
- (void)recreateGLESSurface __deprecated_msg("use recreateRenderingSurface instead.");
@end
@interface UnityView (Keyboard)
- (void)processKeyboard;
@end
@interface UnityView (UnityAppController)
// if we know that unity view bounds have changed but need to update unity-side size/orientation immediately
// otherwise the update will be delayed to next layoutSubviews
- (void)boundsUpdated;
@end
#if PLATFORM_IOS || PLATFORM_VISIONOS
#include "UnityView+iOS.h"
#elif PLATFORM_TVOS
#include "UnityView+tvOS.h"
#endif
void ReportSafeAreaChangeForView(UIView* view);
// Computes safe area for a view in Unity coordinate system (origin of the view
// is bottom-left, as compared to standard top-left)
CGRect ComputeSafeArea(UIView* view);
CGSize GetCutoutToScreenRatio();

368
Classes/UI/UnityView.mm Normal file
View File

@ -0,0 +1,368 @@
#include "UnityView.h"
#include "UnityAppController.h"
#include "UnityAppController+Rendering.h"
#include "OrientationSupport.h"
#include "Unity/DisplayManager.h"
#include "Unity/UnityMetalSupport.h"
#include "Unity/ObjCRuntime.h"
extern bool _renderingInited;
extern bool _unityAppReady;
extern bool _skipPresent;
@implementation UnityView
{
CGSize _surfaceSize;
}
@synthesize contentOrientation = _curOrientation;
- (void)onUpdateSurfaceSize:(CGSize)size
{
_surfaceSize = size;
CGSize systemRenderSize = CGSizeMake(size.width * self.contentScaleFactor, size.height * self.contentScaleFactor);
_curOrientation = (ScreenOrientation)UnityReportResizeView((unsigned)systemRenderSize.width, (unsigned)systemRenderSize.height, _curOrientation);
ReportSafeAreaChangeForView(self);
}
- (void)boundsUpdated
{
[self onUpdateSurfaceSize: self.bounds.size];
}
- (void)initImpl:(CGRect)frame scaleFactor:(CGFloat)scale
{
#if !PLATFORM_TVOS
self.multipleTouchEnabled = YES;
self.exclusiveTouch = YES;
#endif
self.contentScaleFactor = scale;
self.isAccessibilityElement = TRUE;
self.accessibilityTraits = UIAccessibilityTraitAllowsDirectInteraction;
self.skipRendering = NO;
#if UNITY_TVOS
_curOrientation = UNITY_TVOS_ORIENTATION;
#elif UNITY_VISIONOS
_curOrientation = UNITY_VISIONOS_ORIENTATION;
#endif
[self onUpdateSurfaceSize: frame.size];
}
- (id)initWithFrame:(CGRect)frame scaleFactor:(CGFloat)scale;
{
if ((self = [super initWithFrame: frame]))
[self initImpl: frame scaleFactor: scale];
return self;
}
- (id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame: frame]))
[self initImpl: frame scaleFactor: 1.0f];
return self;
}
- (id)initFromMainScreen
{
#if !PLATFORM_VISIONOS
CGRect frame = [UIScreen mainScreen].bounds;
CGFloat scale = UnityScreenScaleFactor([UIScreen mainScreen]);
#else
CGRect frame = CGRectMake(0.0f, 0.0f, 1920.0f, 1080.0f);
CGFloat scale = 1.0f;
#endif
if ((self = [super initWithFrame: frame]))
[self initImpl: frame scaleFactor: scale];
return self;
}
- (void)resumeRendering
{
self.skipRendering = NO;
}
- (void)layoutSubviews
{
if (_surfaceSize.width != self.bounds.size.width || _surfaceSize.height != self.bounds.size.height)
_shouldRecreateView = YES;
[self onUpdateSurfaceSize: self.bounds.size];
for (UIView* subView in self.subviews)
{
if ([subView respondsToSelector: @selector(onUnityUpdateViewLayout)])
[subView performSelector: @selector(onUnityUpdateViewLayout)];
}
[super layoutSubviews];
}
- (void)safeAreaInsetsDidChange
{
ReportSafeAreaChangeForView(self);
}
- (void)recreateRenderingSurfaceIfNeeded
{
#if !PLATFORM_VISIONOS
float requestedContentScaleFactor = UnityScreenScaleFactor([UIScreen mainScreen]);
#else
float requestedContentScaleFactor = 1.0f;
#endif
if (abs(requestedContentScaleFactor - self.contentScaleFactor) > FLT_EPSILON)
{
self.contentScaleFactor = requestedContentScaleFactor;
[self onUpdateSurfaceSize: self.bounds.size];
}
unsigned requestedW, requestedH; UnityGetRenderingResolution(&requestedW, &requestedH);
int requestedMSAA = UnityGetDesiredMSAASampleCount(1);
int requestedSRGB = UnityGetSRGBRequested();
int requestedWideColor = UnityGetWideColorRequested();
int requestedHDR = UnityGetHDRModeRequested();
int requestedMemorylessDepth = UnityMetalMemorylessDepth();
UnityDisplaySurfaceBase* surf = GetMainDisplaySurface();
if (_shouldRecreateView == YES
|| surf->targetW != requestedW || surf->targetH != requestedH
|| surf->disableDepthAndStencil != UnityDisableDepthAndStencilBuffers()
|| surf->msaaSamples != requestedMSAA
|| surf->srgb != requestedSRGB
|| surf->wideColor != requestedWideColor
|| surf->hdr != requestedHDR
|| surf->memorylessDepth != requestedMemorylessDepth
)
{
[self recreateRenderingSurface];
}
}
- (void)recreateRenderingSurface
{
if (_renderingInited)
{
unsigned requestedW, requestedH;
UnityGetRenderingResolution(&requestedW, &requestedH);
RenderingSurfaceParams params =
{
.msaaSampleCount = UnityGetDesiredMSAASampleCount(1),
.renderW = (int)requestedW,
.renderH = (int)requestedH,
.srgb = UnityGetSRGBRequested(),
.wideColor = UnityGetWideColorRequested(),
.hdr = UnityGetHDRModeRequested(),
.metalFramebufferOnly = UnityMetalFramebufferOnly(),
.metalMemorylessDepth = UnityMetalMemorylessDepth(),
.disableDepthAndStencil = UnityDisableDepthAndStencilBuffers(),
.useCVTextureCache = 0,
};
APP_CONTROLLER_RENDER_PLUGIN_METHOD_ARG(onBeforeMainDisplaySurfaceRecreate, &params);
[GetMainDisplay() recreateSurface: params];
// actually poke unity about updated back buffer and notify that extents were changed
UnityReportBackbufferChange(GetMainDisplaySurface()->unityColorBuffer, GetMainDisplaySurface()->unityDepthBuffer);
APP_CONTROLLER_RENDER_PLUGIN_METHOD(onAfterMainDisplaySurfaceRecreate);
if (_unityAppReady)
{
// seems like ios sometimes got confused about abrupt swap chain destroy
// draw 2 times to fill "both" buffers (we assume double buffering)
// present only once to make sure correct image goes to CA
// if we are calling this from inside repaint, second draw and present will be done automatically
_skipPresent = true;
// we may be asked to recreate surface while paused (in the background)
// like changing device orientation while showing some system dialog
// in this case we still want to redraw contents to avoid view stretching
const bool wasPaused = UnityIsPaused();
// please note that we still need to pretend we did come from displaylink to make sure vsync magic works
// NOTE: unity does handle "draw frame with exact same timestamp" just fine
UnityDisplayLinkCallback(GetAppController().unityDisplayLink.timestamp);
UnityRepaint();
// if we are inside actual repaint: we are done (second draw and present will be done automatically)
// otherwise we need the second repaint, actualy doing present this time
_skipPresent = false;
if (_viewIsRotating || wasPaused)
{
UnityDisplayLinkCallback(GetAppController().unityDisplayLink.timestamp);
UnityRepaint();
}
}
}
_shouldRecreateView = NO;
}
@end
@implementation UnityView (Deprecated)
- (void)recreateGLESSurfaceIfNeeded { [self recreateRenderingSurfaceIfNeeded]; }
- (void)recreateGLESSurface { [self recreateRenderingSurface]; }
@end
static Class UnityRenderingView_LayerClassMTL(id self_, SEL _cmd)
{
return NSClassFromString(@"CAMetalLayer");
}
static Class UnityRenderingView_LayerClassNULL(id self_, SEL _cmd)
{
return NSClassFromString(@"CALayer");
}
@implementation UnityRenderingView
+ (Class)layerClass
{
return nil;
}
+ (void)InitializeForAPI:(UnityRenderingAPI)api
{
IMP layerClassImpl = api == apiMetal ? (IMP)UnityRenderingView_LayerClassMTL : (IMP)UnityRenderingView_LayerClassNULL;
class_replaceMethod(object_getClass([UnityRenderingView class]), @selector(layerClass), layerClassImpl, UIView_LayerClass_Enc);
}
@end
void ReportSafeAreaChangeForView(UIView* view)
{
CGRect safeArea = ComputeSafeArea(view);
UnityReportSafeAreaChange(safeArea.origin.x, safeArea.origin.y,
safeArea.size.width, safeArea.size.height);
#if !PLATFORM_VISIONOS
if (UnityDeviceHasCutout())
{
CGSize cutoutSizeRatio = GetCutoutToScreenRatio();
if (!CGSizeEqualToSize(CGSizeZero, cutoutSizeRatio))
{
const float w = ([UIScreen mainScreen].nativeBounds.size.width * cutoutSizeRatio.width);
const float h = ([UIScreen mainScreen].nativeBounds.size.height * cutoutSizeRatio.height);
// Apple's cutouts are currently centred on the horizontal, and stuck to the top of the vertical, hence this positioning.
const float x = (([UIScreen mainScreen].nativeBounds.size.width - w) / 2);
const float y = ([UIScreen mainScreen].nativeBounds.size.height - h);
UnityReportDisplayCutouts(&x, &y, &w, &h, 1);
return;
}
}
#endif
UnityReportDisplayCutouts(nullptr, nullptr, nullptr, nullptr, 0);
}
CGRect ComputeSafeArea(UIView* view)
{
CGSize screenSize = view.bounds.size;
CGRect screenRect = CGRectMake(0, 0, screenSize.width, screenSize.height);
UIEdgeInsets insets = [view safeAreaInsets];
float insetLeft = insets.left, insetBottom = insets.bottom, insetTop = insets.top;
float insetHeight = insetBottom + insetTop;
float insetWidth = insetLeft + insets.right;
#if PLATFORM_IOS && !PLATFORM_VISIONOS
// pre-iOS 15 there is a bug with safeAreaInsets when coupled with the way unity handles forced orientation
// when we create/show new ViewController with fixed orientation, safeAreaInsets include status bar always
// alas, we did not find a good way to work around that (this can be seen even in View Debugging: Safe Area would have status bar accounted for)
// we know for sure that status bar height is 20 (at least on ios16 or older), so we can check if the safe area
// includes inset of this size while status bar should be hidden in that case we reset top inset and keep
// bottom one (might include home button swipe line,etc.).
if (@available(iOS 15, *))
{
// everything works as expected
}
else
{
bool isStatusBarHidden = false;
if (@available(iOS 13, *))
isStatusBarHidden = view.window.windowScene.statusBarManager.statusBarHidden;
else
isStatusBarHidden = [UIApplication sharedApplication].statusBarHidden;
if (isStatusBarHidden && fabsf(insetTop - 20) < 1e-6f)
insetHeight -= insetTop;
}
#endif
// Unity uses bottom left as the origin
screenRect = CGRectOffset(screenRect, insetLeft, insetBottom);
screenRect.size.width -= insetWidth;
screenRect.size.height -= insetHeight;
const float scale = view.contentScaleFactor;
// Truncate safe area size because in some cases (for example when Display zoom is turned on)
// it might become larger than Screen.width/height which are returned as ints.
screenRect.origin.x = (unsigned)(screenRect.origin.x * scale);
screenRect.origin.y = (unsigned)(screenRect.origin.y * scale);
screenRect.size.width = (unsigned)(screenRect.size.width * scale);
screenRect.size.height = (unsigned)(screenRect.size.height * scale);
return screenRect;
}
// Apple does not provide the cutout width and height in points/pixels. They *do* however list the
// size of the cutout and screen in mm for accessory makers. We can use this information to calculate the percentage of the screen is cutout.
// This information can be found here - https://developer.apple.com/accessories/Accessory-Design-Guidelines.pdf
CGSize GetCutoutToScreenRatio()
{
switch (UnityDeviceGeneration())
{
case deviceiPhone14:
case deviceiPhone16e:
return CGSizeMake(0.415, 0.04);
case deviceiPhone14Plus:
return CGSizeMake(0.377, 0.036);
case deviceiPhone14Pro:
case deviceiPhone15:
case deviceiPhone15Pro:
case deviceiPhone16:
case deviceiPhone16Pro:
return CGSizeMake(0.318, 0.057);
case deviceiPhone14ProMax:
case deviceiPhone15ProMax:
case deviceiPhone15Plus:
case deviceiPhone16Plus:
case deviceiPhone16ProMax:
return CGSizeMake(0.292, 0.052);
case deviceiPhone13ProMax:
return CGSizeMake(0.373, 0.036);
case deviceiPhone13Pro:
case deviceiPhone13:
return CGSizeMake(0.4148, 0.0399);
case deviceiPhone13Mini:
return CGSizeMake(0.4644, 0.0462);
case deviceiPhone12ProMax:
return CGSizeMake(0.4897, 0.0346);
case deviceiPhone12Pro:
case deviceiPhone12:
return CGSizeMake(0.5393, 0.0379);
case deviceiPhone12Mini:
return CGSizeMake(0.604, 0.0424);
case deviceiPhone11ProMax:
return CGSizeMake(0.5057, 0.0335);
case deviceiPhone11Pro:
return CGSizeMake(0.5583, 0.037);
case deviceiPhone11:
case deviceiPhoneXR:
return CGSizeMake(0.5568, 0.0398);
case deviceiPhoneXSMax:
return CGSizeMake(0.4884, 0.0333);
case deviceiPhoneX:
case deviceiPhoneXS:
return CGSizeMake(0.5391, 0.0368);
default:
NSCAssert(!UnityDeviceHasCutout(), @"Device has a cutout, but no ratio has been added for it.");
return CGSizeZero;
}
}

View File

@ -0,0 +1,62 @@
#pragma once
@interface UnityViewControllerBase (iOS)
- (BOOL)shouldAutorotate;
- (BOOL)prefersStatusBarHidden;
- (UIStatusBarStyle)preferredStatusBarStyle;
@end
// we have several ViewController implementations, to better handle all the possible scenarios of setting orientation
// long long ago we had just once controller, handling everything
// then we have found that iOS does not "like" this, or rather it might behave in a way we don't want
// thus we split into one "default" view controller (handling orientation)
// and then per-orientation "fixed orientation" view controllers
// when we were changing orientation forcibly (or autorotation constraints) we were changing view controller to another one
// it turned out later that sometimes (on some devices) iOS 17 does not like this as in it could error/hang
// probably because it ended up having two orientation "processes": one from old controller and another from new one
// for example sometimes it was printing the error message: "A new orientation transaction token is being requested while a valid one already exists"
// thus we are returning back to using just one view controller (on iOS 16+)
// this makes sense especially since in iOS 16 special api to poke iOS about changing autorotation constraint was added
// so we can use it directly (and hope for the best) instead of doing this dance of recreating view controllers
// to support both old and new way without introducing too much copy-paste code, we will tweak
// UnityDefaultViewController to include "forced orientation" field that can be used in determining supported orientations
// should we handle fixed orientation in UnityDefaultViewController is defined by the app (as in, AppController will decide when creating root view controller)
// as we don't want to push the decision that low-level
// view controllers constrained to one orientation
@interface UnityFixedOrientationViewController : UnityViewControllerBase
- (instancetype)initWithOrientation:(UIInterfaceOrientation)interfaceOrientation;
@end
@interface UnityPortraitOnlyViewController : UnityFixedOrientationViewController
@end
@interface UnityPortraitUpsideDownOnlyViewController : UnityFixedOrientationViewController
@end
@interface UnityLandscapeLeftOnlyViewController : UnityFixedOrientationViewController
@end
@interface UnityLandscapeRightOnlyViewController : UnityFixedOrientationViewController
@end
// this is default view controller implementation (autorotation enabled)
// it also has the ability to support fixed orientation; this will be enabled by AppController when creating view controller on iOS 16+
@interface UnityDefaultViewController : UnityViewControllerBase
- (instancetype)initShouldHandleFixedOrientation:(BOOL)shouldHandleFixedOrientation;
// we have well defined points where we should update supported orientations:
// on init and inside [UnityAppController checkOrientationRequest]
// note that pre iOS 16 the latter will recreate default view controller if supported orientations conflict with the current orientation
// on iOS 16+ we are keeping one view controller and let it handle supported orientations by itself
// this is done as opposed to [UnityDefaultViewController supportedInterfaceOrientations] poking unity for that
// as this might happen in "random" places, out-of-sync with our handling of "orientation constraints were changed at unity side"
- (void)updateSupportedOrientations;
@property (nonatomic,readonly) BOOL willHandleFixedOrientation;
@end
NSUInteger EnabledAutorotationInterfaceOrientations();

View File

@ -0,0 +1,313 @@
#if PLATFORM_IOS
#import "UnityViewControllerBase.h"
#import "UnityAppController.h"
#include "OrientationSupport.h"
#include "Keyboard.h"
#include "UnityView.h"
#include "PluginBase/UnityViewControllerListener.h"
#include "UnityAppController.h"
#include "UnityAppController+ViewHandling.h"
#include "Unity/ObjCRuntime.h"
// when orientation changes with animation, pause rendering for this long so resolution change happens during animation with less visual distortion
const NSTimeInterval REORIENTATION_RENDERING_PAUSE = 0.15;
// when returning from presenting UIViewController we might need to update app orientation to "correct" one, as we wont get rotation notification
@interface UnityAppController ()
- (void)updateAppOrientation:(UIInterfaceOrientation)orientation;
@end
#ifndef __IPHONE_16_0
@interface UIViewController ()
- (void)setNeedsUpdateOfSupportedInterfaceOrientations;
@end
#endif
@implementation UnityViewControllerBase (iOS)
- (BOOL)shouldAutorotate
{
return YES;
}
- (BOOL)prefersStatusBarHidden
{
static bool _PrefersStatusBarHidden = true;
static bool _PrefersStatusBarHiddenInited = false;
if (!_PrefersStatusBarHiddenInited)
{
NSNumber* hidden = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"UIStatusBarHidden"];
_PrefersStatusBarHidden = hidden ? [hidden boolValue] : YES;
_PrefersStatusBarHiddenInited = true;
}
return _PrefersStatusBarHidden;
}
- (UIStatusBarStyle)preferredStatusBarStyle
{
static UIStatusBarStyle _PreferredStatusBarStyle = UIStatusBarStyleDefault;
static bool _PreferredStatusBarStyleInited = false;
if (!_PreferredStatusBarStyleInited)
{
NSString* style = [[[NSBundle mainBundle] infoDictionary] objectForKey: @"UIStatusBarStyle"];
if (style && [style isEqualToString: @"UIStatusBarStyleLightContent"])
_PreferredStatusBarStyle = UIStatusBarStyleLightContent;
_PreferredStatusBarStyleInited = true;
}
return _PreferredStatusBarStyle;
}
- (UIRectEdge)preferredScreenEdgesDeferringSystemGestures
{
UIRectEdge res = UIRectEdgeNone;
if (UnityGetDeferSystemGesturesTopEdge())
res |= UIRectEdgeTop;
if (UnityGetDeferSystemGesturesBottomEdge())
res |= UIRectEdgeBottom;
if (UnityGetDeferSystemGesturesLeftEdge())
res |= UIRectEdgeLeft;
if (UnityGetDeferSystemGesturesRightEdge())
res |= UIRectEdgeRight;
return res;
}
- (BOOL)prefersHomeIndicatorAutoHidden
{
return UnityGetHideHomeButton();
}
@end
@implementation UnityDefaultViewController
{
// these will be updated in one place where we "sync" UI side orientation handling to unity side
NSUInteger _supportedOrientations;
// this will be updated in one place where we "sync" UI side orientation handling to unity side
UIInterfaceOrientation _fixedOrientation;
// this indicates if we are asked to handle fixed orientation too - app should decide
BOOL _willHandleFixedOrientation;
}
- (BOOL)willHandleFixedOrientation
{
return _willHandleFixedOrientation;
}
- (void)readOrientationFromUnity
{
if(UnityShouldAutorotate())
{
_fixedOrientation = UIInterfaceOrientationUnknown;
_supportedOrientations = EnabledAutorotationInterfaceOrientations();
}
else
{
_fixedOrientation = ConvertToIosScreenOrientation((ScreenOrientation)UnityRequestedScreenOrientation());
_supportedOrientations = (1 << _fixedOrientation);
}
}
- (instancetype)initShouldHandleFixedOrientation:(BOOL)shouldHandleFixedOrientation
{
if ((self = [super init]))
{
_willHandleFixedOrientation = shouldHandleFixedOrientation;
NSAssert(UnityShouldAutorotate() || _willHandleFixedOrientation,
@"UnityDefaultViewController should be used either if unity is set to autorotate, or if asked explicitly to handle fixed orientation");
[self readOrientationFromUnity];
}
return self;
}
- (void)updateSupportedOrientations
{
[self readOrientationFromUnity];
if (@available(iOS 16.0, *))
[self setNeedsUpdateOfSupportedInterfaceOrientations];
}
- (NSUInteger)supportedInterfaceOrientations
{
return _supportedOrientations;
}
- (void)viewWillAppear:(BOOL)animated
{
ScreenOrientation currentOrientation = UIViewControllerOrientation(self);
[GetAppController() updateAppOrientation: ConvertToIosScreenOrientation(currentOrientation)];
[super viewWillAppear: animated];
}
- (void)viewDidAppear:(BOOL)animated
{
ScreenOrientation currentOrientation = UIViewControllerOrientation(self);
[GetAppController() updateAppOrientation: ConvertToIosScreenOrientation(currentOrientation)];
[super viewDidAppear: animated];
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
// CODE ARCHEOLOGY: we were using UIViewControllerOrientation, but on showing view with "Requires full screen"
// CODE ARCHEOLOGY: we will get the size/orientation *already* set, and the rotation logic would break
const ScreenOrientation curOrient = GetAppController().unityView.contentOrientation;
const ScreenOrientation newOrient = OrientationAfterTransform(curOrient, [coordinator targetTransform]);
// delay resolution change, ideally we want it to happen in the middle of rotation animation
// we force rendering back upon completion, just in case transition happens sooner
GetAppController().unityView.skipRendering = YES;
[GetAppController().unityView performSelector: @selector(resumeRendering) withObject: nil afterDelay: REORIENTATION_RENDERING_PAUSE];
// in case of presentation controller it will take control over orientations
// so to avoid crazy corner cases, make default view controller to ignore "wrong" orientations
// as they will come only in case of presentation view controller and will be reverted anyway
// NB: we still want to pass message to super, we just want to skip unity-specific magic
NSUInteger targetMask = 1 << ConvertToIosScreenOrientation(newOrient);
if (([self supportedInterfaceOrientations] & targetMask) != 0)
{
[UIView setAnimationsEnabled: UnityUseAnimatedAutorotation() ? YES : NO];
[KeyboardDelegate StartReorientation];
[GetAppController() interfaceWillChangeOrientationTo: ConvertToIosScreenOrientation(newOrient)];
[coordinator animateAlongsideTransition: nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
[self.view setNeedsLayout];
[GetAppController() interfaceDidChangeOrientationFrom: ConvertToIosScreenOrientation(curOrient)];
[KeyboardDelegate FinishReorientation];
[UIView setAnimationsEnabled: YES];
GetAppController().unityView.skipRendering = NO;
}];
}
[super viewWillTransitionToSize: size withTransitionCoordinator: coordinator];
}
@end
@interface UnityFixedOrientationViewController()
{
UIInterfaceOrientation _fixedOrientation;
}
@end
@implementation UnityFixedOrientationViewController
- (instancetype)initWithOrientation:(UIInterfaceOrientation)interfaceOrientation
{
self = [super init];
if (self) {
_fixedOrientation = interfaceOrientation;
}
return self;
}
- (NSUInteger)supportedInterfaceOrientations
{
return 1 << _fixedOrientation;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return _fixedOrientation;
}
- (void)viewWillAppear:(BOOL)animated
{
[GetAppController() updateAppOrientation: _fixedOrientation];
[super viewWillAppear: animated];
}
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
// Adding a call to notify about changed orientation. In iOS16 there was a runtime change where view controller
// is not fully set up as soon as we make the view controller change in AppController at -transitionToViewController:.
// And instead iOS calls this method, in other cases this method is not called. So we want to call
// didTransitionToViewController here as this is the place where we get updated orientation.
//
// NB: Look for additional explanation at UnityAppController+ViewHandling.mm method -transitionToViewController: before
// call to same method.
[GetAppController() didTransitionToViewController:self fromViewController:self];
[super viewWillTransitionToSize: size withTransitionCoordinator: coordinator];
}
@end
@implementation UnityPortraitOnlyViewController
- (instancetype)init
{
self = [super initWithOrientation:UIInterfaceOrientationPortrait];
return self;
}
@end
@implementation UnityPortraitUpsideDownOnlyViewController
- (instancetype)init
{
self = [super initWithOrientation:UIInterfaceOrientationPortraitUpsideDown];
return self;
}
@end
@implementation UnityLandscapeLeftOnlyViewController
- (instancetype)init
{
self = [super initWithOrientation:UIInterfaceOrientationLandscapeLeft];
return self;
}
@end
@implementation UnityLandscapeRightOnlyViewController
- (instancetype)init
{
self = [super initWithOrientation:UIInterfaceOrientationLandscapeRight];
return self;
}
@end
NSUInteger EnabledAutorotationInterfaceOrientations()
{
NSUInteger ret = 0;
if (UnityIsOrientationEnabled(portrait))
ret |= (1 << UIInterfaceOrientationPortrait);
if (UnityDeviceSupportsUpsideDown() && UnityIsOrientationEnabled(portraitUpsideDown))
ret |= (1 << UIInterfaceOrientationPortraitUpsideDown);
if (UnityIsOrientationEnabled(landscapeLeft))
ret |= (1 << UIInterfaceOrientationLandscapeRight);
if (UnityIsOrientationEnabled(landscapeRight))
ret |= (1 << UIInterfaceOrientationLandscapeLeft);
// Handling unexpected case where autorotation is on and all the orientations are off by defaulting to current orientation.
// Previously we returned 0 and iOS were handling it by keeping orientation as is. From iOS16 behaviour changed and the bug was raised.
// Either way iOS requires us to provide non 0 value to supportedInterfaceOrientations.
if (ret == 0)
{
NSLog(@"[Error] All orientations are off for autorotation. Preventing crash by using current orientation.");
ret = (1 << [GetAppController() interfaceOrientation]);
}
return ret;
}
#endif // PLATFORM_IOS

View File

@ -0,0 +1,7 @@
#pragma once
//for tvOS we need just one view controller subclass as there is no screen orientation here
@interface UnityDefaultViewController : UnityViewControllerBase
{
}
@end

View File

@ -0,0 +1,9 @@
#if PLATFORM_TVOS
#import "UnityViewControllerBase.h"
#import "UnityAppController.h"
@implementation UnityDefaultViewController
@end
#endif // PLATFORM_TVOS

View File

@ -0,0 +1,7 @@
#pragma once
//for visionos we need just one view controller subclass as there is no screen orientation here
@interface UnityDefaultViewController : UnityViewControllerBase
{
}
@end

View File

@ -0,0 +1,9 @@
#if PLATFORM_VISIONOS
#import "UnityViewControllerBase.h"
#import "UnityAppController.h"
@implementation UnityDefaultViewController
@end
#endif // PLATFORM_VISIONOS

View File

@ -0,0 +1,42 @@
#pragma once
#import <UIKit/UIKit.h>
#import "PluginBase/UnityViewControllerListener.h"
#if PLATFORM_IOS || PLATFORM_VISIONOS
#define UNITY_VIEW_CONTROLLER_BASE_CLASS UIViewController
#elif PLATFORM_TVOS
#import <GameController/GCEventViewController.h>
#define UNITY_VIEW_CONTROLLER_BASE_CLASS GCEventViewController
#endif
@interface UnityViewControllerBase : UNITY_VIEW_CONTROLLER_BASE_CLASS
{
id<UnityViewControllerNotifications> _notificationDelegate;
}
- (void)viewWillLayoutSubviews;
- (void)viewDidLayoutSubviews;
- (void)viewDidDisappear:(BOOL)animated;
- (void)viewWillDisappear:(BOOL)animated;
- (void)viewDidAppear:(BOOL)animated;
- (void)viewWillAppear:(BOOL)animated;
@property (nonatomic, retain) id<UnityViewControllerNotifications> notificationDelegate;
@end
#if PLATFORM_IOS
#include "UnityViewControllerBase+iOS.h"
#elif PLATFORM_TVOS
#include "UnityViewControllerBase+tvOS.h"
#elif PLATFORM_VISIONOS
#include "UnityViewControllerBase+visionOS.h"
#endif
// this should be used to create view controller that plays nicely with unity and account for player settings
UnityViewControllerBase* AllocUnityViewController(void);
UnityViewControllerBase* AllocUnityDefaultViewController(void);
#if UNITY_SUPPORT_ROTATION
UnityViewControllerBase* AllocUnitySingleOrientationViewController(UIInterfaceOrientation orient);
#endif

View File

@ -0,0 +1,90 @@
#import "UnityViewControllerBase.h"
#import "UnityAppController.h"
#import "UnityAppController+ViewHandling.h"
#include "OrientationSupport.h"
@implementation UnityViewControllerBase
@synthesize notificationDelegate = _notificationDelegate;
- (id)init
{
if ((self = [super init]))
self.modalPresentationStyle = UIModalPresentationFullScreen;
return self;
}
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
[_notificationDelegate onViewWillLayoutSubviews];
}
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
[_notificationDelegate onViewDidLayoutSubviews];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear: animated];
[_notificationDelegate onViewDidDisappear: animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear: animated];
[_notificationDelegate onViewWillDisappear: animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear: animated];
[_notificationDelegate onViewDidAppear: animated];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
[_notificationDelegate onViewWillAppear: animated];
}
@end
UnityViewControllerBase* AllocUnityDefaultViewController()
{
return [UnityDefaultViewController alloc];
}
#if UNITY_SUPPORT_ROTATION
UnityViewControllerBase* AllocUnitySingleOrientationViewController(UIInterfaceOrientation orient)
{
switch (orient)
{
case UIInterfaceOrientationPortrait: return [UnityPortraitOnlyViewController alloc];
case UIInterfaceOrientationPortraitUpsideDown: return [UnityPortraitUpsideDownOnlyViewController alloc];
case UIInterfaceOrientationLandscapeLeft: return [UnityLandscapeLeftOnlyViewController alloc];
case UIInterfaceOrientationLandscapeRight: return [UnityLandscapeRightOnlyViewController alloc];
default: assert(false && "bad UIInterfaceOrientation provided");
}
return nil;
}
#endif
UnityViewControllerBase* AllocUnityViewController()
{
#if UNITY_SUPPORT_ROTATION
if (UnityShouldAutorotate())
return AllocUnityDefaultViewController();
UIInterfaceOrientation orient = ConvertToIosScreenOrientation((ScreenOrientation)UnityRequestedScreenOrientation());
return AllocUnitySingleOrientationViewController(orient);
#else
return AllocUnityDefaultViewController();
#endif
}

123
Classes/UndefinePlatforms.h Normal file
View File

@ -0,0 +1,123 @@
// DO NOT PUT #pragma once or include guard check here
// This header is designed to be able to be included multiple times
// This header is used to temporary undefine all platform definitions in case there is a naming conflict with
// 3rd party code. Please make sure to always use this paired with the RedefinePlatforms.h header.
//
// ex.
//
// #include "UndefinePlatforms.h"
// #include "Some3rdParty.h"
// #include "RedefinePlatforms.h"
#ifdef DETAIL__PLATFORMS_HAD_BEEN_UNDEFINED_BY_UNDEFINEPLATFORMS_H
#error "UndefinePlatforms.h has been included more than once or RedefinePlatforms.h is missing."
#endif
// define all other platforms to 0
#if PLATFORM_WIN
#define DETAIL__TEMP_PLATFORM_WIN_WAS_1
#endif
#undef PLATFORM_WIN
#if PLATFORM_OSX
#define DETAIL__TEMP_PLATFORM_OSX_WAS_1
#endif
#undef PLATFORM_OSX
#if PLATFORM_LINUX
#define DETAIL__TEMP_PLATFORM_LINUX_WAS_1
#endif
#undef PLATFORM_LINUX
#if PLATFORM_WINRT
#define DETAIL__TEMP_PLATFORM_WINRT_WAS_1
#endif
#undef PLATFORM_WINRT
#if PLATFORM_FAMILY_WINDOWSGAMES
#define DETAIL__TEMP_PLATFORM_FAMILY_WINDOWSGAMES_WAS_1
#endif
#undef PLATFORM_FAMILY_WINDOWSGAMES
#if PLATFORM_WEBGL
#define DETAIL__TEMP_PLATFORM_WEBGL_WAS_1
#endif
#undef PLATFORM_WEBGL
#if PLATFORM_WASI
#define DETAIL__TEMP_PLATFORM_WASI_WAS_1
#endif
#undef PLATFORM_WASI
#if PLATFORM_ANDROID
#define DETAIL__TEMP_PLATFORM_ANDROID_WAS_1
#endif
#undef PLATFORM_ANDROID
#if PLATFORM_PS4
#define DETAIL__TEMP_PLATFORM_PS4_WAS_1
#endif
#undef PLATFORM_PS4
#if PLATFORM_PS5
#define DETAIL__TEMP_PLATFORM_PS5_WAS_1
#endif
#undef PLATFORM_PS5
#if PLATFORM_IPHONE
#define DETAIL__TEMP_PLATFORM_IPHONE_WAS_1
#endif
#undef PLATFORM_IPHONE
#if PLATFORM_IOS
#define DETAIL__TEMP_PLATFORM_IOS_WAS_1
#endif
#undef PLATFORM_IOS
#if PLATFORM_TVOS
#define DETAIL__TEMP_PLATFORM_TVOS_WAS_1
#endif
#undef PLATFORM_TVOS
#if PLATFORM_VISIONOS
#define DETAIL__TEMP_PLATFORM_VISIONOS_WAS_1
#endif
#undef PLATFORM_VISIONOS
#if PLATFORM_XBOXONE
#define DETAIL__TEMP_PLATFORM_XBOXONE_WAS_1
#endif
#undef PLATFORM_XBOXONE
#if PLATFORM_SWITCH
#define DETAIL__TEMP_PLATFORM_SWITCH_WAS_1
#endif
#undef PLATFORM_SWITCH
#if PLATFORM_LUMIN
#define DETAIL__TEMP_PLATFORM_LUMIN_WAS_1
#endif
#undef PLATFORM_LUMIN
#if PLATFORM_STADIA
#define DETAIL__TEMP_PLATFORM_STADIA_WAS_1
#endif
#undef PLATFORM_STADIA
#if PLATFORM_NETBSD
#define DETAIL__TEMP_PLATFORM_NETBSD_WAS_1
#endif
#undef PLATFORM_NETBSD
#if PLATFORM_EMBEDDED_LINUX
#define DETAIL__TEMP_PLATFORM_EMBEDDED_LINUX_WAS_1
#endif
#undef PLATFORM_EMBEDDED_LINUX
#if PLATFORM_QNX
#define DETAIL__TEMP_PLATFORM_QNX_WAS_1
#endif
#undef PLATFORM_QNX
#define DETAIL__PLATFORMS_HAD_BEEN_UNDEFINED_BY_UNDEFINEPLATFORMS_H

16
Classes/Unity/AVCapture.h Normal file
View File

@ -0,0 +1,16 @@
#pragma once
enum
{
avCapturePermissionUnknown = 0,
avCapturePermissionGranted = 1,
avCapturePermissionDenied = 2,
};
enum
{
avVideoCapture = 1,
avAudioCapture = 2,
};
extern "C" int UnityGetAVCapturePermission(int captureType);
extern "C" void UnityRequestAVCapturePermission(int captureType, void* userData);

View File

@ -0,0 +1,45 @@
#include "AVCapture.h"
#include <AVFoundation/AVFoundation.h>
static NSString* MediaTypeFromEnum(int captureType)
{
if (captureType == avAudioCapture)
return AVMediaTypeAudio;
else if (captureType == avVideoCapture)
return AVMediaTypeVideo;
return nil;
}
extern "C" int UnityGetAVCapturePermission(int captureType)
{
NSString* mediaType = MediaTypeFromEnum(captureType);
if (mediaType == nil)
return avCapturePermissionDenied;
#if !PLATFORM_TVOS && (UNITY_USES_WEBCAM || UNITY_USES_MICROPHONE)
NSInteger status = AVAuthorizationStatusAuthorized;
status = [AVCaptureDevice authorizationStatusForMediaType: mediaType];
if (status == AVAuthorizationStatusNotDetermined)
return avCapturePermissionUnknown;
else if (status == AVAuthorizationStatusAuthorized)
return avCapturePermissionGranted;
#endif
return avCapturePermissionDenied;
}
extern "C" void UnityRequestAVCapturePermission(int captureType, void* userData)
{
#if !PLATFORM_TVOS && (UNITY_USES_WEBCAM || UNITY_USES_MICROPHONE)
NSString* mediaType = MediaTypeFromEnum(captureType);
if (mediaType == nil)
return;
[AVCaptureDevice requestAccessForMediaType: mediaType completionHandler:^(BOOL granted) {
UnityReportAVCapturePermission(userData);
}];
#endif
}

View File

@ -0,0 +1,19 @@
#pragma once
// small helper for getting texture from CMSampleBuffer
typedef struct
CMVideoSampling
{
void* cvTextureCache;
void* cvTextureCacheTexture;
void* cvImageBuffer;
}
CMVideoSampling;
void CMVideoSampling_Initialize(CMVideoSampling* sampling);
void CMVideoSampling_Uninitialize(CMVideoSampling* sampling);
intptr_t CMVideoSampling_ImageBuffer(CMVideoSampling* sampling, CVImageBufferRef buffer, size_t* w, size_t* h);
intptr_t CMVideoSampling_SampleBuffer(CMVideoSampling* sampling, void* buffer, size_t* w, size_t* h); // buffer is CMSampleBufferRef
intptr_t CMVideoSampling_LastSampledTexture(CMVideoSampling* sampling);

View File

@ -0,0 +1,79 @@
#include "CMVideoSampling.h"
#include "CVTextureCache.h"
#include <AVFoundation/AVFoundation.h>
#include "DisplayManager.h" // for GetMainDisplaySurface() to have proper linear/srgb handling
void CMVideoSampling_Initialize(CMVideoSampling* sampling)
{
::memset(sampling, 0x00, sizeof(CMVideoSampling));
sampling->cvTextureCache = CreateCVTextureCache();
}
void CMVideoSampling_Uninitialize(CMVideoSampling* sampling)
{
if (sampling->cvImageBuffer)
{
CFRelease(sampling->cvImageBuffer);
sampling->cvImageBuffer = 0;
}
if (sampling->cvTextureCacheTexture)
{
CFRelease(sampling->cvTextureCacheTexture);
sampling->cvTextureCacheTexture = 0;
}
if (sampling->cvTextureCache)
{
CFRelease(sampling->cvTextureCache);
sampling->cvTextureCache = 0;
}
}
intptr_t CMVideoSampling_ImageBuffer(CMVideoSampling* sampling, CVImageBufferRef buffer, size_t* w, size_t* h)
{
intptr_t retTex = 0;
if (sampling->cvImageBuffer)
CFRelease(sampling->cvImageBuffer);
sampling->cvImageBuffer = buffer;
CFRetain(sampling->cvImageBuffer);
*w = CVPixelBufferGetWidth((CVImageBufferRef)sampling->cvImageBuffer);
*h = CVPixelBufferGetHeight((CVImageBufferRef)sampling->cvImageBuffer);
if (sampling->cvTextureCacheTexture)
{
CFRelease(sampling->cvTextureCacheTexture);
FlushCVTextureCache(sampling->cvTextureCache);
sampling->cvTextureCacheTexture = nil;
}
OSType pixelFormat = CVPixelBufferGetPixelFormatType(buffer);
if (pixelFormat == kCVPixelFormatType_32BGRA || pixelFormat == kCVPixelFormatType_DepthFloat16)
{
MTLPixelFormat metalFormat32BGRA = GetMainDisplaySurface()->srgb ? MTLPixelFormatBGRA8Unorm_sRGB : MTLPixelFormatBGRA8Unorm;
MTLPixelFormat metalFormat = pixelFormat == kCVPixelFormatType_32BGRA ? metalFormat32BGRA : MTLPixelFormatR16Float;
sampling->cvTextureCacheTexture = CreateTextureFromCVTextureCache2(sampling->cvTextureCache, sampling->cvImageBuffer, *w, *h, metalFormat);
}
else
{
#define FourCC2Str(fourcc) (const char[]){*(((char*)&fourcc)+3), *(((char*)&fourcc)+2), *(((char*)&fourcc)+1), *(((char*)&fourcc)+0),0}
::printf("CMVideoSampling_SampleBuffer: unexpected pixel format \'%s\'\n", FourCC2Str(pixelFormat));
}
if (sampling->cvTextureCacheTexture)
retTex = GetTextureFromCVTextureCache(sampling->cvTextureCacheTexture);
return retTex;
}
intptr_t CMVideoSampling_SampleBuffer(CMVideoSampling* sampling, void* buffer, size_t* w, size_t* h)
{
return CMVideoSampling_ImageBuffer(sampling, CMSampleBufferGetImageBuffer((CMSampleBufferRef)buffer), w, h);
}
intptr_t CMVideoSampling_LastSampledTexture(CMVideoSampling* sampling)
{
return GetTextureFromCVTextureCache(sampling->cvTextureCacheTexture);
}

View File

@ -0,0 +1,47 @@
#pragma once
#include <stdint.h>
// returns CVMetalTextureCacheRef
void* CreateCVTextureCache();
// cache = CVMetalTextureCacheRef
void FlushCVTextureCache(void* cache);
// returns CVMetalTextureRef
// cache = CVMetalTextureCacheRef
// image = CVImageBufferRef/CVPixelBufferRef
void* CreateTextureFromCVTextureCache2(void* cache, void* image, size_t w, size_t h, uint64_t metalFormat);
// texture = CVMetalTextureRef
MTLTextureRef GetMetalTextureFromCVTextureCache(void* texture);
// texture = CVMetalTextureRef
uintptr_t GetTextureFromCVTextureCache(void* texture);
// returns CVPixelBufferRef
void* CreatePixelBufferForCVTextureCache2(size_t w, size_t h, uint32_t cvFormat);
// returns CVMetalTextureRef
// cache = CVMetalTextureCacheRef
// pb = CVPixelBufferRef (out)
void* CreateReadableRTFromCVTextureCache2(void* cache, size_t w, size_t h, uint32_t cvFormat, uint64_t metalFormat, void** pb);
// texture = CVMetalTextureRef
int IsCVTextureFlipped(void* texture);
//
// deprecated
//
// returns CVPixelBufferRef
// enforces kCVPixelFormatType_32BGRA
void* CreatePixelBufferForCVTextureCache(size_t w, size_t h);
// returns CVMetalTextureRef
// cache = CVMetalTextureCacheRef
// pb = CVPixelBufferRef (out)
// enforces rgba texture with bgra backing
void* CreateReadableRTFromCVTextureCache(void* cache, size_t w, size_t h, void** pb);
// returns CVMetalTextureRef
// cache = CVMetalTextureCacheRef
// image = CVImageBufferRef/CVPixelBufferRef
void* CreateBGRA32TextureFromCVTextureCache(void* cache, void* image, size_t w, size_t h);
void* CreateHalfFloatTextureFromCVTextureCache(void* cache, void* image, size_t w, size_t h);

View File

@ -0,0 +1,145 @@
#include "CVTextureCache.h"
#include "DisplayManager.h"
#include "UnityMetalSupport.h"
#include <CoreVideo/CVMetalTextureCache.h>
void* CreateCVTextureCache()
{
void* ret = 0;
CVReturn err = 0;
if (UnitySelectedRenderingAPI() == apiMetal)
err = CVMetalTextureCacheCreate(kCFAllocatorDefault, 0, UnityGetMetalDevice(), 0, (CVMetalTextureCacheRef*)&ret);
if (err)
{
::printf("Error at CVMetalTextureCacheCreate: %d", err);
ret = 0;
}
return ret;
}
void FlushCVTextureCache(void* cache)
{
if (UnitySelectedRenderingAPI() == apiMetal)
CVMetalTextureCacheFlush((CVMetalTextureCacheRef)cache, 0);
}
void* CreateTextureFromCVTextureCache2(void* cache, void* image, size_t w, size_t h, uint64_t metalFormat)
{
void* texture = 0;
CVReturn err = 0;
if (UnitySelectedRenderingAPI() == apiMetal)
{
err = CVMetalTextureCacheCreateTextureFromImage(
kCFAllocatorDefault, (CVMetalTextureCacheRef)cache, (CVImageBufferRef)image, 0,
(MTLPixelFormat)metalFormat, w, h, 0, (CVMetalTextureRef*)&texture
);
}
if (err)
{
::printf("Error at CVMetalTextureCacheCreateTextureFromImage: %d\n", err);
texture = 0;
}
return texture;
}
id<MTLTexture> GetMetalTextureFromCVTextureCache(void* texture)
{
assert(UnitySelectedRenderingAPI() == apiMetal);
return CVMetalTextureGetTexture((CVMetalTextureRef)texture);
}
uintptr_t GetTextureFromCVTextureCache(void* texture)
{
if (UnitySelectedRenderingAPI() == apiMetal)
return (uintptr_t)(__bridge void*)GetMetalTextureFromCVTextureCache(texture);
return 0;
}
void* CreatePixelBufferForCVTextureCache2(size_t w, size_t h, uint32_t cvFormat)
{
CVPixelBufferRef pb = 0;
NSDictionary* options = @{ (__bridge NSString*)kCVPixelBufferPixelFormatTypeKey: @(cvFormat),
(__bridge NSString*)kCVPixelBufferWidthKey: @(w),
(__bridge NSString*)kCVPixelBufferHeightKey: @(h),
(__bridge NSString*)kCVPixelBufferMetalCompatibilityKey: @(YES),
(__bridge NSString*)kCVPixelBufferIOSurfacePropertiesKey: @{}};
CVPixelBufferCreate(kCFAllocatorDefault, w, h, cvFormat, (__bridge CFDictionaryRef)options, &pb);
return pb;
}
void* CreateReadableRTFromCVTextureCache2(void* cache, size_t w, size_t h, uint32_t cvFormat, uint64_t metalFormat, void** pb)
{
*pb = CreatePixelBufferForCVTextureCache2(w, h, cvFormat);
return CreateTextureFromCVTextureCache2(cache, *pb, w, h, metalFormat);
}
int IsCVTextureFlipped(void* texture)
{
if (UnitySelectedRenderingAPI() == apiMetal)
return CVMetalTextureIsFlipped((CVMetalTextureRef)texture);
return 0;
}
//
// deprecated
//
void* CreatePixelBufferForCVTextureCache(size_t w, size_t h)
{
return CreatePixelBufferForCVTextureCache2(w, h, kCVPixelFormatType_32BGRA);
}
void* CreateReadableRTFromCVTextureCache(void* cache, size_t w, size_t h, void** pb)
{
*pb = CreatePixelBufferForCVTextureCache2(w, h, kCVPixelFormatType_32BGRA);
return CreateBGRA32TextureFromCVTextureCache(cache, *pb, w, h);
}
void* CreateBGRA32TextureFromCVTextureCache(void* cache, void* image, size_t w, size_t h)
{
void* texture = 0;
CVReturn err = 0;
if (UnitySelectedRenderingAPI() == apiMetal)
{
err = CVMetalTextureCacheCreateTextureFromImage(
kCFAllocatorDefault, (CVMetalTextureCacheRef)cache, (CVImageBufferRef)image, 0,
(MTLPixelFormat)((UnityDisplaySurfaceMTL*)GetMainDisplaySurface())->colorFormat, w, h, 0, (CVMetalTextureRef*)&texture
);
}
if (err)
{
::printf("Error at CVMetalTextureCacheCreateTextureFromImage: %d\n", err);
texture = 0;
}
return texture;
}
void* CreateHalfFloatTextureFromCVTextureCache(void* cache, void* image, size_t w, size_t h)
{
void* texture = 0;
CVReturn err = 0;
if (UnitySelectedRenderingAPI() == apiMetal)
{
err = CVMetalTextureCacheCreateTextureFromImage(
kCFAllocatorDefault, (CVMetalTextureCacheRef)cache, (CVImageBufferRef)image, 0,
MTLPixelFormatR16Float, w, h, 0, (CVMetalTextureRef*)&texture
);
}
if (err)
{
::printf("Error at CVMetalTextureCacheCreateTextureFromImage: %d\n", err);
texture = 0;
}
return texture;
}

View File

@ -0,0 +1,70 @@
#pragma once
#if !PLATFORM_TVOS && UNITY_USES_WEBCAM
#import <AVFoundation/AVFoundation.h>
#if PLATFORM_VISIONOS
@interface CameraCaptureController : NSObject<AVCaptureVideoDataOutputSampleBufferDelegate>
#else
@interface CameraCaptureController : NSObject<AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureDataOutputSynchronizerDelegate>
#endif
- (bool)initCapture:(AVCaptureDevice*)device;
- (bool)initCapture:(AVCaptureDevice*)device preset:(NSString*)preset fps:(float)fps;
- (void)setCaptureFPS:(float)fps;
- (bool)initColorAndDepthCameraCapture:(AVCaptureDevice*)device preset:(NSString*)preset fps:(float)fps isDepth:(bool)isDepth;
- (void)initColorAndDepthCameraCaptureSession;
- (void)clearColorAndDepthCameraCaptureSession;
- (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection;
#if !PLATFORM_VISIONOS
- (void)dataOutputSynchronizer:(AVCaptureDataOutputSynchronizer *)synchronizer didOutputSynchronizedDataCollection:(AVCaptureSynchronizedDataCollection *)synchronizedDataCollection;
+ (BOOL)focusPointSupported:(AVCaptureDevice*)captureDevice withFocusMode:(AVCaptureFocusMode)focusMode;
#endif
+ (NSMutableArray<CameraCaptureController*>*)getActiveColorAndDepthCameraControllers;
+ (void)addColorAndDepthCameraController:(CameraCaptureController*)controller;
+ (void)removeColorAndDepthCameraController:(CameraCaptureController*)controller;
+ (void)clearColorAndDepthCameraControllers;
+ (CameraCaptureController*)findColorAndDepthCameraController:(AVCaptureDevice*)device isDepth:(bool)isDepth;
- (void)capturePixelBufferToMemBuffer:(uint8_t*)dst;
- (int)isCVTextureFlipped;
- (int)setFocusPointWithX:(float)x Y:(float)y;
- (int)setFocusPoint;
- (void)start;
- (void)pause;
- (void)stop;
@property (nonatomic, retain) AVCaptureDevice* captureDevice;
@property (nonatomic, retain) AVCaptureSession* captureSession;
@property (nonatomic, retain) AVCaptureDeviceInput* captureInput;
@property (nonatomic, retain) AVCaptureVideoDataOutput* captureOutput;
#if !PLATFORM_VISIONOS
@property (nonatomic, retain) AVCaptureDepthDataOutput* captureDepthOutput;
@property (nonatomic, retain) AVCaptureDataOutputSynchronizer* captureSynchronizer;
#endif
- (float)pickAvailableFrameRate:(float)fps;
@end
enum WebCamKind
{
kWebCamWideAngle = 1,
kWebCamTelephoto = 2,
kWebCamColorAndDepth = 3,
kWebCamUltraWideAngle = 4,
};
@interface CameraCaptureDevice : NSObject
- (bool)isColorAndDepthCaptureDevice;
- (WebCamKind)getKind;
- (void)fillCaptureDeviceResolutions;
- (NSString*)pickPresetFromWidth:(int)w height:(int)h;
- (bool)initCaptureForController:(CameraCaptureController*)controller width:(int)w height:(int)h fps:(float)fps isDepth:(bool)isDepth;
+ (bool)initialized;
+ (void)createCameraCaptureDevicesArray;
+ (void)addCameraCaptureDevice:(AVCaptureDevice*)device;
@end
#endif

View File

@ -0,0 +1,861 @@
#if !PLATFORM_TVOS && UNITY_USES_WEBCAM
#include "CameraCapture.h"
#include "AVCapture.h"
#include "CMVideoSampling.h"
#include "CVTextureCache.h"
#import <CoreVideo/CoreVideo.h>
#include <cmath>
static NSMutableArray<CameraCaptureController*> *activeColorAndDepthCameraControllers = nil;
@implementation CameraCaptureController
{
AVCaptureDevice* _captureDevice;
AVCaptureSession* _captureSession;
AVCaptureDeviceInput* _captureInput;
AVCaptureVideoDataOutput* _captureOutput;
#if !PLATFORM_VISIONOS
AVCaptureDepthDataOutput* _captureDepthOutput;
AVCaptureDataOutputSynchronizer* _captureSynchronizer;
#endif
@public bool _isDepth;
uint8_t* _pixelBufferCopy;
CMVideoSampling _cmVideoSampling;
NSString* _preset;
CGPoint _focusPoint;
#if !PLATFORM_VISIONOS
AVCaptureFocusMode _focusMode;
#endif
@public void* _userData;
@public size_t _width, _height;
}
- (bool)initCapture:(AVCaptureDevice*)device
{
if (UnityGetAVCapturePermission(avVideoCapture) == avCapturePermissionDenied)
return false;
self.captureDevice = device;
#if PLATFORM_VISIONOS
self.captureInput = [[AVCaptureDeviceInput alloc] initWithDevice: device error:nil];
#else
self.captureInput = [AVCaptureDeviceInput deviceInputWithDevice: device error: nil];
#endif
self.captureOutput = [[AVCaptureVideoDataOutput alloc] init];
if (self.captureOutput == nil || self.captureInput == nil)
return false;
self.captureOutput.alwaysDiscardsLateVideoFrames = YES;
NSDictionary* options = @{ (NSString*)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA) };
[self.captureOutput setVideoSettings: options];
CMVideoSampling_Initialize(&self->_cmVideoSampling);
_width = _height = 0;
_focusPoint = CGPointMake(0.5, 0.5); // default focus point is center
#if !PLATFORM_VISIONOS
_focusMode = AVCaptureFocusModeContinuousAutoFocus;
#endif
_pixelBufferCopy = nullptr;
return true;
}
- (void)setCaptureFPS:(float)fps
{
if ([self.captureDevice lockForConfiguration: nil])
{
if (self.captureDevice.activeFormat)
{
fps = [self pickAvailableFrameRate: fps];
self.captureDevice.activeVideoMinFrameDuration = CMTimeMake(1, fps);
self.captureDevice.activeVideoMaxFrameDuration = CMTimeMake(1, fps);
}
else
{
#if !PLATFORM_VISIONOS
// In some corner cases (seeing this on iPod iOS 6.1.5) activeFormat is null.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
self.captureOutput.minFrameDuration = CMTimeMake(1, fps);
#pragma clang diagnostic pop
#endif
}
[self.captureDevice unlockForConfiguration];
}
}
- (bool)initCapture:(AVCaptureDevice*)device preset:(NSString*)preset fps:(float)fps
{
if (![self initCapture: device])
return false;
self.captureSession = [[AVCaptureSession alloc] init];
if ([self.captureSession canAddInput: self.captureInput])
[self.captureSession addInput: self.captureInput];
else
return false;
if ([self.captureSession canAddOutput: self.captureOutput])
[self.captureSession addOutput: self.captureOutput];
else
return false;
// queue on main thread to simplify gles life
[self.captureOutput setSampleBufferDelegate: self queue: dispatch_get_main_queue()];
self->_preset = preset;
#if !PLATFORM_VISIONOS
[self.captureSession setSessionPreset: preset];
#endif
[self setCaptureFPS: fps];
return true;
}
- (void)captureOutput:(AVCaptureOutput*)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection*)connection
{
intptr_t tex = (intptr_t)CMVideoSampling_SampleBuffer(&self->_cmVideoSampling, sampleBuffer, &_width, &_height);
UnityDidCaptureVideoFrame(tex, self->_userData);
}
- (void)capturePixelBufferToMemBuffer:(uint8_t*)dst
{
CVPixelBufferRef pbuf = (CVPixelBufferRef)self->_cmVideoSampling.cvImageBuffer;
const size_t srcRowSize = CVPixelBufferGetBytesPerRow(pbuf);
const size_t bufSize = srcRowSize * self->_height;
if (self->_pixelBufferCopy == nullptr)
{
self->_pixelBufferCopy = (uint8_t*)::malloc(bufSize);
}
// while not the best way memory-wise, we want to minimize stalling
CVPixelBufferLockBaseAddress(pbuf, kCVPixelBufferLock_ReadOnly);
{
::memcpy(self->_pixelBufferCopy, CVPixelBufferGetBaseAddress(pbuf), bufSize);
}
CVPixelBufferUnlockBaseAddress(pbuf, kCVPixelBufferLock_ReadOnly);
OSType pixelFormat = CVPixelBufferGetPixelFormatType(pbuf);
size_t bpp = 0;
switch (pixelFormat)
{
case kCVPixelFormatType_32BGRA:
bpp = 4;
break;
case kCVPixelFormatType_DepthFloat16:
bpp = 2;
break;
default:
assert(false);
break;
}
const size_t dstRowSize = self->_width * bpp;
uint8_t* src = self->_pixelBufferCopy + (self->_height - 1) * srcRowSize;
for (size_t i = 0; i < self->_height; ++i)
{
::memcpy(dst, src, dstRowSize);
dst += dstRowSize;
src -= srcRowSize;
}
}
- (int)isCVTextureFlipped
{
return IsCVTextureFlipped(self->_cmVideoSampling.cvTextureCacheTexture);
}
#if !PLATFORM_VISIONOS
+ (BOOL)focusPointSupported:(AVCaptureDevice*)captureDevice withFocusMode:(AVCaptureFocusMode)focusMode
{
return captureDevice.focusPointOfInterestSupported && [captureDevice isFocusModeSupported: focusMode];
}
#endif
- (int)setFocusPointWithX:(float)x Y:(float)y
{
#if !PLATFORM_VISIONOS
if (x < 0 || x > 1 || y < 0 || y > 1)
{
_focusPoint = CGPointMake(0.5, 0.5); // default value for iOS
_focusMode = AVCaptureFocusModeContinuousAutoFocus;
}
else
{
_focusPoint = CGPointMake(x, 1.0 - y);
_focusMode = AVCaptureFocusModeAutoFocus;
}
#endif
return [self setFocusPoint];
}
- (int)setFocusPoint
{
#if !PLATFORM_VISIONOS
if (self.captureDevice != nil && [CameraCaptureController focusPointSupported: self.captureDevice withFocusMode: _focusMode])
{
if ([self.captureDevice lockForConfiguration: nil])
{
self.captureDevice.focusPointOfInterest = _focusPoint;
self.captureDevice.focusMode = _focusMode;
[self.captureDevice unlockForConfiguration];
return 1;
}
}
#endif
return 0;
}
+ (NSMutableArray<CameraCaptureController*>*)getActiveColorAndDepthCameraControllers
{
if (activeColorAndDepthCameraControllers == nil)
{
activeColorAndDepthCameraControllers = [[NSMutableArray alloc] init];
}
return activeColorAndDepthCameraControllers;
}
+ (void)addColorAndDepthCameraController:(CameraCaptureController*)controller
{
CameraCaptureController* prevController = [self findColorAndDepthCameraController: controller.captureDevice isDepth: controller->_isDepth];
if (prevController != nil)
[prevController pause];
CameraCaptureController* otherController = [self findColorAndDepthCameraController: controller.captureDevice isDepth: !controller->_isDepth];
if (otherController != nil)
{
[otherController.captureSession stopRunning];
[otherController clearColorAndDepthCameraCaptureSession];
}
[[self getActiveColorAndDepthCameraControllers] addObject: controller];
}
+ (void)removeColorAndDepthCameraController:(CameraCaptureController*)controller
{
[[self getActiveColorAndDepthCameraControllers] removeObject: controller];
CameraCaptureController* otherController = [self findColorAndDepthCameraController: controller.captureDevice isDepth: !controller->_isDepth];
if (otherController != nil)
{
[otherController initColorAndDepthCameraCaptureSession];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[otherController.captureSession startRunning];
});
}
}
+ (void)clearColorAndDepthCameraControllers
{
NSMutableArray<CameraCaptureController*>* activeColorAndDepthCameraControllers = [self getActiveColorAndDepthCameraControllers];
for (CameraCaptureController *controller in activeColorAndDepthCameraControllers)
{
if (controller.captureSession != nil)
{
[controller.captureSession stopRunning];
[controller clearColorAndDepthCameraCaptureSession];
}
}
[activeColorAndDepthCameraControllers removeAllObjects];
}
+ (CameraCaptureController*)findColorAndDepthCameraController:(AVCaptureDevice*)device isDepth:(bool)isDepth
{
for (CameraCaptureController *controller in [self getActiveColorAndDepthCameraControllers])
{
if (controller.captureDevice == device && controller->_isDepth == isDepth)
return controller;
}
return nil;
}
- (bool)initColorAndDepthCameraCapture:(AVCaptureDevice*)device preset:(NSString*)preset fps:(float)fps isDepth:(bool)isDepth
{
if (![self initCapture: device])
return false;
#if !PLATFORM_VISIONOS
self.captureDepthOutput = [[AVCaptureDepthDataOutput alloc] init];
if (self.captureDepthOutput == nil)
return false;
self.captureDepthOutput.filteringEnabled = YES; // getting filtered depth data to avoid invalid values
self.captureDepthOutput.alwaysDiscardsLateDepthData = YES;
#endif
self->_preset = preset;
[self initColorAndDepthCameraCaptureSession];
[self setCaptureFPS: fps];
#if !PLATFORM_VISIONOS
NSArray<AVCaptureOutput*> *outputs = [NSArray arrayWithObjects: self.captureOutput, self.captureDepthOutput, nil];
self.captureSynchronizer = [[AVCaptureDataOutputSynchronizer alloc] initWithDataOutputs: outputs];
// queue on main thread to simplify gles life
[self.captureSynchronizer setDelegate: self queue: dispatch_get_main_queue()];
#endif
_isDepth = isDepth;
return true;
}
- (void)initColorAndDepthCameraCaptureSession
{
self.captureSession = [[AVCaptureSession alloc] init];
#if !PLATFORM_VISIONOS
[self.captureSession setSessionPreset: self->_preset];
#endif
[self.captureSession addInput: self.captureInput];
[self.captureSession addOutput: self.captureOutput];
#if !PLATFORM_VISIONOS
[self.captureSession addOutput: self.captureDepthOutput];
#endif
}
- (void)clearColorAndDepthCameraCaptureSession
{
[self.captureSession removeInput: self.captureInput];
[self.captureSession removeOutput: self.captureOutput];
#if !PLATFORM_VISIONOS
[self.captureSession removeOutput: self.captureDepthOutput];
#endif
self.captureSession = nil;
}
#if !PLATFORM_VISIONOS
- (void)dataOutputSynchronizer:(AVCaptureDataOutputSynchronizer *)synchronizer didOutputSynchronizedDataCollection:(AVCaptureSynchronizedDataCollection *)synchronizedDataCollection
{
AVCaptureSynchronizedSampleBufferData *sampleData = (AVCaptureSynchronizedSampleBufferData*)[synchronizedDataCollection synchronizedDataForCaptureOutput: self.captureOutput];
if (CMSampleBufferGetImageBuffer(sampleData.sampleBuffer) != nil)
{
CameraCaptureController* colorController = !self->_isDepth ? self : [CameraCaptureController findColorAndDepthCameraController: self.captureDevice isDepth: false];
if (colorController != nil)
{
intptr_t tex = (intptr_t)CMVideoSampling_SampleBuffer(&colorController->_cmVideoSampling, sampleData.sampleBuffer, &(colorController->_width), &(colorController->_height));
UnityDidCaptureVideoFrame(tex, colorController->_userData);
}
}
AVCaptureSynchronizedDepthData *depthData = (AVCaptureSynchronizedDepthData*)[synchronizedDataCollection synchronizedDataForCaptureOutput: self.captureDepthOutput];
if (depthData.depthData.depthDataMap != nil)
{
CameraCaptureController* depthController = self->_isDepth ? self : [CameraCaptureController findColorAndDepthCameraController: self.captureDevice isDepth: true];
if (depthController != nil)
{
intptr_t tex = (intptr_t)CMVideoSampling_ImageBuffer(&depthController->_cmVideoSampling, [depthData.depthData depthDataByConvertingToDepthDataType: kCVPixelFormatType_DepthFloat16].depthDataMap, &(depthController->_width), &(depthController->_height));
UnityDidCaptureVideoFrame(tex, depthController->_userData);
}
}
}
#endif
- (void)start
{
#if !PLATFORM_VISIONOS
if (self.captureDepthOutput != nil)
{
[CameraCaptureController addColorAndDepthCameraController: self];
}
else
#endif
{
[CameraCaptureController clearColorAndDepthCameraControllers];
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
[self.captureSession startRunning];
});
}
- (void)pause
{
[self.captureSession stopRunning];
#if !PLATFORM_VISIONOS
if (self.captureDepthOutput != nil)
#endif
{
[CameraCaptureController removeColorAndDepthCameraController: self];
}
}
- (void)stop
{
[self.captureSession stopRunning];
[self.captureSession removeInput: self.captureInput];
[self.captureSession removeOutput: self.captureOutput];
self.captureInput = nil;
self.captureOutput = nil;
#if !PLATFORM_VISIONOS
if (self.captureDepthOutput != nil)
{
self.captureSynchronizer = nil;
[self.captureSession removeOutput: self.captureDepthOutput];
self.captureDepthOutput = nil;
[CameraCaptureController removeColorAndDepthCameraController: self];
}
#else
[CameraCaptureController removeColorAndDepthCameraController: self];
#endif
self.captureDevice = nil;
self.captureSession = nil;
if (self->_pixelBufferCopy != nullptr)
{
::free(self->_pixelBufferCopy);
self->_pixelBufferCopy = nullptr;
}
CMVideoSampling_Uninitialize(&self->_cmVideoSampling);
}
- (float)pickAvailableFrameRate:(float)fps
{
AVFrameRateRange* bestRange = nil;
float minDiff = INFINITY;
float epsilon = 0.1;
fps = fps > epsilon ? fps : 24;
for (AVFrameRateRange* rate in self.captureDevice.activeFormat.videoSupportedFrameRateRanges)
{
if (fps + epsilon > rate.minFrameRate && fps - epsilon < rate.maxFrameRate)
return fps;
else
{
float diff = ::fmin(::fabs(fps - rate.minFrameRate), ::fabs(fps - rate.maxFrameRate));
if (diff < minDiff)
{
minDiff = diff;
bestRange = rate;
}
}
}
return fps > bestRange.maxFrameRate ? bestRange.maxFrameRate : bestRange.minFrameRate;
}
@synthesize captureDevice = _captureDevice;
@synthesize captureSession = _captureSession;
@synthesize captureOutput = _captureOutput;
@synthesize captureInput = _captureInput;
#if !PLATFORM_VISIONOS
@synthesize captureDepthOutput = _captureDepthOutput;
@synthesize captureSynchronizer = _captureSynchronizer;
#endif
@end
#if !PLATFORM_VISIONOS
// Preset for getting depth data with max resolution available
static NSString* const depthCaptureSessionPreset = AVCaptureSessionPresetPhoto;
#endif
static NSMutableArray<CameraCaptureDevice*> *videoCaptureDevices = nil;
@implementation CameraCaptureDevice
{
@public AVCaptureDevice* _device;
@public int _frontFacing;
@public int _autoFocusPointSupported;
@public WebCamKind _kind;
@public NSMutableArray<NSValue*>* _resolutions;
NSMutableArray<NSString*>* _resPresets;
}
- (bool)isColorAndDepthCaptureDevice
{
#if !PLATFORM_VISIONOS
for (AVCaptureDeviceFormat *format in [self->_device formats])
{
if ([format supportedDepthDataFormats].count > 0)
return true;
}
#endif
return false;
}
- (WebCamKind)getKind
{
#if !PLATFORM_VISIONOS
AVCaptureDeviceType type = _device.deviceType;
if ([type isEqualToString: AVCaptureDeviceTypeBuiltInWideAngleCamera])
return kWebCamWideAngle;
if ([type isEqualToString: AVCaptureDeviceTypeBuiltInTelephotoCamera])
return kWebCamTelephoto;
if ([type isEqualToString: AVCaptureDeviceTypeBuiltInDualCamera] && [self isColorAndDepthCaptureDevice])
return kWebCamColorAndDepth;
if (@available(iOS 13, *))
{
if ([type isEqualToString: AVCaptureDeviceTypeBuiltInUltraWideCamera])
return kWebCamUltraWideAngle;
if ([type isEqualToString: AVCaptureDeviceTypeBuiltInDualWideCamera])
return kWebCamWideAngle;
if ([type isEqualToString: AVCaptureDeviceTypeBuiltInTripleCamera])
return kWebCamUltraWideAngle;
}
else
{
// Only works if device language is English; this was original impl, keeping to not regress
if ([self->_device.localizedName containsString: @"Ultra Wide"])
return kWebCamUltraWideAngle;
}
#if defined(__IPHONE_17_0) || defined(__TVOS_17_0)
if (@available(iOS 17.0, *))
{
if ([type isEqualToString: AVCaptureDeviceTypeContinuityCamera])
return kWebCamWideAngle;
}
#endif
#endif
#if PLATFORM_IOS
#ifdef __IPHONE_15_4
if (@available(iOS 15.4, *))
{
if ([type isEqualToString: AVCaptureDeviceTypeBuiltInLiDARDepthCamera])
return kWebCamColorAndDepth;
}
#endif
if ([type isEqualToString: AVCaptureDeviceTypeBuiltInTrueDepthCamera] && [self isColorAndDepthCaptureDevice])
return kWebCamColorAndDepth;
#endif
return kWebCamWideAngle;
}
- (void)fillCaptureDeviceResolutions
{
#if PLATFORM_VISIONOS
const int count = 0;
#else
static NSString* preset[] =
{
AVCaptureSessionPresetLow, // usually 192x144
AVCaptureSessionPreset352x288,
AVCaptureSessionPresetMedium, // usually 480x320
AVCaptureSessionPreset640x480,
AVCaptureSessionPreset1280x720,
AVCaptureSessionPreset1920x1080, // usually the same as AVCaptureSessionPresetHigh
AVCaptureSessionPreset3840x2160,
};
const int count = sizeof(preset) / sizeof(preset[0]);
#endif
self->_resolutions = [NSMutableArray arrayWithCapacity: count];
self->_resPresets = [NSMutableArray arrayWithCapacity: count];
#if PLATFORM_VISIONOS
AVCaptureInput* captureInput = [[AVCaptureDeviceInput alloc] initWithDevice: self->_device error: nil];
#else
AVCaptureInput* captureInput = [AVCaptureDeviceInput deviceInputWithDevice: self->_device error: nil];
#endif
//Don't attempt to setup an AVCaptureSession if the user has explicitly denied permission to use the camera.
if (captureInput != nil)
{
AVCaptureSession* captureSession = [[AVCaptureSession alloc] init];
if ([captureSession canAddInput: captureInput])
[captureSession addInput: captureInput];
#if !PLATFORM_VISIONOS
if (self->_kind == kWebCamColorAndDepth)
{
AVCaptureDepthDataOutput* captureDepthOutput = [[AVCaptureDepthDataOutput alloc] init];
if ([captureSession canSetSessionPreset: depthCaptureSessionPreset])
{
[captureSession setSessionPreset: AVCaptureSessionPresetPhoto];
[captureSession addOutput: captureDepthOutput];
CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(self->_device.activeDepthDataFormat.formatDescription); // for ColorAndDepth camera return depth buffer resolution
[self->_resolutions addObject: [NSValue valueWithCGSize: CGSizeMake(dim.width, dim.height)]];
[self->_resPresets addObject: AVCaptureSessionPresetPhoto];
}
}
else
{
for (int i = 0; i < count; ++i)
{
if ([captureSession canSetSessionPreset: preset[i]])
{
[captureSession setSessionPreset: preset[i]];
CMVideoDimensions dim = CMVideoFormatDescriptionGetDimensions(self->_device.activeFormat.formatDescription);
[self->_resolutions addObject: [NSValue valueWithCGSize: CGSizeMake(dim.width, dim.height)]];
[self->_resPresets addObject: preset[i]];
}
}
}
#endif
}
}
- (NSString*)pickPresetFromWidth:(int)w height:(int)h
{
#if !PLATFORM_VISIONOS
if (self->_kind == kWebCamColorAndDepth)
{
return depthCaptureSessionPreset;
}
#endif
int requestedWidth = w > 0 ? w : 640;
int requestedHeight = h > 0 ? h : 480;
if (requestedHeight > requestedWidth) // hardware camera frame is landscape oriented
std::swap(requestedWidth, requestedHeight);
NSInteger ret = -1;
double bestMatch = std::numeric_limits<double>::max();
for (NSInteger i = 0, n = [_resolutions count]; i < n; ++i)
{
double width = [self->_resolutions[i] CGSizeValue].width;
double height = [self->_resolutions[i] CGSizeValue].height;
double match = std::abs(std::log(requestedWidth / width)) + std::abs(std::log(requestedHeight / height));
if (match < bestMatch)
{
ret = i;
bestMatch = match;
}
}
#if PLATFORM_VISIONOS
return nil;
#else
NSAssert(ret != -1, @"Cannot pick capture preset");
return ret != -1 ? self->_resPresets[ret] : AVCaptureSessionPresetHigh;
#endif
}
- (CameraCaptureDevice*)initWithDevice:(AVCaptureDevice*)device
{
self->_device = device;
self->_frontFacing = device.position == AVCaptureDevicePositionFront ? 1 : 0;
#if PLATFORM_VISIONOS
self->_autoFocusPointSupported = 0;
#else
self->_autoFocusPointSupported = [CameraCaptureController focusPointSupported: device withFocusMode: AVCaptureFocusModeAutoFocus] ? 1 : 0;
#endif
self->_kind = [self getKind];
[self fillCaptureDeviceResolutions];
return self;
}
- (bool)initCaptureForController:(CameraCaptureController*)controller width:(int)w height:(int)h fps:(float)fps isDepth:(bool)isDepth
{
bool initResult = false;
NSString *preset = [self pickPresetFromWidth: w height: h];
if ([self isColorAndDepthCaptureDevice])
{
initResult = [controller initColorAndDepthCameraCapture: self->_device preset: preset fps: fps isDepth: isDepth];
}
else
{
assert(!isDepth);
initResult = [controller initCapture: self->_device preset: preset fps: fps];
}
return initResult;
}
+ (bool)initialized
{
return videoCaptureDevices != nil;
}
+ (void)createCameraCaptureDevicesArray
{
videoCaptureDevices = [NSMutableArray arrayWithCapacity: 2];
}
+ (void)addCameraCaptureDevice:(AVCaptureDevice*)device
{
[videoCaptureDevices addObject: [[CameraCaptureDevice alloc] initWithDevice: device]];
}
@end
extern "C" void UnityEnumVideoCaptureDevices(void* udata, void(*callback)(void* udata, const char* name, int frontFacing, int autoFocusPointSupported, int kind, const int* resolutions, int resCount))
{
if (![CameraCaptureDevice initialized])
{
[CameraCaptureDevice createCameraCaptureDevicesArray];
#if PLATFORM_VISIONOS
AVCaptureDevice* systemPreferredCamera = [AVCaptureDevice systemPreferredCamera];
if (systemPreferredCamera != nil)
[CameraCaptureDevice addCameraCaptureDevice: systemPreferredCamera];
#else
NSMutableArray<AVCaptureDeviceType>* captureDevices = [NSMutableArray arrayWithObjects: AVCaptureDeviceTypeBuiltInWideAngleCamera, AVCaptureDeviceTypeBuiltInTelephotoCamera, nil];
[captureDevices addObject: AVCaptureDeviceTypeBuiltInDualCamera];
[captureDevices addObject: AVCaptureDeviceTypeBuiltInTrueDepthCamera];
if (UnityiOS130orNewer())
{
[captureDevices addObject: AVCaptureDeviceTypeBuiltInUltraWideCamera];
[captureDevices addObject: AVCaptureDeviceTypeBuiltInDualWideCamera];
[captureDevices addObject: AVCaptureDeviceTypeBuiltInTripleCamera];
}
AVCaptureDeviceDiscoverySession *captureDeviceDiscoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes: captureDevices mediaType: AVMediaTypeVideo position: AVCaptureDevicePositionUnspecified];
for (AVCaptureDevice* device in [captureDeviceDiscoverySession devices])
{
[CameraCaptureDevice addCameraCaptureDevice: device];
}
#endif
}
// we should not provide camera devices information while access has not been granted
// but we need to try to enumerate camera devices anyway to trigger permission request dialog
if ([AVCaptureDevice authorizationStatusForMediaType: AVMediaTypeVideo] != AVAuthorizationStatusAuthorized)
return;
for (CameraCaptureDevice *cameraCaptureDevice in videoCaptureDevices)
{
int resCount = (int)[cameraCaptureDevice->_resolutions count];
int *resolutions = new int[resCount * 2];
for (int i = 0; i < resCount; ++i)
{
resolutions[i * 2] = (int)[cameraCaptureDevice->_resolutions[i] CGSizeValue].width;
resolutions[i * 2 + 1] = (int)[cameraCaptureDevice->_resolutions[i] CGSizeValue].height;
}
NSString* localizedName = cameraCaptureDevice->_device.localizedName;
const char* deviceName = localizedName != nil ? localizedName.UTF8String : "";
callback(udata, deviceName, cameraCaptureDevice->_frontFacing, cameraCaptureDevice->_autoFocusPointSupported, cameraCaptureDevice->_kind, resolutions, resCount);
delete[] resolutions;
}
}
extern "C" void* UnityInitCameraCapture(int deviceIndex, int w, int h, int fps, int isDepth, void* udata)
{
if (videoCaptureDevices != nil && deviceIndex < videoCaptureDevices.count)
{
CameraCaptureController* controller = [CameraCaptureController alloc];
bool initResult = [videoCaptureDevices[deviceIndex] initCaptureForController: controller width: w height: h fps: (float)fps isDepth: (isDepth != 0)];
if (initResult)
{
controller->_userData = udata;
return (__bridge_retained void*)controller;
}
controller = nil;
}
return 0;
}
extern "C" void UnityStartCameraCapture(void* capture)
{
[(__bridge CameraCaptureController*)capture start];
}
extern "C" void UnityPauseCameraCapture(void* capture)
{
[(__bridge CameraCaptureController*)capture pause];
}
extern "C" void UnityStopCameraCapture(void* capture)
{
CameraCaptureController* controller = (__bridge_transfer CameraCaptureController*)capture;
[controller stop];
controller = nil;
}
extern "C" void UnityCameraCaptureExtents(void* capture, int* w, int* h)
{
CameraCaptureController* controller = (__bridge CameraCaptureController*)capture;
if (controller == nil)
return;
*w = (int)controller->_width;
*h = (int)controller->_height;
}
extern "C" void UnityCameraCaptureReadToMemory(void* capture, void* dst_, int w, int h)
{
CameraCaptureController* controller = (__bridge CameraCaptureController*)capture;
if (controller == nil)
return;
assert(w == controller->_width && h == controller->_height);
[controller capturePixelBufferToMemBuffer: (uint8_t*)dst_];
}
extern "C" int UnityCameraCaptureVideoRotationDeg(void* capture)
{
CameraCaptureController* controller = (__bridge CameraCaptureController*)capture;
if (controller == nil)
return 0;
// all cams are landscape.
switch (UnityCurrentOrientation())
{
case portrait: return 90;
case portraitUpsideDown: return 270;
case landscapeLeft: return controller.captureDevice.position == AVCaptureDevicePositionFront ? 180 : 0;
case landscapeRight: return controller.captureDevice.position == AVCaptureDevicePositionFront ? 0 : 180;
default: assert(false && "bad orientation returned from UnityCurrentOrientation()"); break;
}
return 0;
}
extern "C" int UnityCameraCaptureVerticallyMirrored(void* capture)
{
CameraCaptureController* controller = (__bridge CameraCaptureController*)capture;
if (controller == nil)
return 0;
return [controller isCVTextureFlipped];
}
extern "C" int UnityCameraCaptureSetAutoFocusPoint(void* capture, float x, float y)
{
CameraCaptureController* controller = (__bridge CameraCaptureController*)capture;
if (controller == nil)
return 0;
return [controller setFocusPointWithX: x Y: y];
}
#else
// Stubs for when UNITY_USES_WEBCAM is not defined
extern "C" void UnityEnumVideoCaptureDevices(void* udata, void(*callback)(void* udata, const char* name, int frontFacing, int autoFocusPointSupported, int kind, const int* resolutions, int resCount))
{
}
extern "C" void* UnityInitCameraCapture(int deviceIndex, int w, int h, int fps, int isDepth, void* udata)
{
return 0;
}
extern "C" void UnityStartCameraCapture(void* capture)
{
}
extern "C" void UnityPauseCameraCapture(void* capture)
{
}
extern "C" void UnityStopCameraCapture(void* capture)
{
}
extern "C" void UnityCameraCaptureExtents(void* capture, int* w, int* h)
{
}
extern "C" void UnityCameraCaptureReadToMemory(void* capture, void* dst_, int w, int h)
{
}
extern "C" int UnityCameraCaptureVideoRotationDeg(void* capture)
{
return 0;
}
extern "C" int UnityCameraCaptureVerticallyMirrored(void* capture)
{
return 0;
}
extern "C" int UnityCameraCaptureSetAutoFocusPoint(void* capture, float x, float y)
{
return 0;
}
#endif

View File

@ -0,0 +1,616 @@
#include <sys/types.h>
#include <sys/sysctl.h>
#include "UnityAppController.h"
#include "UnityView.h"
#include "DisplayManager.h"
// ad/vendor ids
#if UNITY_USES_IAD
#include <AdSupport/ASIdentifierManager.h>
#include <AppTrackingTransparency/ATTrackingManager.h>
static id QueryASIdentifierManager()
{
static bool _queryAttempted = false;
static id _manager = nil;
if (_queryAttempted)
return _manager;
_queryAttempted = true;
NSBundle* bundle = [NSBundle bundleWithPath: @"/System/Library/Frameworks/AdSupport.framework"];
if (bundle)
{
[bundle load];
_manager = [NSClassFromString(@"ASIdentifierManager") performSelector: @selector(sharedManager)];
return _manager;
}
return nil;
}
API_AVAILABLE(ios(14))
static bool QueryAttTrackingAuthorization()
{
static bool _status = false;
// if authorization is revoked, app is restarted, so we can cache
if (!_status)
{
static Class _ATTrackingManager = nil;
static bool _classLoadAttempted = false;
if (!_classLoadAttempted)
{
_classLoadAttempted = true;
NSBundle* bundle = [NSBundle bundleWithPath: @"/System/Library/Frameworks/AppTrackingTransparency.framework"];
if (bundle)
{
[bundle load];
_ATTrackingManager = NSClassFromString(@"ATTrackingManager");
}
}
if (_ATTrackingManager)
{
id status = [_ATTrackingManager valueForKey: @"trackingAuthorizationStatus"];
if (status && [status isKindOfClass: NSNumber.class])
{
NSNumber* tackingStatus = status;
_status = ATTrackingManagerAuthorizationStatusAuthorized == tackingStatus.unsignedIntValue;
}
}
}
return _status;
}
#endif
extern "C" const char* UnityAdIdentifier()
{
static const char* _ADID = NULL;
#if UNITY_USES_IAD
static const NSString* _ADIDNSString = nil;
// ad id can be reset during app lifetime
id manager = QueryASIdentifierManager();
if (manager)
{
NSString* adid = [[manager performSelector: @selector(advertisingIdentifier)] UUIDString];
// Do stuff to avoid UTF8String leaks. We still leak if ADID changes, but that shouldn't happen too often.
if (![_ADIDNSString isEqualToString: adid])
{
_ADIDNSString = adid;
free((void*)_ADID);
_ADID = AllocCString(adid);
}
}
#endif
return _ADID;
}
extern "C" int UnityGetLowPowerModeEnabled()
{
return [[NSProcessInfo processInfo] isLowPowerModeEnabled] ? 1 : 0;
}
extern "C" int UnityGetWantsSoftwareDimming()
{
#if !PLATFORM_TVOS && !PLATFORM_VISIONOS
UIScreen* mainScreen = [UIScreen mainScreen];
return mainScreen.wantsSoftwareDimming ? 1 : 0;
#else
return 0;
#endif
}
extern "C" void UnitySetWantsSoftwareDimming(int enabled)
{
#if !PLATFORM_TVOS && !PLATFORM_VISIONOS
UIScreen* mainScreen = [UIScreen mainScreen];
mainScreen.wantsSoftwareDimming = enabled;
#endif
}
extern "C" int UnityGetIosAppOnMac()
{
if (@available(iOS 14, tvOS 14, *))
return [[NSProcessInfo processInfo] isiOSAppOnMac] ? 1 : 0;
return 0;
}
extern "C" int UnityAdTrackingEnabled()
{
bool _AdTrackingEnabled = false;
#if UNITY_USES_IAD
if (@available(iOS 14.0, tvOS 14.0, *))
{
_AdTrackingEnabled = QueryAttTrackingAuthorization();
}
else
{
// ad tracking can be changed during app lifetime
id manager = QueryASIdentifierManager();
if (manager)
_AdTrackingEnabled = [manager performSelector: @selector(isAdvertisingTrackingEnabled)];
}
#endif
return _AdTrackingEnabled ? 1 : 0;
}
extern "C" const char* UnityVendorIdentifier()
{
static const char* _VendorID = NULL;
if (_VendorID == NULL)
_VendorID = AllocCString([[UIDevice currentDevice].identifierForVendor UUIDString]);
return _VendorID;
}
// UIDevice properties
#define QUERY_UIDEVICE_PROPERTY(FUNC, PROP) \
extern "C" const char* FUNC() \
{ \
static const char* value = NULL; \
if (value == NULL && [UIDevice instancesRespondToSelector:@selector(PROP)]) \
value = AllocCString([UIDevice currentDevice].PROP); \
return value; \
}
QUERY_UIDEVICE_PROPERTY(UnityDeviceName, name)
QUERY_UIDEVICE_PROPERTY(UnitySystemName, systemName)
QUERY_UIDEVICE_PROPERTY(UnitySystemVersion, systemVersion)
#undef QUERY_UIDEVICE_PROPERTY
// hw info
extern "C" const char* UnityDeviceModel()
{
static const char* _DeviceModel = NULL;
if (_DeviceModel == NULL)
{
size_t size;
::sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char* model = (char*)::malloc(size + 1);
::sysctlbyname("hw.machine", model, &size, NULL, 0);
model[size] = 0;
#if TARGET_OS_SIMULATOR
if (!strncmp(model, "arm64", 5) || !strncmp(model, "x86_64", 6))
{
NSString* simModel = [[NSProcessInfo processInfo] environment][@"SIMULATOR_MODEL_IDENTIFIER"];
if ([simModel length] > 0)
{
_DeviceModel = AllocCString(simModel);
::free(model);
return _DeviceModel;
}
}
#endif
_DeviceModel = AllocCString([NSString stringWithUTF8String: model]);
::free(model);
}
return _DeviceModel;
}
extern "C" int UnityDeviceCPUCount()
{
static int _DeviceCPUCount = -1;
if (_DeviceCPUCount <= 0)
{
// maybe would be better to use HW_AVAILCPU
int ctlName[] = {CTL_HW, HW_NCPU};
size_t dataLen = sizeof(_DeviceCPUCount);
::sysctl(ctlName, 2, &_DeviceCPUCount, &dataLen, NULL, 0);
}
return _DeviceCPUCount;
}
extern "C" int UnityGetPhysicalMemory()
{
return (int)(NSProcessInfo.processInfo.physicalMemory / (1024ULL * 1024ULL));
}
// misc
extern "C" const char* UnitySystemLanguage()
{
static const char* _SystemLanguage = NULL;
if (_SystemLanguage == NULL)
{
NSArray* lang = [NSLocale preferredLanguages];
if (lang.count > 0)
_SystemLanguage = AllocCString(lang[0]);
}
return _SystemLanguage;
}
enum DeviceType : uint8_t
{
deviceTypeUnknown = 0,
iPhone = 1,
iPad = 2,
iPod = 3,
AppleTV = 4
};
struct DeviceTableEntry
{
DeviceType deviceType;
uint8_t majorGen;
uint8_t minorGenMin;
uint8_t minorGenMax;
DeviceGeneration device;
};
DeviceTableEntry DeviceTable[] =
{
{ iPhone, 2, 1, 1, deviceiPhone3GS },
{ iPhone, 3, 1, 3, deviceiPhone4 },
{ iPhone, 4, 1, 1, deviceiPhone4S },
{ iPhone, 5, 3, 4, deviceiPhone5C },
{ iPhone, 5, 1, 2, deviceiPhone5 },
{ iPhone, 6, 1, 2, deviceiPhone5S },
{ iPhone, 7, 2, 2, deviceiPhone6 },
{ iPhone, 7, 1, 1, deviceiPhone6Plus },
{ iPhone, 8, 1, 1, deviceiPhone6S },
{ iPhone, 8, 2, 2, deviceiPhone6SPlus },
{ iPhone, 8, 4, 4, deviceiPhoneSE1Gen },
{ iPhone, 9, 1, 1, deviceiPhone7 },
{ iPhone, 9, 3, 3, deviceiPhone7 },
{ iPhone, 9, 2, 2, deviceiPhone7Plus },
{ iPhone, 9, 4, 4, deviceiPhone7Plus },
{ iPhone, 10, 1, 1, deviceiPhone8 },
{ iPhone, 10, 4, 4, deviceiPhone8 },
{ iPhone, 10, 2, 2, deviceiPhone8Plus },
{ iPhone, 10, 5, 5, deviceiPhone8Plus },
{ iPhone, 10, 3, 3, deviceiPhoneX },
{ iPhone, 10, 6, 6, deviceiPhoneX },
{ iPhone, 11, 8, 8, deviceiPhoneXR },
{ iPhone, 11, 2, 2, deviceiPhoneXS },
{ iPhone, 11, 4, 4, deviceiPhoneXSMax },
{ iPhone, 11, 6, 6, deviceiPhoneXSMax },
{ iPhone, 12, 1, 1, deviceiPhone11 },
{ iPhone, 12, 3, 3, deviceiPhone11Pro },
{ iPhone, 12, 5, 5, deviceiPhone11ProMax },
{ iPhone, 12, 8, 8, deviceiPhoneSE2Gen },
{ iPhone, 13, 1, 1, deviceiPhone12Mini },
{ iPhone, 13, 2, 2, deviceiPhone12 },
{ iPhone, 13, 3, 3, deviceiPhone12Pro },
{ iPhone, 13, 4, 4, deviceiPhone12ProMax },
{ iPhone, 14, 4, 4, deviceiPhone13Mini },
{ iPhone, 14, 5, 5, deviceiPhone13 },
{ iPhone, 14, 2, 2, deviceiPhone13Pro },
{ iPhone, 14, 3, 3, deviceiPhone13ProMax },
{ iPhone, 14, 6, 6, deviceiPhoneSE3Gen },
{ iPhone, 14, 7, 7, deviceiPhone14 },
{ iPhone, 14, 8, 8, deviceiPhone14Plus },
{ iPhone, 15, 2, 2, deviceiPhone14Pro },
{ iPhone, 15, 3, 3, deviceiPhone14ProMax },
{ iPhone, 15, 4, 4, deviceiPhone15 },
{ iPhone, 15, 5, 5, deviceiPhone15Plus },
{ iPhone, 16, 1, 1, deviceiPhone15Pro },
{ iPhone, 16, 2, 2, deviceiPhone15ProMax },
{ iPhone, 17, 3, 3, deviceiPhone16 },
{ iPhone, 17, 5, 5, deviceiPhone16e },
{ iPhone, 17, 4, 4, deviceiPhone16Plus },
{ iPhone, 17, 1, 1, deviceiPhone16Pro },
{ iPhone, 17, 2, 2, deviceiPhone16ProMax },
{ iPod, 4, 1, 1, deviceiPodTouch4Gen },
{ iPod, 5, 1, 1, deviceiPodTouch5Gen },
{ iPod, 7, 1, 1, deviceiPodTouch6Gen },
{ iPod, 9, 1, 1, deviceiPodTouch7Gen },
{ iPad, 2, 5, 7, deviceiPadMini1Gen },
{ iPad, 4, 4, 6, deviceiPadMini2Gen },
{ iPad, 4, 7, 9, deviceiPadMini3Gen },
{ iPad, 5, 1, 2, deviceiPadMini4Gen },
{ iPad, 11, 1, 2, deviceiPadMini5Gen },
{ iPad, 14, 1, 2, deviceiPadMini6Gen },
{ iPad, 2, 1, 4, deviceiPad2Gen },
{ iPad, 3, 1, 3, deviceiPad3Gen },
{ iPad, 3, 4, 6, deviceiPad4Gen },
{ iPad, 6, 11, 12, deviceiPad5Gen },
{ iPad, 7, 5, 6, deviceiPad6Gen },
{ iPad, 7, 11, 12, deviceiPad7Gen },
{ iPad, 12, 1, 2, deviceiPad9Gen },
{ iPad, 4, 1, 3, deviceiPadAir1 },
{ iPad, 5, 3, 4, deviceiPadAir2 },
{ iPad, 11, 3, 4, deviceiPadAir3Gen },
{ iPad, 6, 7, 8, deviceiPadPro1Gen },
{ iPad, 7, 1, 2, deviceiPadPro2Gen },
{ iPad, 6, 3, 4, deviceiPadPro10Inch1Gen },
{ iPad, 7, 3, 4, deviceiPadPro10Inch2Gen },
{ iPad, 8, 1, 4, deviceiPadPro11Inch },
{ iPad, 8, 9, 10, deviceiPadPro11Inch2Gen },
{ iPad, 13, 6, 7, deviceiPadPro11Inch3Gen },
{ iPad, 8, 5, 8, deviceiPadPro3Gen },
{ iPad, 8, 11, 12, deviceiPadPro4Gen },
{ iPad, 13, 10, 11, deviceiPadPro5Gen },
{ iPad, 11, 6, 7, deviceiPad8Gen },
{ iPad, 13, 1, 2, deviceiPadAir4Gen },
{ iPad, 13, 16, 17, deviceiPadAir5Gen },
{ iPad, 14, 5, 6, deviceiPadPro6Gen },
{ iPad, 14, 3, 4, deviceiPadPro11Inch4Gen },
{ iPad, 13, 18, 19, deviceiPad10Gen },
{ AppleTV, 5, 3, 3, deviceAppleTVHD },
{ AppleTV, 6, 2, 2, deviceAppleTV4K },
{ AppleTV, 11, 1, 1, deviceAppleTV4K2Gen },
{ AppleTV, 14, 1, 1, deviceAppleTV4K3Gen },
};
extern "C" int ParseDeviceGeneration(const char* model)
{
DeviceType deviceType = deviceTypeUnknown;
if (!strncmp(model, "iPhone", 6))
{
deviceType = iPhone;
model += 6;
}
else if (!strncmp(model, "iPad", 4))
{
deviceType = iPad;
model += 4;
}
else if (!strncmp(model, "iPod", 4))
{
deviceType = iPod;
model += 4;
}
else if (!strncmp(model, "AppleTV", 7))
{
deviceType = AppleTV;
model += 7;
}
char* endPtr;
int majorGen = (int)strtol(model, &endPtr, 10);
int minorGen = (int)strtol(endPtr + 1, &endPtr, 10);
if (strlen(endPtr) == 0)
{
for (int i = 0; i < sizeof(DeviceTable) / sizeof(DeviceTable[0]); ++i)
{
if (deviceType != DeviceTable[i].deviceType)
continue;
if (majorGen != DeviceTable[i].majorGen)
continue;
if (minorGen < DeviceTable[i].minorGenMin || minorGen > DeviceTable[i].minorGenMax)
continue;
return DeviceTable[i].device;
}
}
if (deviceType == iPhone)
return deviceiPhoneUnknown;
else if (deviceType == iPad)
return deviceiPadUnknown;
else if (deviceType == iPod)
return deviceiPodTouchUnknown;
return deviceUnknown;
}
extern "C" int UnityDeviceGeneration()
{
static int _DeviceGeneration = deviceUnknown;
if (_DeviceGeneration == deviceUnknown)
{
const char* model = UnityDeviceModel();
_DeviceGeneration = ParseDeviceGeneration(model);
}
return _DeviceGeneration;
}
// Currently a manual process to add devices that have a cutout (notch). If you add one here you need to also update UnityView GetCutoutToScreenRatio()
extern "C" int UnityDeviceHasCutout()
{
switch (UnityDeviceGeneration())
{
case deviceiPhoneX: case deviceiPhoneXS: case deviceiPhoneXSMax: case deviceiPhoneXR:
case deviceiPhone11: case deviceiPhone11Pro: case deviceiPhone11ProMax:
case deviceiPhone12: case deviceiPhone12Mini: case deviceiPhone12Pro: case deviceiPhone12ProMax:
case deviceiPhone13: case deviceiPhone13Mini: case deviceiPhone13Pro: case deviceiPhone13ProMax:
case deviceiPhone14: case deviceiPhone14Plus: case deviceiPhone14Pro: case deviceiPhone14ProMax:
case deviceiPhone15: case deviceiPhone15Plus: case deviceiPhone15Pro: case deviceiPhone15ProMax:
case deviceiPhone16: case deviceiPhone16Plus: case deviceiPhone16Pro: case deviceiPhone16ProMax: case deviceiPhone16e:
return 1;
default:
return 0;
}
}
// Devices with a cutout do not support Portrait UpsideDown orientation.
extern "C" int UnityDeviceSupportsUpsideDown()
{
return UnityDeviceHasCutout() ? 0 : 1;
}
extern "C" int UnityDeviceSupportedOrientations()
{
int orientations = (1 << portrait) | (1 << landscapeLeft) | (1 << landscapeRight);
if (UnityDeviceSupportsUpsideDown())
orientations |= (1 << portraitUpsideDown);
return orientations;
}
extern "C" int UnityDeviceIsForceTouchSupported()
{
return UnityGetUnityView().traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable;
}
extern "C" int UnityDeviceIsStylusTouchSupported()
{
const int deviceGen = UnityDeviceGeneration();
return (deviceGen == deviceiPadPro1Gen ||
deviceGen == deviceiPadPro10Inch1Gen ||
deviceGen == deviceiPadPro2Gen ||
deviceGen == deviceiPadPro10Inch2Gen ||
deviceGen == deviceiPadPro11Inch ||
deviceGen == deviceiPadPro3Gen ||
deviceGen == deviceiPad6Gen) ? 1 : 0;
}
extern "C" int UnityDeviceCanShowWideColor()
{
return UnityGetUnityView().traitCollection.displayGamut == UIDisplayGamutP3;
}
extern "C" float UnityDeviceDPI()
{
static float _DeviceDPI = -1.0f;
if (_DeviceDPI < 0.0f)
{
switch (UnityDeviceGeneration())
{
// iPhone
case deviceiPhone3GS:
_DeviceDPI = 163.0f; break;
case deviceiPhone4:
case deviceiPhone4S:
case deviceiPhone5:
case deviceiPhone5C:
case deviceiPhone5S:
case deviceiPhone6:
case deviceiPhone6S:
case deviceiPhoneSE1Gen:
case deviceiPhone7:
case deviceiPhone8:
case deviceiPhoneXR:
case deviceiPhone11:
case deviceiPhoneSE2Gen:
case deviceiPhoneSE3Gen:
_DeviceDPI = 326.0f; break;
case deviceiPhone6Plus:
case deviceiPhone6SPlus:
case deviceiPhone7Plus:
case deviceiPhone8Plus:
_DeviceDPI = 401.0f; break;
case deviceiPhoneX:
case deviceiPhoneXS:
case deviceiPhoneXSMax:
case deviceiPhone11Pro:
case deviceiPhone11ProMax:
case deviceiPhone12ProMax:
case deviceiPhone13ProMax:
case deviceiPhone14Plus:
_DeviceDPI = 458.0f; break;
case deviceiPhone12:
case deviceiPhone12Pro:
case deviceiPhone13:
case deviceiPhone13Pro:
case deviceiPhone14:
case deviceiPhone14Pro:
case deviceiPhone14ProMax:
case deviceiPhone15:
case deviceiPhone15Plus:
case deviceiPhone15Pro:
case deviceiPhone15ProMax:
case deviceiPhone16:
case deviceiPhone16e:
case deviceiPhone16Plus:
case deviceiPhone16Pro:
case deviceiPhone16ProMax:
_DeviceDPI = 460.0f; break;
case deviceiPhone12Mini:
case deviceiPhone13Mini:
_DeviceDPI = 476.0f; break;
// iPad
case deviceiPad2Gen:
_DeviceDPI = 132.0f; break;
case deviceiPad3Gen:
case deviceiPad4Gen: // iPad retina
case deviceiPadAir1:
case deviceiPadAir2:
case deviceiPadAir3Gen:
case deviceiPadPro1Gen:
case deviceiPadPro10Inch1Gen:
case deviceiPadPro2Gen:
case deviceiPadPro10Inch2Gen:
case deviceiPad5Gen:
case deviceiPad6Gen:
case deviceiPadPro11Inch:
case deviceiPadPro3Gen:
case deviceiPadPro11Inch2Gen:
case deviceiPadPro11Inch3Gen:
case deviceiPadPro4Gen:
case deviceiPadPro5Gen:
case deviceiPad8Gen:
case deviceiPadAir4Gen:
case deviceiPad9Gen:
case deviceiPadAir5Gen:
_DeviceDPI = 264.0f; break;
case deviceiPad7Gen:
_DeviceDPI = 326.0f; break;
// iPad mini
case deviceiPadMini1Gen:
_DeviceDPI = 163.0f; break;
case deviceiPadMini2Gen:
case deviceiPadMini3Gen:
case deviceiPadMini4Gen:
case deviceiPadMini5Gen:
case deviceiPadMini6Gen:
_DeviceDPI = 326.0f; break;
// iPod
case deviceiPodTouch4Gen:
case deviceiPodTouch5Gen:
case deviceiPodTouch6Gen:
case deviceiPodTouch7Gen:
_DeviceDPI = 326.0f; break;
// unknown (new) devices
case deviceiPhoneUnknown:
_DeviceDPI = 326.0f; break;
case deviceiPadUnknown:
case deviceiPadPro6Gen:
case deviceiPadPro11Inch4Gen:
case deviceiPad10Gen:
_DeviceDPI = 264.0f; break;
case deviceiPodTouchUnknown:
_DeviceDPI = 326.0f; break;
}
// If we didn't find DPI, set it to "unknown" value.
if (_DeviceDPI < 0.0f)
_DeviceDPI = 0.0f;
}
return _DeviceDPI;
}
// device id with fallback for pre-ios7
extern "C" const char* UnityDeviceUniqueIdentifier()
{
static const char* _DeviceID = NULL;
if (_DeviceID == NULL)
_DeviceID = UnityVendorIdentifier();
return _DeviceID;
}

View File

@ -0,0 +1,71 @@
#pragma once
#include "UnityRendering.h"
#include <UIKit/UIKit.h>
@class UnityView;
@interface DisplayConnection : NSObject
#if !PLATFORM_VISIONOS
- (id)init:(UIScreen*)targetScreen;
#else
- (id)init;
#endif
- (void)dealloc;
- (void)createView:(BOOL)useForRendering showRightAway:(BOOL)showRightAway;
- (void)createView:(BOOL)useForRendering;
- (void)createWithWindow:(UIWindow*)window andView:(UIView*)view;
- (UnityDisplaySurfaceBase*)initRendering;
- (void)recreateSurface:(RenderingSurfaceParams)params;
- (void)destroySurface;
- (void)shouldShowWindow:(BOOL)show;
- (void)requestRenderingResolution:(CGSize)res;
- (void)present;
#if !PLATFORM_VISIONOS
@property (readonly, copy, nonatomic) UIScreen* screen;
#endif
@property (readonly, copy, nonatomic) UIWindow* window;
@property (readonly, copy, nonatomic) UIView* view;
@property (readonly, nonatomic) CGSize screenSize;
@property (readonly, nonatomic) UnityDisplaySurfaceBase* surface;
@end
@interface DisplayManager : NSObject
#if !PLATFORM_VISIONOS
- (id)objectForKeyedSubscript:(id)key;
- (BOOL)displayAvailable:(UIScreen*)targetScreen;
- (void)updateDisplayListCacheInUnity;
- (void)enumerateDisplaysWithBlock:(void (^)(DisplayConnection* conn))block;
- (void)enumerateNonMainDisplaysWithBlock:(void (^)(DisplayConnection* conn))block;
#endif
- (void)startFrameRendering;
- (void)present;
- (void)endFrameRendering;
+ (void)Initialize;
+ (DisplayManager*)Instance;
+ (void)Destroy;
@property (readonly, nonatomic) DisplayConnection* mainDisplay;
@property (readonly, nonatomic) NSUInteger displayCount;
@end
inline DisplayConnection* GetMainDisplay()
{
return [DisplayManager Instance].mainDisplay;
}
inline UnityDisplaySurfaceBase* GetMainDisplaySurface()
{
return GetMainDisplay().surface;
}

View File

@ -0,0 +1,806 @@
#include "DisplayManager.h"
#include "UI/UnityView.h"
#include "UnityAppController.h"
#include "UI/UnityAppController+ViewHandling.h"
#import <QuartzCore/QuartzCore.h>
#import <CoreGraphics/CoreGraphics.h>
#include "UnityMetalSupport.h"
static DisplayManager* _DisplayManager = nil;
@interface DisplayConnection ()
@property (readonly, nonatomic) UnityDisplaySurfaceMTL* surfaceMTL;
@end
@implementation DisplayConnection
{
BOOL _needRecreateSurface;
CGSize _requestedRenderingSize;
#if !PLATFORM_VISIONOS
UIScreen* _screen;
#endif
UIWindow* _window;
UIView* _view;
CGSize _screenSize;
UnityDisplaySurfaceBase* _surface;
}
#if !PLATFORM_VISIONOS
@synthesize screen = _screen;
#endif
@synthesize window = _window;
@synthesize view = _view;
@synthesize screenSize = _screenSize;
@synthesize surface = _surface;
@synthesize surfaceMTL;
- (UnityDisplaySurfaceMTL*)surfaceMTL
{
assert(_surface->api == apiMetal);
return (UnityDisplaySurfaceMTL*)_surface;
}
#if !PLATFORM_VISIONOS
- (id)init:(UIScreen*)targetScreen
{
if ((self = [super init]))
{
self->_screen = targetScreen;
#if !PLATFORM_TVOS
targetScreen.currentMode = targetScreen.preferredMode;
#endif
// UIScreenOverscanCompensationNone == UIScreenOverscanCompensationInsetApplicationFrame so it will work with pre-ios9 just fine
targetScreen.overscanCompensation = UIScreenOverscanCompensationNone;
self->_screenSize = targetScreen.currentMode.size;
self->_needRecreateSurface = NO;
self->_requestedRenderingSize = CGSizeMake(-1, -1);
}
return self;
}
#else
- (id)init
{
if ((self = [super init]))
{
self->_screenSize = CGSizeMake(1920, 1080);
self->_needRecreateSurface = NO;
self->_requestedRenderingSize = CGSizeMake(-1, -1);
}
return self;
}
#endif
- (void)createWithWindow:(UIWindow*)window andView:(UIView*)view
{
_window = window;
_view = view;
CGSize layerSize = _view.layer.bounds.size;
_screenSize = CGSizeMake(roundf(layerSize.width) * _view.contentScaleFactor, roundf(layerSize.height) * _view.contentScaleFactor);
}
- (void)createView:(BOOL)useForRendering
{
[self createView: useForRendering showRightAway: YES];
}
- (void)createView:(BOOL)useForRendering showRightAway:(BOOL)showRightAway;
{
#if !PLATFORM_VISIONOS
NSAssert(_screen != [UIScreen mainScreen], @"DisplayConnection for mainScreen should be created with createWithWindow:andView:");
#endif
if (_view == nil)
{
#if !PLATFORM_VISIONOS
UIWindow* window = [[UIWindow alloc] initWithFrame: _screen.bounds];
window.screen = _screen;
UIView* view = [(useForRendering ? [UnityRenderingView alloc] : [UIView alloc]) initWithFrame: _screen.bounds];
view.contentScaleFactor = UnityScreenScaleFactor(_screen);
#else
UIWindow* window = [[UIWindow alloc] init];
UIView* view = [(useForRendering ? [UnityRenderingView alloc] : [UIView alloc]) init];
#endif
[self createWithWindow: window andView: view];
if (showRightAway)
{
[window addSubview: view];
window.hidden = NO;
}
}
}
- (void)shouldShowWindow:(BOOL)show
{
_window.hidden = show ? NO : YES;
#if !PLATFORM_VISIONOS
_window.screen = show ? _screen : nil;
#endif
}
- (UnityDisplaySurfaceBase*)initRendering
{
if (_surface)
return _surface;
UnityDisplaySurfaceBase* ret = NULL;
const int api = UnitySelectedRenderingAPI();
if (api == apiMetal)
{
UnityDisplaySurfaceMTL* surf = new UnityDisplaySurfaceMTL();
surf->layer = (CAMetalLayer*)_view.layer;
surf->device = UnityGetMetalDevice();
surf->commandQueue = [surf->device newCommandQueueWithMaxCommandBufferCount: UnityCommandQueueMaxCommandBufferCountMTL()];
ret = surf;
}
else
ret = new UnityDisplaySurfaceBase();
ret->api = api;
return ret;
}
- (void)recreateSurface:(RenderingSurfaceParams)params
{
UnityDisplaySurfaceBase* surface = [self initRendering];
// On metal we depend on hardware screen compositor to handle upscaling this way avoiding additional blit
CGSize layerSize = _view.layer.bounds.size;
float scale = _view.contentScaleFactor;
CGSize screenSize = CGSizeMake(layerSize.width * scale, layerSize.height * scale);
// if we did request custom resolution we apply it here.
// for metal we use hardware scaler which will be triggered exactly because our window is not of "native" size
// but we also want to enforce native resolution as maximum, otherwise we might run out of memory vert fast
// TODO: how about supersampling screenshots? maybe there are reasonable usecases
if (UnitySelectedRenderingAPI() == apiMetal && params.renderW > 0 && params.renderH > 0)
_screenSize = CGSizeMake(fminf(screenSize.width, params.renderW), fminf(screenSize.height, params.renderH));
else
_screenSize = screenSize;
bool systemSizeChanged = surface->systemW != _screenSize.width || surface->systemH != _screenSize.height;
bool msaaChanged = surface->msaaSamples != params.msaaSampleCount;
bool depthFmtChanged = surface->disableDepthAndStencil != params.disableDepthAndStencil;
bool cvCacheChanged = surface->useCVTextureCache != params.useCVTextureCache;
bool memorylessChanged = surface->memorylessDepth != params.metalMemorylessDepth;
bool renderSizeChanged = false;
if ((params.renderW > 0 && surface->targetW != params.renderW) // changed resolution
|| (params.renderH > 0 && surface->targetH != params.renderH) // changed resolution
|| (params.renderW <= 0 && surface->targetW != surface->systemW) // no longer need intermediate fb
|| (params.renderH <= 0 && surface->targetH != surface->systemH) // no longer need intermediate fb
)
{
renderSizeChanged = true;
}
bool recreateSystemSurface = systemSizeChanged;
bool recreateRenderingSurface = systemSizeChanged || renderSizeChanged || msaaChanged || cvCacheChanged;
bool recreateDepthbuffer = systemSizeChanged || renderSizeChanged || msaaChanged || depthFmtChanged || memorylessChanged;
surface->disableDepthAndStencil = params.disableDepthAndStencil;
surface->systemW = (unsigned)_screenSize.width;
surface->systemH = (unsigned)_screenSize.height;
surface->targetW = params.renderW > 0 ? params.renderW : surface->systemW;
surface->targetH = params.renderH > 0 ? params.renderH : surface->systemH;
surface->msaaSamples = params.msaaSampleCount;
surface->srgb = params.srgb;
surface->wideColor = params.wideColor;
surface->hdr = params.hdr;
surface->useCVTextureCache = params.useCVTextureCache;
surface->memorylessDepth = params.metalMemorylessDepth;
const int api = UnitySelectedRenderingAPI();
if (api == apiMetal)
{
UnityDisplaySurfaceMTL* mtlSurf = (UnityDisplaySurfaceMTL*)surface;
recreateSystemSurface = recreateSystemSurface || mtlSurf->systemColorRB == 0;
mtlSurf->framebufferOnly = params.metalFramebufferOnly;
}
if (recreateSystemSurface)
CreateSystemRenderingSurface(surface);
if (recreateRenderingSurface)
CreateRenderingSurface(surface);
if (recreateDepthbuffer)
CreateSharedDepthbuffer(surface);
if (recreateSystemSurface || recreateRenderingSurface || recreateDepthbuffer)
CreateUnityRenderBuffers(surface);
_surface = surface;
#if !PLATFORM_VISIONOS
UnityInvalidateDisplayDataCache((__bridge void*)_screen);
#endif
}
- (void)destroySurface
{
if (_surface)
{
DestroySystemRenderingSurface(_surface);
DestroyRenderingSurface(_surface);
DestroySharedDepthbuffer(_surface);
DestroyUnityRenderBuffers(_surface);
const int api = UnitySelectedRenderingAPI();
if (api == apiMetal)
{
self.surfaceMTL->device = nil;
self.surfaceMTL->layer = nil;
}
}
delete _surface;
_surface = 0;
}
- (void)dealloc
{
NSAssert(_surface == 0, @"At this point surface should be already destroyed!");
_view = nil;
_window = nil;
}
- (void)present
{
PreparePresent(self.surface);
Present(self.surface);
if (_needRecreateSurface)
{
RenderingSurfaceParams params =
{
.msaaSampleCount = _surface->msaaSamples,
.renderW = (int)_requestedRenderingSize.width,
.renderH = (int)_requestedRenderingSize.height,
.srgb = _surface->srgb,
.wideColor = _surface->wideColor,
.hdr = _surface->hdr,
.metalFramebufferOnly = 0,
.metalMemorylessDepth = 0,
.disableDepthAndStencil = _surface->disableDepthAndStencil,
.useCVTextureCache = self.surface->cvTextureCache != 0,
};
[self recreateSurface: params];
_needRecreateSurface = NO;
_requestedRenderingSize = CGSizeMake(_surface->targetW, _surface->targetH);
}
}
- (void)requestRenderingResolution:(CGSize)res
{
_requestedRenderingSize = res;
_needRecreateSurface = YES;
}
@end
#if !PLATFORM_VISIONOS
@implementation DisplayManager
{
NSMapTable* _displayConnection;
DisplayConnection* _mainDisplay;
}
@synthesize mainDisplay = _mainDisplay;
@synthesize displayCount;
- (NSUInteger)displayCount { return _displayConnection.count; }
- (void)registerScreen:(UIScreen*)screen
{
[_displayConnection setObject: [[DisplayConnection alloc] init: screen] forKey: screen];
}
- (id)init
{
if ((self = [super init]))
{
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(screenDidConnect:)
name: UIScreenDidConnectNotification
object: nil
];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(screenDidDisconnect:)
name: UIScreenDidDisconnectNotification
object: nil
];
_displayConnection = [NSMapTable
mapTableWithKeyOptions: NSPointerFunctionsStrongMemory | NSPointerFunctionsObjectPointerPersonality
valueOptions: NSPointerFunctionsStrongMemory | NSPointerFunctionsObjectPointerPersonality
];
for (UIScreen* screen in [UIScreen screens])
[self registerScreen: screen];
_mainDisplay = self[[UIScreen mainScreen]];
}
return self;
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver: self];
}
- (BOOL)displayAvailable:(UIScreen*)targetScreen;
{
return self[targetScreen] != nil;
}
- (DisplayConnection*)display:(UIScreen*)targetScreen
{
return self[targetScreen];
}
- (id)objectForKeyedSubscript:(id)key
{
NSAssert([key isKindOfClass: [UIScreen class]], @"DisplayManager allows only UIScreen as subscript");
return [_displayConnection objectForKey: (UIScreen*)key];
}
- (void)updateDisplayListCacheInUnity
{
// [UIScreen screens] might be out of sync to what is indicated to the
// application via UIScreenDidConnectNotification and UIScreenDidDisconnectNotification
// notifications. For example, on disconnection [UIScreen screens] might still
// have the screen that the display manager no longer knows about.
const unsigned MAX_DISPLAYS_SUPPORTED = 8; // sync this to the value on Unity side
void* screens[MAX_DISPLAYS_SUPPORTED];
unsigned screenCount = 0;
UIScreen* mainScreen = [UIScreen mainScreen];
screens[screenCount++] = (__bridge void*)mainScreen;
for (UIScreen* screen in _displayConnection)
{
if (screen == mainScreen)
continue;
screens[screenCount++] = (__bridge void*)screen;
}
UnityUpdateDisplayListCache(screens, screenCount);
}
- (void)enumerateDisplaysWithBlock:(void (^)(DisplayConnection* conn))block
{
for (UIScreen* screen in _displayConnection)
{
// if we want simple mirroring unity wont create rendering backing for display
// in that case we dont want to touch Display
DisplayConnection* conn = [_displayConnection objectForKey: screen];
if (conn.surface != nil)
block(conn);
}
}
- (void)enumerateNonMainDisplaysWithBlock:(void (^)(DisplayConnection* conn))block
{
for (UIScreen* screen in _displayConnection)
{
DisplayConnection* conn = [_displayConnection objectForKey: screen];
if (conn != _mainDisplay && conn.surface != nil)
block(conn);
}
}
- (void)startFrameRendering
{
[self enumerateDisplaysWithBlock:^(DisplayConnection* conn) {
StartFrameRendering(conn.surface);
}];
}
- (void)endFrameRendering
{
[self enumerateDisplaysWithBlock:^(DisplayConnection* conn) {
EndFrameRendering(conn.surface);
}];
}
- (void)present
{
[self enumerateDisplaysWithBlock:^(DisplayConnection* conn) {
[conn present];
}];
}
- (void)screenDidConnect:(NSNotification*)notification
{
[self registerScreen: (UIScreen*)[notification object]];
[self updateDisplayListCacheInUnity];
}
- (void)screenDidDisconnect:(NSNotification*)notification
{
UIScreen* screen = (UIScreen*)[notification object];
DisplayConnection* conn = (DisplayConnection*)self[screen];
if (conn != nil && conn.surface != nil)
UnityDisableRenderBuffers(conn.surface->unityColorBuffer, conn.surface->unityDepthBuffer);
[conn destroySurface];
conn = nil;
[_displayConnection removeObjectForKey: screen];
[self updateDisplayListCacheInUnity];
}
+ (void)Initialize
{
NSAssert(_DisplayManager == nil, @"[DisplayManager Initialize] called after creating handler");
if (!_DisplayManager)
_DisplayManager = [[DisplayManager alloc] init];
}
+ (DisplayManager*)Instance
{
if (!_DisplayManager)
_DisplayManager = [[DisplayManager alloc] init];
return _DisplayManager;
}
+ (void)Destroy
{
_DisplayManager = nil;
}
@end
#else
// xros DisplayManager
@implementation DisplayManager
{
DisplayConnection* _mainDisplay;
}
@synthesize mainDisplay = _mainDisplay;
@synthesize displayCount;
- (NSUInteger)displayCount { return 1; }
- (id)init
{
if ((self = [super init]))
{
_mainDisplay = [[DisplayConnection alloc] init];
// Unity needs a non-zero screen in order for renderloop to run
const int screenCount = 1;
void* screens[screenCount] = {(void*)0x1};
UnityUpdateDisplayListCache(screens, screenCount);
}
return self;
}
- (void)dealloc
{
}
- (void)startFrameRendering
{
StartFrameRendering(_mainDisplay.surface);
}
- (void)endFrameRendering
{
EndFrameRendering(_mainDisplay.surface);
}
- (void)present
{
[_mainDisplay present];
}
+ (void)Initialize
{
NSAssert(_DisplayManager == nil, @"[DisplayManager Initialize] called after creating handler");
if (!_DisplayManager)
_DisplayManager = [[DisplayManager alloc] init];
}
+ (DisplayManager*)Instance
{
if (!_DisplayManager)
_DisplayManager = [[DisplayManager alloc] init];
return _DisplayManager;
}
@end
#endif
//==============================================================================
//
// Unity Interface:
static void EnsureDisplayIsInited(DisplayConnection* conn)
{
// main screen view will be created in AppController,
// so we can assume that we need to init secondary display from script
// meaning: gles + show right away
if (conn.view == nil)
[conn createView: YES];
int api = UnitySelectedRenderingAPI();
bool needRecreate = false;
if (conn.surface == 0)
needRecreate = true;
else if (api == apiMetal)
needRecreate = conn.surfaceMTL->layer == nil;
if (needRecreate)
{
RenderingSurfaceParams params =
{
.msaaSampleCount = UnityGetDesiredMSAASampleCount(1),
.renderW = -1, // native resolution at first (can be changed later)
.renderH = -1, // native resolution at first (can be changed later)
.srgb = UnityGetSRGBRequested(),
.wideColor = 0, // i am not sure how to handle wide color here (and if it is even supported for airplay)
.hdr = 0,
.metalFramebufferOnly = UnityMetalFramebufferOnly(),
.metalMemorylessDepth = UnityMetalMemorylessDepth(),
.disableDepthAndStencil = UnityDisableDepthAndStencilBuffers(),
.useCVTextureCache = 0,
};
[conn recreateSurface: params];
{
DisplayConnection* main = [DisplayManager Instance].mainDisplay;
StartFrameRendering(main.surface);
}
}
}
#if !PLATFORM_TVOS
extern "C" int UnityDisplayManager_DisplayCount()
{
return (int)[DisplayManager Instance].displayCount;
}
extern "C" bool UnityDisplayManager_DisplayAvailable(void* nativeDisplay)
{
#if !PLATFORM_VISIONOS
if (nativeDisplay == NULL)
return false;
return [[DisplayManager Instance] displayAvailable: (__bridge UIScreen*)nativeDisplay];
#else
return false;
#endif
}
extern "C" bool UnityDisplayManager_DisplayActive(void* nativeDisplay)
{
#if !PLATFORM_VISIONOS
return UnityDisplayManager_DisplayAvailable(nativeDisplay);
#else
return true;
#endif
}
extern "C" void UnityDisplayManager_DisplaySystemResolution(void* nativeDisplay, int* w, int* h)
{
#if !PLATFORM_VISIONOS
if (nativeDisplay == NULL)
return;
DisplayConnection* conn = [DisplayManager Instance][(__bridge UIScreen*)nativeDisplay];
EnsureDisplayIsInited(conn);
// CODE ARCHEOLOGY: We were creating full-screen buffer for "system" RT, and (possibly) resized for "target" RT,
// CODE ARCHEOLOGY: and if the resolution was changed we were blitting target to system to rescale the image.
// CODE ARCHEOLOGY: Since then we have switched to using OS scaling mechanism, i.e. we are creating window
// CODE ARCHEOLOGY: with rendering extents and let iOS do the upscale
// CODE ARCHEOLOGY: We should revisit the rendering code to possibly get rid of the code needed for this setup
// CODE ARCHEOLOGY: but for now we do the minimal change to unbreak native resolution query
// note that we mimic size calculation that we use in other places, i.e. using screen bounds + content scale factor
// we should also note that we tweak CAMetalLayer.drawableSize (well, that's the way to trigger native upscale)
// so we have CAMetalLayer.drawableSize = rendering size
// and CAMetalLayer.size = system (native) size
const CGSize layerSize = conn.view.layer.bounds.size; const float scale = conn.view.contentScaleFactor;
*w = (int)(layerSize.width * scale);
*h = (int)(layerSize.height * scale);
#endif
}
extern "C" void UnityDisplayManager_DisplayRenderingResolution(void* nativeDisplay, int* w, int* h)
{
if (nativeDisplay == NULL)
return;
#if !PLATFORM_VISIONOS
DisplayConnection* conn = [DisplayManager Instance][(__bridge UIScreen*)nativeDisplay];
#else
DisplayConnection* conn = [DisplayManager Instance].mainDisplay;
#endif
EnsureDisplayIsInited(conn);
*w = (int)conn.surface->targetW;
*h = (int)conn.surface->targetH;
}
extern "C" void UnityDisplayManager_DisplayRenderingBuffers(void* nativeDisplay, void** colorBuffer, void** depthBuffer)
{
if (nativeDisplay == NULL)
return;
#if !PLATFORM_VISIONOS
DisplayConnection* conn = [DisplayManager Instance][(__bridge UIScreen*)nativeDisplay];
#else
DisplayConnection* conn = [DisplayManager Instance].mainDisplay;
#endif
EnsureDisplayIsInited(conn);
if (colorBuffer)
*colorBuffer = conn.surface->unityColorBuffer;
if (depthBuffer)
*depthBuffer = conn.surface->unityDepthBuffer;
}
extern "C" void UnityDisplayManager_SetRenderingResolution(void* nativeDisplay, int w, int h)
{
#if !PLATFORM_VISIONOS
if (nativeDisplay == NULL)
return;
UIScreen* screen = (__bridge UIScreen*)nativeDisplay;
DisplayConnection* conn = [DisplayManager Instance][screen];
EnsureDisplayIsInited(conn);
if (screen == [UIScreen mainScreen])
UnityRequestRenderingResolution(w, h);
else
[conn requestRenderingResolution: CGSizeMake(w, h)];
#endif
}
extern "C" int UnityDisplayManager_PrimaryDisplayIndex()
{
return 0;
}
#endif
extern "C" void UnityActivateScreenForRendering(void* nativeDisplay)
{
if (nativeDisplay == NULL)
return;
#if !PLATFORM_VISIONOS
DisplayConnection* conn = [DisplayManager Instance][(__bridge UIScreen*)nativeDisplay];
#else
DisplayConnection* conn = [DisplayManager Instance].mainDisplay;
#endif
EnsureDisplayIsInited(conn);
[conn shouldShowWindow: YES];
}
#if !PLATFORM_VISIONOS
extern "C" float UnityScreenScaleFactor(UIScreen* screen)
{
// NOTE: All views handled by Unity have their contentScaleFactor initialized
// to value returned by this function.
// we should query nativeScale if available to get the true device resolution
// this way we avoid unnecessarily large frame buffers and downscaling.
// e.g. iPhone 6+ pretends to be a x3 device, while its physical screen is x2.6 something.
// it is available on iOS 8.0+, tvOS 9.0+
// for older ios versions we add this selector ourselves (AddNewAPIImplIfNeeded in UnityAppController.mm)
// On AppleTV screen.nativeScale returns NaN when device is in sleep mode and starting from tvOS 10 (?) it returns 0.
if (isnan(screen.nativeScale) || (screen.nativeScale == 0))
return 1.0f;
else
{
float scalingFactor = UnityCalculateScalingFactorFromTargetDPI(screen);
if (scalingFactor > 0.0f)
return scalingFactor;
else
return screen.nativeScale;
}
return screen.scale;
}
extern "C" int UnityMainScreenRefreshRate()
{
return (int)[UIScreen mainScreen].maximumFramesPerSecond;
}
extern "C" void UnityStartFrameRendering()
{
[[DisplayManager Instance] startFrameRendering];
}
extern "C" void UnityDestroyUnityRenderSurfaces()
{
[[DisplayManager Instance] enumerateDisplaysWithBlock:^(DisplayConnection* conn) {
[conn destroySurface];
}];
}
extern "C" void UnitySetBrightness(float brightness)
{
#if !PLATFORM_TVOS
brightness = (brightness > 1.0 ? 1.0 : brightness) < 0 ? 0.0 : brightness;
UIScreen* screen = [UIScreen mainScreen];
screen.brightness = brightness;
#endif
}
extern "C" float UnityGetBrightness()
{
#if !PLATFORM_TVOS
UIScreen* screen = [UIScreen mainScreen];
return screen.brightness;
#else
return 1.0f;
#endif
}
extern "C" bool UnityIsFullscreen()
{
CGSize screenSize = [[[[DisplayManager Instance] mainDisplay] screen] bounds].size;
CGSize viewSize = [[[[DisplayManager Instance] mainDisplay] view] bounds].size;
return screenSize.width == viewSize.width && screenSize.height == viewSize.height;
}
#else
extern "C" int UnityMainScreenRefreshRate()
{
return 90;
}
extern "C" void UnityStartFrameRendering()
{
[[DisplayManager Instance] startFrameRendering];
}
extern "C" void UnityDestroyUnityRenderSurfaces()
{
[[DisplayManager Instance].mainDisplay destroySurface];
}
extern "C" void UnitySetBrightness(float brightness)
{
}
extern "C" float UnityGetBrightness()
{
return 1.0f;
}
extern "C" bool UnityIsFullscreen()
{
return false;
}
#endif

141
Classes/Unity/Filesystem.mm Normal file
View File

@ -0,0 +1,141 @@
#include <sys/xattr.h>
#include "UnityInterface.h"
#include <cstring>
static NSString* bundleIdWithData = nil;
extern "C" void UnitySetDataBundleDirWithBundleId(const char* bundleId)
{
if (bundleId) bundleIdWithData = [NSString stringWithUTF8String: bundleId];
else bundleIdWithData = nil;
}
extern "C" const char* UnityDataBundleDir()
{
static const char* dir = NULL;
if (dir == NULL)
{
if (bundleIdWithData == nil)
dir = AllocCString([[NSBundle mainBundle] bundlePath]);
else
dir = AllocCString([[NSBundle bundleWithIdentifier: bundleIdWithData] bundlePath]);
}
return dir;
}
#define RETURN_SPECIAL_DIR(dir) \
do { \
static const char* var = NULL; \
if (var == NULL) \
var = AllocCString(NSSearchPathForDirectoriesInDomains(dir, NSUserDomainMask, YES)[0]); \
return var; \
} while (0)
extern "C" const char* UnityDocumentsDir()
{
RETURN_SPECIAL_DIR(NSDocumentDirectory);
}
extern "C" const char* UnityLibraryDir()
{
RETURN_SPECIAL_DIR(NSLibraryDirectory);
}
extern "C" const char* UnityCachesDir()
{
RETURN_SPECIAL_DIR(NSCachesDirectory);
}
#undef RETURN_SPECIAL_DIR
extern "C" int UnityUpdateNoBackupFlag(const char* path, int setFlag)
{
int result;
if (setFlag)
{
u_int8_t b = 1;
result = ::setxattr(path, "com.apple.MobileBackup", &b, 1, 0, 0);
}
else
{
result = ::removexattr(path, "com.apple.MobileBackup", 0);
}
return result == 0 ? 1 : 0;
}
extern "C" const char* const* UnityFontFallbacks()
{
/* The following is the family names of fonts that are used as fallbacks
for characters that were not fount in user-specified fonts. Add more
fonts and/or reorder the list to fit your needs. For certain character
NOTE: Some similar Chinese, Japanese and Korean characters share the
character number in Unicode, but are written differently. To display
such characters properly, correct font must be selected. We reorder
the fonts list on the first run of this function.
*/
static const char** cachedFonts = NULL;
if (cachedFonts == NULL)
{
const int fontsToReorderCount = 4;
static const char* defaultFonts[] =
{
// first fontsToReorderCount items will be reordered if needed.
"Hiragino Kaku Gothic ProN", // Japanese characters
"Heiti TC", // Traditional Chinese characters (on 9.0 OS substitutes this with "PingFang TC")
"Heiti SC", // Simplified Chinese characters (on 9.0 OS substitutes this with "PingFang SC")
"Apple SD Gothic Neo", // Korean characters
".Sukhumvit Set UI", // Thai characters since 8.2 until 9.x
"AppleGothic",
"Noto Sans Yi", // Yi characters on 9.0 (not available on tvOS)
"Helvetica",
"Helvetica Neue",
"Arial Hebrew", // Hebrew since 9.0
"Kohinoor Devanagari", // Hindi since 9.0
"Kohinoor Bangla", // Bengali since 9.0
"Kohinoor Telugu", // Telugu since 9.0
"Lao Sangam MN", // Lao
"Geeza Pro", // Arabic
"Kailasa", // Tibetan since iOS 10.0
".PhoneFallback", // Armenian, Braille, Georgian, Thai, various symbols since iOS 10.0
// Note that iOS itself prefers Thonburi font for the Thai characters, but our font subsystem
// can't display combining characters for some reason
".LastResort",
NULL
};
// The default works for Japanese, we won't reorder in that case
static const char* koFontOrder[] =
{
"Apple SD Gothic Neo", // Korean characters
"Hiragino Kaku Gothic ProN", // Japanese characters
"Heiti TC", // Traditional Chinese characters (on 9.0 OS substitutes this with "PingFang TC")
"Heiti SC", // Simplified Chinese characters (on 9.0 OS substitutes this with "PingFang SC")
};
static const char* zhFontOrder[] =
{
"Heiti TC", // Traditional Chinese characters (on 9.0 OS substitutes this with "PingFang TC")
"Heiti SC", // Simplified Chinese characters (on 9.0 OS substitutes this with "PingFang SC")
"Hiragino Kaku Gothic ProN", // Japanese characters
"Apple SD Gothic Neo", // Korean characters
};
const char* lang = UnitySystemLanguage();
const char** fontOrderOverride = NULL;
if (std::strncmp(lang, "ko", 2) == 0)
fontOrderOverride = koFontOrder;
if (std::strncmp(lang, "zh", 2) == 0)
fontOrderOverride = zhFontOrder;
if (fontOrderOverride)
{
for (int i = 0; i < fontsToReorderCount; ++i)
defaultFonts[i] = fontOrderOverride[i];
}
cachedFonts = defaultFonts;
}
return cachedFonts;
}

View File

@ -0,0 +1,268 @@
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AVKit/AVKit.h>
#import <UIKit/UIGestureRecognizerSubclass.h>
#include "UnityAppController.h"
#include "UI/UnityView.h"
#include "UI/UnityViewControllerBase.h"
#include "UI/OrientationSupport.h"
#include "UI/UnityAppController+ViewHandling.h"
#include "Unity/ObjCRuntime.h"
#include "Unity/VideoPlayer.h"
#include "PluginBase/UnityViewControllerListener.h"
@interface UICancelGestureRecognizer : UITapGestureRecognizer
@end
@interface AVKitVideoPlayback : NSObject<VideoPlayerDelegate, UIViewControllerTransitioningDelegate, UIGestureRecognizerDelegate>
{
AVPlayerViewController* videoViewController;
VideoPlayer* videoPlayer;
UIColor* bgColor;
const NSString* videoGravity;
BOOL showControls;
BOOL cancelOnTouch;
}
- (void)onPlayerReady;
- (void)onPlayerDidFinishPlayingVideo;
- (id)initAndPlay:(NSURL*)url bgColor:(UIColor*)color showControls:(BOOL)controls videoGravity:(const NSString*)scaling cancelOnTouch:(BOOL)cot;
- (void)actuallyStartTheMovie:(NSURL*)url;
- (void)finish;
@end
static AVKitVideoPlayback* _AVKitVideoPlayback = nil;
@implementation AVKitVideoPlayback
#if PLATFORM_IOS || PLATFORM_VISIONOS
static void AVPlayerViewController_SetAllowsPictureInPicturePlayback_OldIOSImpl(id self_, SEL _cmd, BOOL allow) {}
static NSUInteger supportedInterfaceOrientations_DefaultImpl(id self_, SEL _cmd)
{
return GetAppController().rootViewController.supportedInterfaceOrientations;
}
static bool prefersStatusBarHidden_DefaultImpl(id self_, SEL _cmd)
{
if (_AVKitVideoPlayback) // video is still playing
return _AVKitVideoPlayback->videoViewController.showsPlaybackControls ? NO : YES;
else // video has beed stopped
return GetAppController().rootViewController.prefersStatusBarHidden;
}
#endif
+ (void)initialize
{
if (self == [AVKitVideoPlayback class])
{
#if PLATFORM_IOS || PLATFORM_VISIONOS
class_replaceMethod([AVPlayerViewController class], @selector(supportedInterfaceOrientations), (IMP)&supportedInterfaceOrientations_DefaultImpl, UIViewController_supportedInterfaceOrientations_Enc);
class_replaceMethod([AVPlayerViewController class], @selector(prefersStatusBarHidden), (IMP)&prefersStatusBarHidden_DefaultImpl, UIViewController_prefersStatusBarHidden_Enc);
#endif
}
}
- (id)initAndPlay:(NSURL*)url bgColor:(UIColor*)color showControls:(BOOL)controls videoGravity:(const NSString*)scaling cancelOnTouch:(BOOL)cot
{
if ((self = [super init]))
{
UnityPause(1);
showControls = controls;
videoGravity = scaling;
bgColor = color;
cancelOnTouch = cot;
[self performSelector: @selector(actuallyStartTheMovie:) withObject: url afterDelay: 0];
}
return self;
}
- (void)dealloc
{
[self finish];
}
- (void)actuallyStartTheMovie:(NSURL*)url
{
@autoreleasepool
{
videoViewController = [[AVPlayerViewController alloc] init];
videoViewController.showsPlaybackControls = showControls;
videoViewController.view.backgroundColor = bgColor;
videoViewController.videoGravity = (NSString*)videoGravity;
videoViewController.transitioningDelegate = self;
#if PLATFORM_IOS || PLATFORM_VISIONOS
videoViewController.allowsPictureInPicturePlayback = NO;
#endif
#if PLATFORM_TVOS
// In tvOS clicking Menu button while video is playing will exit the app. So when
// app disables exiting to menu behavior, we need to catch the click and ignore it.
if (!UnityGetAppleTVRemoteAllowExitToMenu())
{
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap:)];
tapRecognizer.allowedPressTypes = @[@(UIPressTypeMenu)];
[videoViewController.view addGestureRecognizer: tapRecognizer];
}
#endif
if (cancelOnTouch)
{
UICancelGestureRecognizer *cancelTouch = [[UICancelGestureRecognizer alloc] initWithTarget: self action: @selector(handleTap:)];
cancelTouch.delegate = self;
[videoViewController.view addGestureRecognizer: cancelTouch];
}
videoPlayer = [[VideoPlayer alloc] init];
videoPlayer.delegate = self;
[videoPlayer loadVideo: url];
}
}
- (void)handleTap:(UITapGestureRecognizer*)sender
{
if (cancelOnTouch && (sender.state == UIGestureRecognizerStateEnded))
[self finish];
}
- (void)onPlayerReady
{
videoViewController.player = videoPlayer.player;
CGSize screenSize = GetAppController().rootView.bounds.size;
BOOL ret = [VideoPlayer CheckScalingModeAspectFill: videoPlayer.videoSize screenSize: screenSize];
if (ret == YES && [videoViewController.videoGravity isEqualToString: AVLayerVideoGravityResizeAspect] == YES)
{
videoViewController.videoGravity = AVLayerVideoGravityResizeAspectFill;
}
[videoPlayer playVideoPlayer];
#if PLATFORM_TVOS
GetAppController().window.rootViewController = videoViewController;
#else
UIViewController *viewController = [GetAppController() topMostController];
if ([viewController isEqual: videoViewController] == NO && [videoViewController isBeingPresented] == NO)
[viewController presentViewController: videoViewController animated: NO completion: nil];
#endif
}
- (void)onPlayerDidFinishPlayingVideo
{
[self finish];
}
- (void)onPlayerTryResume
{
if (![videoPlayer isPlaying])
[videoPlayer resume];
}
- (void)onPlayerError:(NSError*)error
{
[self finish];
}
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
if ([dismissed isEqual: videoViewController] == YES)
{
[self finish];
}
return nil;
}
- (void)finish
{
@synchronized(self)
{
#if PLATFORM_TVOS
GetAppController().window.rootViewController = GetAppController().rootViewController;
#else
UIViewController *viewController = [GetAppController() topMostController];
if ([viewController isEqual: videoViewController] == YES && [viewController isBeingDismissed] == NO)
[viewController dismissViewControllerAnimated: NO completion: nil];
#endif
[videoPlayer unloadPlayer];
videoPlayer = nil;
videoViewController = nil;
_AVKitVideoPlayback = nil;
#if PLATFORM_TVOS
UnityCancelTouches();
#endif
if (UnityIsPaused())
UnityPause(0);
}
}
@end
@implementation UICancelGestureRecognizer
//instead of having lots of UITapGestureRecognizers with different finger numbers
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self setState: UIGestureRecognizerStateRecognized];
}
@end
extern "C" void UnityPlayFullScreenVideo(const char* path, const float* color, unsigned controls, unsigned scaling)
{
const BOOL cancelOnTouch[] = { NO, NO, YES, NO };
UIColor* bgColor = [UIColor colorWithRed: color[0] green: color[1] blue: color[2] alpha: color[3]];
const bool isURL = ::strstr(path, "://") != 0;
NSURL* url = nil;
if (isURL)
{
url = [NSURL URLWithString: [NSString stringWithUTF8String: path]];
}
else
{
NSString* relPath = path[0] == '/' ? [NSString stringWithUTF8String: path] : [NSString stringWithFormat: @"Data/Raw/%s", path];
NSString* fullPath = [[NSString stringWithUTF8String: UnityDataBundleDir()] stringByAppendingPathComponent: relPath];
url = [NSURL fileURLWithPath: fullPath];
}
const BOOL showControls[] = { YES, YES, NO, NO };
const NSString* videoGravity[] =
{
AVLayerVideoGravityResizeAspectFill, // ???
AVLayerVideoGravityResizeAspect,
AVLayerVideoGravityResizeAspectFill,
AVLayerVideoGravityResize,
};
if (_AVKitVideoPlayback)
[_AVKitVideoPlayback finish];
_AVKitVideoPlayback = [[AVKitVideoPlayback alloc] initAndPlay: url bgColor: bgColor
showControls: showControls[controls] videoGravity: videoGravity[scaling] cancelOnTouch: cancelOnTouch[controls]];
}
extern "C" void UnityStopFullScreenVideoIfPlaying()
{
if (_AVKitVideoPlayback)
[_AVKitVideoPlayback finish];
}
extern "C" int UnityIsFullScreenPlaying()
{
return _AVKitVideoPlayback ? 1 : 0;
}
extern "C" void TryResumeFullScreenVideo()
{
if (_AVKitVideoPlayback)
[_AVKitVideoPlayback onPlayerTryResume];
}

View File

@ -0,0 +1,62 @@
// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityInterface.h"
// Has to match the GfxDeviceRenderer enum
typedef enum UnityGfxRenderer
{
//kUnityGfxRendererOpenGL = 0, // Legacy OpenGL, removed
//kUnityGfxRendererD3D9 = 1, // Direct3D 9, removed
kUnityGfxRendererD3D11 = 2, // Direct3D 11
kUnityGfxRendererNull = 4, // "null" device (used in batch mode)
kUnityGfxRendererOpenGLES20 = 8, // OpenGL ES 2.0
kUnityGfxRendererOpenGLES30 = 11, // OpenGL ES 3.0
//kUnityGfxRendererGXM = 12, // PlayStation Vita, removed
kUnityGfxRendererPS4 = 13, // PlayStation 4
kUnityGfxRendererXboxOne = 14, // Xbox One
kUnityGfxRendererMetal = 16, // iOS Metal
kUnityGfxRendererOpenGLCore = 17, // OpenGL core
kUnityGfxRendererD3D12 = 18, // Direct3D 12
kUnityGfxRendererVulkan = 21, // Vulkan
kUnityGfxRendererNvn = 22, // Nintendo Switch NVN API
kUnityGfxRendererXboxOneD3D12 = 23, // MS XboxOne Direct3D 12
kUnityGfxRendererGameCoreXboxOne = 24, // GameCore Xbox One
kUnityGfxRendererGameCoreXboxSeries = 25, // GameCore XboxSeries
kUnityGfxRendererPS5 = 26, // PS5
kUnityGfxRendererPS5NGGC = 27 // PS5 NGGC
} UnityGfxRenderer;
typedef enum UnityGfxDeviceEventType
{
kUnityGfxDeviceEventInitialize = 0,
kUnityGfxDeviceEventShutdown = 1,
kUnityGfxDeviceEventBeforeReset = 2,
kUnityGfxDeviceEventAfterReset = 3,
} UnityGfxDeviceEventType;
typedef void (UNITY_INTERFACE_API * IUnityGraphicsDeviceEventCallback)(UnityGfxDeviceEventType eventType);
// Should only be used on the rendering thread unless noted otherwise.
UNITY_DECLARE_INTERFACE(IUnityGraphics)
{
UnityGfxRenderer(UNITY_INTERFACE_API * GetRenderer)(); // Thread safe
// This callback will be called when graphics device is created, destroyed, reset, etc.
// It is possible to miss the kUnityGfxDeviceEventInitialize event in case plugin is loaded at a later time,
// when the graphics device is already created.
void(UNITY_INTERFACE_API * RegisterDeviceEventCallback)(IUnityGraphicsDeviceEventCallback callback);
void(UNITY_INTERFACE_API * UnregisterDeviceEventCallback)(IUnityGraphicsDeviceEventCallback callback);
int(UNITY_INTERFACE_API * ReserveEventIDRange)(int count); // reserves 'count' event IDs. Plugins should use the result as a base index when issuing events back and forth to avoid event id clashes.
};
UNITY_REGISTER_INTERFACE_GUID(0x7CBA0A9CA4DDB544ULL, 0x8C5AD4926EB17B11ULL, IUnityGraphics)
// Certain Unity APIs (GL.IssuePluginEvent, CommandBuffer.IssuePluginEvent) can callback into native plugins.
// Provide them with an address to a function of this signature.
typedef void (UNITY_INTERFACE_API * UnityRenderingEvent)(int eventId);
typedef void (UNITY_INTERFACE_API * UnityRenderingEventAndData)(int eventId, void* data);

View File

@ -0,0 +1,117 @@
// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
#include "IUnityInterface.h"
#ifndef __OBJC__
#error metal plugin is objc code.
#endif
#ifndef __clang__
#error only clang compiler is supported.
#endif
@class NSBundle;
@protocol MTLDevice;
@protocol MTLCommandQueue;
@protocol MTLCommandBuffer;
@protocol MTLCommandEncoder;
@protocol MTLTexture;
@class MTLRenderPassDescriptor;
UNITY_DECLARE_INTERFACE(IUnityGraphicsMetalV2)
{
// V2
// Unity has it's own internal logic to happen on command buffer commit, so if you need to commit the current command buffer
// you need to call this function.
// It will just commit the current buffer and returns it (so it can be waited on by the caller code)
id<MTLCommandBuffer>(UNITY_INTERFACE_API * CommitCurrentCommandBuffer)();
// returns Unity Metal Command Queue
id<MTLCommandQueue>(UNITY_INTERFACE_API * CommandQueue)();
// V1
NSBundle* (UNITY_INTERFACE_API * MetalBundle)();
id<MTLDevice>(UNITY_INTERFACE_API * MetalDevice)();
id<MTLCommandBuffer>(UNITY_INTERFACE_API * CurrentCommandBuffer)();
// for custom rendering support there are two scenarios:
// you want to use current in-flight MTLCommandEncoder (NB: it might be nil)
id<MTLCommandEncoder>(UNITY_INTERFACE_API * CurrentCommandEncoder)();
// or you might want to create your own encoder.
// In that case you should end unity's encoder before creating your own and end yours before returning control to unity
void(UNITY_INTERFACE_API * EndCurrentCommandEncoder)();
// returns MTLRenderPassDescriptor used to create current MTLCommandEncoder
MTLRenderPassDescriptor* (UNITY_INTERFACE_API * CurrentRenderPassDescriptor)();
// converting trampoline UnityRenderBufferHandle into native RenderBuffer
UnityRenderBuffer(UNITY_INTERFACE_API * RenderBufferFromHandle)(void* bufferHandle);
// access to RenderBuffer's texure
// NB: you pass here *native* RenderBuffer, acquired by calling (C#) RenderBuffer.GetNativeRenderBufferPtr
// AAResolvedTextureFromRenderBuffer will return nil in case of non-AA RenderBuffer or if called for depth RenderBuffer
// StencilTextureFromRenderBuffer will return nil in case of no-stencil RenderBuffer or if called for color RenderBuffer
id<MTLTexture>(UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer buffer);
id<MTLTexture>(UNITY_INTERFACE_API * AAResolvedTextureFromRenderBuffer)(UnityRenderBuffer buffer);
id<MTLTexture>(UNITY_INTERFACE_API * StencilTextureFromRenderBuffer)(UnityRenderBuffer buffer);
};
UNITY_REGISTER_INTERFACE_GUID(0xF58857784FEF46ECULL, 0x9DB7A8803B87DA3DULL, IUnityGraphicsMetalV2)
UNITY_DECLARE_INTERFACE(IUnityGraphicsMetalV1)
{
NSBundle* (UNITY_INTERFACE_API * MetalBundle)();
id<MTLDevice>(UNITY_INTERFACE_API * MetalDevice)();
id<MTLCommandBuffer>(UNITY_INTERFACE_API * CurrentCommandBuffer)();
// for custom rendering support there are two scenarios:
// you want to use current in-flight MTLCommandEncoder (NB: it might be nil)
id<MTLCommandEncoder>(UNITY_INTERFACE_API * CurrentCommandEncoder)();
// or you might want to create your own encoder.
// In that case you should end unity's encoder before creating your own and end yours before returning control to unity
void(UNITY_INTERFACE_API * EndCurrentCommandEncoder)();
// returns MTLRenderPassDescriptor used to create current MTLCommandEncoder
MTLRenderPassDescriptor* (UNITY_INTERFACE_API * CurrentRenderPassDescriptor)();
// converting trampoline UnityRenderBufferHandle into native RenderBuffer
UnityRenderBuffer(UNITY_INTERFACE_API * RenderBufferFromHandle)(void* bufferHandle);
// access to RenderBuffer's texture
// NB: you pass here *native* RenderBuffer, acquired by calling (C#) RenderBuffer.GetNativeRenderBufferPtr
// AAResolvedTextureFromRenderBuffer will return nil in case of non-AA RenderBuffer or if called for depth RenderBuffer
// StencilTextureFromRenderBuffer will return nil in case of no-stencil RenderBuffer or if called for color RenderBuffer
id<MTLTexture>(UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer buffer);
id<MTLTexture>(UNITY_INTERFACE_API * AAResolvedTextureFromRenderBuffer)(UnityRenderBuffer buffer);
id<MTLTexture>(UNITY_INTERFACE_API * StencilTextureFromRenderBuffer)(UnityRenderBuffer buffer);
};
UNITY_REGISTER_INTERFACE_GUID(0x29F8F3D03833465EULL, 0x92138551C15D823DULL, IUnityGraphicsMetalV1)
// deprecated: please use versioned interface above
UNITY_DECLARE_INTERFACE(IUnityGraphicsMetal)
{
NSBundle* (UNITY_INTERFACE_API * MetalBundle)();
id<MTLDevice>(UNITY_INTERFACE_API * MetalDevice)();
id<MTLCommandBuffer>(UNITY_INTERFACE_API * CurrentCommandBuffer)();
id<MTLCommandEncoder>(UNITY_INTERFACE_API * CurrentCommandEncoder)();
void(UNITY_INTERFACE_API * EndCurrentCommandEncoder)();
MTLRenderPassDescriptor* (UNITY_INTERFACE_API * CurrentRenderPassDescriptor)();
UnityRenderBuffer(UNITY_INTERFACE_API * RenderBufferFromHandle)(void* bufferHandle);
id<MTLTexture>(UNITY_INTERFACE_API * TextureFromRenderBuffer)(UnityRenderBuffer buffer);
id<MTLTexture>(UNITY_INTERFACE_API * AAResolvedTextureFromRenderBuffer)(UnityRenderBuffer buffer);
id<MTLTexture>(UNITY_INTERFACE_API * StencilTextureFromRenderBuffer)(UnityRenderBuffer buffer);
};
UNITY_REGISTER_INTERFACE_GUID(0x992C8EAEA95811E5ULL, 0x9A62C4B5B9876117ULL, IUnityGraphicsMetal)

View File

@ -0,0 +1,206 @@
// Unity Native Plugin API copyright © 2015 Unity Technologies ApS
//
// Licensed under the Unity Companion License for Unity - dependent projects--see[Unity Companion License](http://www.unity3d.com/legal/licenses/Unity_Companion_License).
//
// Unless expressly provided otherwise, the Software under this license is made available strictly on an “AS IS” BASIS WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.Please review the license for details on these and other terms and conditions.
#pragma once
// Unity native plugin API
// Compatible with C99
#if defined(__CYGWIN32__)
#define UNITY_INTERFACE_API __stdcall
#define UNITY_INTERFACE_EXPORT __declspec(dllexport)
#elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(_WIN64) || defined(WINAPI_FAMILY)
#define UNITY_INTERFACE_API __stdcall
#define UNITY_INTERFACE_EXPORT __declspec(dllexport)
#elif defined(__MACH__) || defined(__ANDROID__) || defined(__linux__) || defined(LUMIN)
#define UNITY_INTERFACE_API
#define UNITY_INTERFACE_EXPORT __attribute__ ((visibility ("default")))
#else
#define UNITY_INTERFACE_API
#define UNITY_INTERFACE_EXPORT
#endif
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// IUnityInterface is a registry of interfaces we choose to expose to plugins.
//
// USAGE:
// ---------
// To retrieve an interface a user can do the following from a plugin, assuming they have the header file for the interface:
//
// IMyInterface * ptr = registry->Get<IMyInterface>();
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Unity Interface GUID
// Ensures global uniqueness.
//
// Template specialization is used to produce a means of looking up a GUID from its interface type at compile time.
// The net result should compile down to passing around the GUID.
//
// UNITY_REGISTER_INTERFACE_GUID should be placed in the header file of any interface definition outside of all namespaces.
// The interface structure and the registration GUID are all that is required to expose the interface to other systems.
struct UnityInterfaceGUID
{
#ifdef __cplusplus
UnityInterfaceGUID(unsigned long long high, unsigned long long low)
: m_GUIDHigh(high)
, m_GUIDLow(low)
{
}
UnityInterfaceGUID(const UnityInterfaceGUID& other)
{
m_GUIDHigh = other.m_GUIDHigh;
m_GUIDLow = other.m_GUIDLow;
}
UnityInterfaceGUID& operator=(const UnityInterfaceGUID& other)
{
m_GUIDHigh = other.m_GUIDHigh;
m_GUIDLow = other.m_GUIDLow;
return *this;
}
bool Equals(const UnityInterfaceGUID& other) const { return m_GUIDHigh == other.m_GUIDHigh && m_GUIDLow == other.m_GUIDLow; }
bool LessThan(const UnityInterfaceGUID& other) const { return m_GUIDHigh < other.m_GUIDHigh || (m_GUIDHigh == other.m_GUIDHigh && m_GUIDLow < other.m_GUIDLow); }
#endif
unsigned long long m_GUIDHigh;
unsigned long long m_GUIDLow;
};
#ifdef __cplusplus
inline bool operator==(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return left.Equals(right); }
inline bool operator!=(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return !left.Equals(right); }
inline bool operator<(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return left.LessThan(right); }
inline bool operator>(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return right.LessThan(left); }
inline bool operator>=(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return !operator<(left, right); }
inline bool operator<=(const UnityInterfaceGUID& left, const UnityInterfaceGUID& right) { return !operator>(left, right); }
#else
typedef struct UnityInterfaceGUID UnityInterfaceGUID;
#endif
#ifdef __cplusplus
#define UNITY_DECLARE_INTERFACE(NAME) \
struct NAME : IUnityInterface
// Generic version of GetUnityInterfaceGUID to allow us to specialize it
// per interface below. The generic version has no actual implementation
// on purpose.
//
// If you get errors about return values related to this method then
// you have forgotten to include UNITY_REGISTER_INTERFACE_GUID with
// your interface, or it is not visible at some point when you are
// trying to retrieve or add an interface.
template<typename TYPE>
inline const UnityInterfaceGUID GetUnityInterfaceGUID();
// This is the macro you provide in your public interface header
// outside of a namespace to allow us to map between type and GUID
// without the user having to worry about it when attempting to
// add or retrieve and interface from the registry.
#define UNITY_REGISTER_INTERFACE_GUID(HASHH, HASHL, TYPE) \
template<> \
inline const UnityInterfaceGUID GetUnityInterfaceGUID<TYPE>() \
{ \
return UnityInterfaceGUID(HASHH,HASHL); \
}
// Same as UNITY_REGISTER_INTERFACE_GUID but allows the interface to live in
// a particular namespace. As long as the namespace is visible at the time you call
// GetUnityInterfaceGUID< INTERFACETYPE >() or you explicitly qualify it in the template
// calls this will work fine, only the macro here needs to have the additional parameter
#define UNITY_REGISTER_INTERFACE_GUID_IN_NAMESPACE(HASHH, HASHL, TYPE, NAMESPACE) \
const UnityInterfaceGUID TYPE##_GUID(HASHH, HASHL); \
template<> \
inline const UnityInterfaceGUID GetUnityInterfaceGUID< NAMESPACE :: TYPE >() \
{ \
return UnityInterfaceGUID(HASHH,HASHL); \
}
// These macros allow for C compatibility in user code.
#define UNITY_GET_INTERFACE_GUID(TYPE) GetUnityInterfaceGUID< TYPE >()
#else
#define UNITY_DECLARE_INTERFACE(NAME) \
typedef struct NAME NAME; \
struct NAME
// NOTE: This has the downside that one some compilers it will not get stripped from all compilation units that
// can see a header containing this constant. However, it's only for C compatibility and thus should have
// minimal impact.
#define UNITY_REGISTER_INTERFACE_GUID(HASHH, HASHL, TYPE) \
const UnityInterfaceGUID TYPE##_GUID = {HASHH, HASHL};
// In general namespaces are going to be a problem for C code any interfaces we expose in a namespace are
// not going to be usable from C.
#define UNITY_REGISTER_INTERFACE_GUID_IN_NAMESPACE(HASHH, HASHL, TYPE, NAMESPACE)
// These macros allow for C compatibility in user code.
#define UNITY_GET_INTERFACE_GUID(TYPE) TYPE##_GUID
#endif
// Using this in user code rather than INTERFACES->Get<TYPE>() will be C compatible for those places in plugins where
// this may be needed. Unity code itself does not need this.
#define UNITY_GET_INTERFACE(INTERFACES, TYPE) (TYPE*)INTERFACES->GetInterfaceSplit (UNITY_GET_INTERFACE_GUID(TYPE).m_GUIDHigh, UNITY_GET_INTERFACE_GUID(TYPE).m_GUIDLow);
#ifdef __cplusplus
struct IUnityInterface
{
};
#else
typedef void IUnityInterface;
#endif
typedef struct IUnityInterfaces
{
// Returns an interface matching the guid.
// Returns nullptr if the given interface is unavailable in the active Unity runtime.
IUnityInterface* (UNITY_INTERFACE_API * GetInterface)(UnityInterfaceGUID guid);
// Registers a new interface.
void(UNITY_INTERFACE_API * RegisterInterface)(UnityInterfaceGUID guid, IUnityInterface * ptr);
// Split APIs for C
IUnityInterface* (UNITY_INTERFACE_API * GetInterfaceSplit)(unsigned long long guidHigh, unsigned long long guidLow);
void(UNITY_INTERFACE_API * RegisterInterfaceSplit)(unsigned long long guidHigh, unsigned long long guidLow, IUnityInterface * ptr);
#ifdef __cplusplus
// Helper for GetInterface.
template<typename INTERFACE>
INTERFACE* Get()
{
return static_cast<INTERFACE*>(GetInterface(GetUnityInterfaceGUID<INTERFACE>()));
}
// Helper for RegisterInterface.
template<typename INTERFACE>
void Register(IUnityInterface* ptr)
{
RegisterInterface(GetUnityInterfaceGUID<INTERFACE>(), ptr);
}
#endif
} IUnityInterfaces;
#ifdef __cplusplus
extern "C" {
#endif
// If exported by a plugin, this function will be called when the plugin is loaded.
void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginLoad(IUnityInterfaces* unityInterfaces);
// If exported by a plugin, this function will be called when the plugin is about to be unloaded.
void UNITY_INTERFACE_EXPORT UNITY_INTERFACE_API UnityPluginUnload();
#ifdef __cplusplus
}
#endif
struct RenderSurfaceBase;
typedef struct RenderSurfaceBase* UnityRenderBuffer;
typedef unsigned int UnityTextureID;

View File

@ -0,0 +1,375 @@
#include "InternalProfiler.h"
#include <stdint.h>
#include <stdio.h>
#include <mach/mach_time.h>
#define ENABLE_DETAILED_GC_STATS 0
#if ENABLE_INTERNAL_PROFILER
namespace
{
enum
{
GpuProfilerBlockEachNthFrame = 4
};
mach_timebase_info_data_t timebaseInfo;
void ProfilerInit()
{
mach_timebase_info(&timebaseInfo);
}
static float MachToMillisecondsDelta(int64_t delta)
{
// Convert to nanoseconds
delta *= timebaseInfo.numer;
delta /= timebaseInfo.denom;
float result = (float)delta / 1000000.0F;
return result;
}
struct ProfilerBlock
{
int64_t maxV, minV, avgV;
};
void ProfilerBlock_Update(struct ProfilerBlock* b, int64_t d, bool reset, bool avoidZero = false)
{
if (reset)
{
b->maxV = b->minV = b->avgV = d;
}
else
{
b->maxV = (d > b->maxV) ? d : b->maxV;
if (avoidZero && (b->minV == 0 || d == 0))
b->minV = (d > b->minV) ? d : b->minV;
else
b->minV = (d < b->minV) ? d : b->minV;
b->avgV += d;
}
}
ProfilerBlock _framePB;
ProfilerBlock _playerPB;
ProfilerBlock _batchCountPB;
ProfilerBlock _drawCallCountPB;
ProfilerBlock _triCountPB;
ProfilerBlock _vertCountPB;
ProfilerBlock _dynamicBatchDtPB;
ProfilerBlock _dynamicBatchCountPB;
ProfilerBlock _dynamicBatchedDrawCallCountPB;
ProfilerBlock _dynamicBatchedTriCountPB;
ProfilerBlock _dynamicBatchedVertCountPB;
ProfilerBlock _staticBatchCountPB;
ProfilerBlock _staticBatchedDrawCallCountPB;
ProfilerBlock _staticBatchedTriCountPB;
ProfilerBlock _staticBatchedVertCountPB;
ProfilerBlock _fixedBehaviourManagerPB;
ProfilerBlock _fixedPhysicsManagerPB;
ProfilerBlock _dynamicBehaviourManagerPB;
ProfilerBlock _coroutinePB;
ProfilerBlock _skinMeshUpdatePB;
ProfilerBlock _animationUpdatePB;
ProfilerBlock _unityRenderLoopPB;
ProfilerBlock _unityCullingPB;
ProfilerBlock _unityMSAAResolvePB;
ProfilerBlock _fixedUpdateCountPB;
ProfilerBlock _GCCountPB;
ProfilerBlock _GCDurationPB;
int _frameId = 0;
// our rendering is dictated by ios display link
// frametime will be time between two frame starts
// unity player time will be time between frame start/end
int64_t _lastFrameStart = -1;
int64_t _frameStart = 0;
int64_t _frameTime = 0;
int64_t _playerTime = 0;
int64_t _msaaResolveStart = 0;
int64_t _msaaResolve = 0;
void* _msaaResolveCounter = 0;
UnityFrameStats _unityFrameStats;
}
extern "C" int64_t UnityScriptingGetUsedSize();
extern "C" int64_t UnityScriptingGetHeapSize();
static void Profiler_SetupScriptingProfile();
void Profiler_InitProfiler()
{
Profiler_SetupScriptingProfile();
ProfilerInit();
if (_msaaResolveCounter == 0)
_msaaResolveCounter = UnityCreateProfilerCounter("iOS.MSAAResolve");
}
void Profiler_UninitProfiler()
{
UnityDestroyProfilerCounter(_msaaResolveCounter);
}
void Profiler_FrameStart()
{
_frameStart = mach_absolute_time();
if (_lastFrameStart < 0)
{
_lastFrameStart = _frameStart; return;
}
_frameTime = _frameStart - _lastFrameStart;
_lastFrameStart = _frameStart;
}
void Profiler_FrameEnd()
{
_playerTime = mach_absolute_time() - _frameStart;
}
void Profiler_FramePresent(const UnityFrameStats* unityFrameStats)
{
if (!unityFrameStats)
return;
_unityFrameStats = *unityFrameStats;
const int EachNthFrame = 32;
if (_frameId == EachNthFrame)
{
_frameId = 0;
::printf("iPhone Unity internal profiler stats\n");
::printf("frametime> min: %4.1f max: %4.1f avg: %4.1f\n", MachToMillisecondsDelta(_framePB.minV), MachToMillisecondsDelta(_framePB.maxV), MachToMillisecondsDelta(_framePB.avgV / EachNthFrame));
::printf("cpu-player> min: %4.1f max: %4.1f avg: %4.1f\n", MachToMillisecondsDelta(_playerPB.minV), MachToMillisecondsDelta(_playerPB.maxV), MachToMillisecondsDelta(_playerPB.avgV / EachNthFrame));
::printf("batches> min: %3d max: %3d avg: %3d\n", (int)_batchCountPB.minV, (int)_batchCountPB.maxV, (int)(_batchCountPB.avgV / EachNthFrame));
::printf("draw calls> min: %3d max: %3d avg: %3d\n", (int)_drawCallCountPB.minV, (int)_drawCallCountPB.maxV, (int)(_drawCallCountPB.avgV / EachNthFrame));
::printf("tris> min: %5d max: %5d avg: %5d\n", (int)_triCountPB.minV, (int)_triCountPB.maxV, (int)(_triCountPB.avgV / EachNthFrame));
::printf("verts> min: %5d max: %5d avg: %5d\n", (int)_vertCountPB.minV, (int)_vertCountPB.maxV, (int)(_vertCountPB.avgV / EachNthFrame));
::printf("dynamic batching> batched draw calls: %3d batches: %3d tris: %5d verts: %5d\n",
(int)(_dynamicBatchedDrawCallCountPB.avgV / EachNthFrame),
(int)(_dynamicBatchCountPB.avgV / EachNthFrame),
(int)(_dynamicBatchedTriCountPB.avgV / EachNthFrame),
(int)(_dynamicBatchedVertCountPB.avgV / EachNthFrame));
::printf("static batching> batched draw calls: %3d batches: %3d tris: %5d verts: %5d\n",
(int)(_staticBatchedDrawCallCountPB.avgV / EachNthFrame),
(int)(_staticBatchCountPB.avgV / EachNthFrame),
(int)(_staticBatchedTriCountPB.avgV / EachNthFrame),
(int)(_staticBatchedVertCountPB.avgV / EachNthFrame));
::printf("player-detail> physx: %4.1f animation: %4.1f culling %4.1f skinning: %4.1f batching: %4.1f render: %4.1f fixed-update-count: %d .. %d\n",
MachToMillisecondsDelta(_fixedPhysicsManagerPB.avgV / EachNthFrame),
MachToMillisecondsDelta(_animationUpdatePB.avgV / EachNthFrame),
MachToMillisecondsDelta(_unityCullingPB.avgV / EachNthFrame),
MachToMillisecondsDelta(_skinMeshUpdatePB.avgV / EachNthFrame),
MachToMillisecondsDelta(_dynamicBatchDtPB.avgV / EachNthFrame),
MachToMillisecondsDelta((_unityRenderLoopPB.avgV - _dynamicBatchDtPB.avgV - _unityCullingPB.avgV) / EachNthFrame),
(int)_fixedUpdateCountPB.minV, (int)_fixedUpdateCountPB.maxV);
::printf("scripting-scripts> update: %4.1f fixedUpdate: %4.1f coroutines: %4.1f \n", MachToMillisecondsDelta(_dynamicBehaviourManagerPB.avgV / EachNthFrame), MachToMillisecondsDelta(_fixedBehaviourManagerPB.avgV / EachNthFrame), MachToMillisecondsDelta(_coroutinePB.avgV / EachNthFrame));
#if UNITY_DEVELOPER_BUILD
::printf("scripting-memory> used heap: %lld allocated heap: %lld max number of collections: %d collection total duration: %4.1f\n", UnityScriptingGetUsedSize(), UnityScriptingGetHeapSize(), (int)_GCCountPB.avgV, MachToMillisecondsDelta(_GCDurationPB.avgV));
#else
::printf("scripting-memory> information not available on non-development player configuration\n");
#endif
::printf("----------------------------------------\n");
}
ProfilerBlock_Update(&_framePB, _frameTime, (_frameId == 0));
ProfilerBlock_Update(&_playerPB, _playerTime, (_frameId == 0));
ProfilerBlock_Update(&_batchCountPB, _unityFrameStats.batchCount, (_frameId == 0));
ProfilerBlock_Update(&_drawCallCountPB, _unityFrameStats.drawCallCount, (_frameId == 0));
ProfilerBlock_Update(&_triCountPB, _unityFrameStats.triCount, (_frameId == 0));
ProfilerBlock_Update(&_vertCountPB, _unityFrameStats.vertCount, (_frameId == 0));
ProfilerBlock_Update(&_dynamicBatchDtPB, _unityFrameStats.dynamicBatchDt, (_frameId == 0));
ProfilerBlock_Update(&_dynamicBatchCountPB, _unityFrameStats.dynamicBatchCount, (_frameId == 0));
ProfilerBlock_Update(&_dynamicBatchedDrawCallCountPB, _unityFrameStats.dynamicBatchedDrawCallCount, (_frameId == 0));
ProfilerBlock_Update(&_dynamicBatchedTriCountPB, _unityFrameStats.dynamicBatchedTris, (_frameId == 0));
ProfilerBlock_Update(&_dynamicBatchedVertCountPB, _unityFrameStats.dynamicBatchedVerts, (_frameId == 0));
ProfilerBlock_Update(&_staticBatchCountPB, _unityFrameStats.staticBatchCount, (_frameId == 0));
ProfilerBlock_Update(&_staticBatchedDrawCallCountPB, _unityFrameStats.staticBatchedDrawCallCount, (_frameId == 0));
ProfilerBlock_Update(&_staticBatchedTriCountPB, _unityFrameStats.staticBatchedTris, (_frameId == 0));
ProfilerBlock_Update(&_staticBatchedVertCountPB, _unityFrameStats.staticBatchedVerts, (_frameId == 0));
ProfilerBlock_Update(&_fixedBehaviourManagerPB, _unityFrameStats.fixedBehaviourManagerDt, (_frameId == 0));
ProfilerBlock_Update(&_fixedPhysicsManagerPB, _unityFrameStats.fixedPhysicsManagerDt, (_frameId == 0));
ProfilerBlock_Update(&_dynamicBehaviourManagerPB, _unityFrameStats.dynamicBehaviourManagerDt, (_frameId == 0));
ProfilerBlock_Update(&_coroutinePB, _unityFrameStats.coroutineDt, (_frameId == 0));
ProfilerBlock_Update(&_skinMeshUpdatePB, _unityFrameStats.skinMeshUpdateDt, (_frameId == 0));
ProfilerBlock_Update(&_animationUpdatePB, _unityFrameStats.animationUpdateDt, (_frameId == 0));
ProfilerBlock_Update(&_unityRenderLoopPB, _unityFrameStats.renderDt, (_frameId == 0));
ProfilerBlock_Update(&_unityCullingPB, _unityFrameStats.cullingDt, (_frameId == 0));
ProfilerBlock_Update(&_unityMSAAResolvePB, _msaaResolve, (_frameId == 0));
ProfilerBlock_Update(&_fixedUpdateCountPB, _unityFrameStats.fixedUpdateCount, (_frameId == 0));
ProfilerBlock_Update(&_GCCountPB, 0, (_frameId == 0));
ProfilerBlock_Update(&_GCDurationPB, 0, (_frameId == 0));
_msaaResolve = 0;
++_frameId;
}
void Profiler_StartMSAAResolve()
{
UnityStartProfilerCounter(_msaaResolveCounter);
_msaaResolveStart = mach_absolute_time();
}
void Profiler_EndMSAAResolve()
{
_msaaResolve += (mach_absolute_time() - _msaaResolveStart);
UnityEndProfilerCounter(_msaaResolveCounter);
}
//
// scriptint memory profiling
//
extern "C"
{
enum ScriptingGCEvent
{
SCRIPTING_GC_EVENT_START,
SCRIPTING_GC_EVENT_MARK_START,
SCRIPTING_GC_EVENT_MARK_END,
SCRIPTING_GC_EVENT_RECLAIM_START,
SCRIPTING_GC_EVENT_RECLAIM_END,
SCRIPTING_GC_EVENT_END,
SCRIPTING_GC_EVENT_PRE_STOP_WORLD,
SCRIPTING_GC_EVENT_POST_STOP_WORLD,
SCRIPTING_GC_EVENT_PRE_START_WORLD,
SCRIPTING_GC_EVENT_POST_START_WORLD
};
enum ScriptingProfileFlags
{
SCRIPTING_PROFILE_NONE = 0,
SCRIPTING_PROFILE_APPDOMAIN_EVENTS = 1 << 0,
SCRIPTING_PROFILE_ASSEMBLY_EVENTS = 1 << 1,
SCRIPTING_PROFILE_MODULE_EVENTS = 1 << 2,
SCRIPTING_PROFILE_CLASS_EVENTS = 1 << 3,
SCRIPTING_PROFILE_JIT_COMPILATION = 1 << 4,
SCRIPTING_PROFILE_INLINING = 1 << 5,
SCRIPTING_PROFILE_EXCEPTIONS = 1 << 6,
SCRIPTING_PROFILE_ALLOCATIONS = 1 << 7,
SCRIPTING_PROFILE_GC = 1 << 8,
SCRIPTING_PROFILE_THREADS = 1 << 9,
SCRIPTING_PROFILE_REMOTING = 1 << 10,
SCRIPTING_PROFILE_TRANSITIONS = 1 << 11,
SCRIPTING_PROFILE_ENTER_LEAVE = 1 << 12,
SCRIPTING_PROFILE_COVERAGE = 1 << 13,
SCRIPTING_PROFILE_INS_COVERAGE = 1 << 14,
SCRIPTING_PROFILE_STATISTICAL = 1 << 15,
SCRIPTING_PROFILE_METHOD_EVENTS = 1 << 16,
SCRIPTING_PROFILE_MONITOR_EVENTS = 1 << 17,
SCRIPTING_PROFILE_IOMAP_EVENTS = 1 << 18, /* this should likely be removed, too */
SCRIPTING_PROFILE_GC_MOVES = 1 << 19,
};
struct MemoryProfiler
{
int64_t gc_total_time;
int64_t gc_mark_time;
int64_t gc_reclaim_time;
int64_t gc_stop_world_time;
int64_t gc_start_world_time;
};
typedef void (*UnityScriptingProfileFunc)(void* /*MemoryProfiler*/ prof);
typedef void (*UnityScriptingProfileGCFunc)(void* /*MemoryProfiler*/ prof, int event, int generation);
typedef void (*UnityScriptingProfileGCResizeFunc)(void* /*MemoryProfiler*/ prof, int64_t new_size);
void UnityScriptingProfilerInstall(void* /*MemoryProfiler*/ prof, UnityScriptingProfileFunc shutdown_callback);
void UnityScriptingProfilerInstallGC(UnityScriptingProfileGCFunc callback, UnityScriptingProfileGCResizeFunc heap_resize_callback);
void UnityScriptingProfilerSetEvents(int /*ScriptingProfileFlags*/ events);
}
static MemoryProfiler _MemoryProfiler;
static void gc_event(void* profiler_, int event, int generation)
{
MemoryProfiler* profiler = (MemoryProfiler*)profiler_;
switch (event)
{
case SCRIPTING_GC_EVENT_START:
profiler->gc_total_time = mach_absolute_time();
break;
case SCRIPTING_GC_EVENT_END:
{
profiler->gc_total_time = mach_absolute_time() - profiler->gc_total_time;
float delta = profiler->gc_total_time;
ProfilerBlock_Update(&_GCDurationPB, delta, false);
ProfilerBlock_Update(&_GCCountPB, 1, false);
break;
}
case SCRIPTING_GC_EVENT_MARK_START:
profiler->gc_mark_time = mach_absolute_time();
break;
case SCRIPTING_GC_EVENT_MARK_END:
profiler->gc_mark_time = mach_absolute_time() - profiler->gc_mark_time;
break;
case SCRIPTING_GC_EVENT_RECLAIM_START:
profiler->gc_reclaim_time = mach_absolute_time();
break;
case SCRIPTING_GC_EVENT_RECLAIM_END:
profiler->gc_reclaim_time = mach_absolute_time() - profiler->gc_reclaim_time;
break;
case SCRIPTING_GC_EVENT_PRE_STOP_WORLD:
profiler->gc_stop_world_time = mach_absolute_time();
break;
case SCRIPTING_GC_EVENT_POST_STOP_WORLD:
profiler->gc_stop_world_time = mach_absolute_time() - profiler->gc_stop_world_time;
break;
case SCRIPTING_GC_EVENT_PRE_START_WORLD:
profiler->gc_start_world_time = mach_absolute_time();
break;
case SCRIPTING_GC_EVENT_POST_START_WORLD:
profiler->gc_start_world_time = mach_absolute_time() - profiler->gc_start_world_time;
break;
default:
break;
}
#if ENABLE_DETAILED_GC_STATS
if (event == SCRIPTING_GC_EVENT_END)
{
::printf("scripting-gc> stop time: %4.1f mark time: %4.1f reclaim time: %4.1f start time: %4.1f total time: %4.1f \n",
MachToMillisecondsDelta(profiler->gc_stop_world_time),
MachToMillisecondsDelta(profiler->gc_mark_time),
MachToMillisecondsDelta(profiler->gc_reclaim_time),
MachToMillisecondsDelta(profiler->gc_start_world_time),
MachToMillisecondsDelta(profiler->gc_total_time)
);
}
#endif
}
static void gc_resize(void* profiler, int64_t new_size)
{
}
static void profiler_shutdown(void* profiler)
{
}
static void Profiler_SetupScriptingProfile()
{
UnityScriptingProfilerInstall(&_MemoryProfiler, &profiler_shutdown);
UnityScriptingProfilerInstallGC(&gc_event, &gc_resize);
UnityScriptingProfilerSetEvents(SCRIPTING_PROFILE_GC);
}
#endif // ENABLE_INTERNAL_PROFILER

View File

@ -0,0 +1,32 @@
#pragma once
#define ENABLE_INTERNAL_PROFILER 0
// 4.x ENABLE_BLOCK_ON_GPU_PROFILER and 5.x ENABLE_GPU_TIMING were removed in favor of using xcode tools
// INCLUDE_OPENGLES_IN_RENDER_TIME was removed
#if ENABLE_INTERNAL_PROFILER
void Profiler_InitProfiler();
void Profiler_UninitProfiler();
void Profiler_FrameStart();
void Profiler_FrameEnd();
void Profiler_FramePresent(const UnityFrameStats*);
void Profiler_StartMSAAResolve();
void Profiler_EndMSAAResolve();
#else
inline void Profiler_InitProfiler() {}
inline void Profiler_UninitProfiler() {}
inline void Profiler_FrameStart() {}
inline void Profiler_FrameEnd() {}
inline void Profiler_FramePresent(const struct UnityFrameStats*) {}
inline void Profiler_StartMSAAResolve() {}
inline void Profiler_EndMSAAResolve() {}
#endif // ENABLE_INTERNAL_PROFILER

View File

@ -0,0 +1,461 @@
#include "UnityTrampolineCompatibility.h"
#include "UnityRendering.h"
#include "UnityMetalSupport.h"
#include <QuartzCore/QuartzCore.h>
#include <libkern/OSAtomic.h>
#if UNITY_TRAMPOLINE_IN_USE
#include "UnityAppController.h"
#include "CVTextureCache.h"
#endif
#include "ObjCRuntime.h"
#include <utility>
extern "C" void InitRenderingMTL()
{
}
static MTLPixelFormat GetColorFormatForSurface(const UnityDisplaySurfaceMTL* surface)
{
MTLPixelFormat colorFormat = MTLPixelFormatInvalid;
#if PLATFORM_OSX
if (surface->hdr)
{
// 0 = 10 bit, 1 = 16bit
if (@available(macOS 10.15, *))
colorFormat = UnityHDRSurfaceDepth() == 0 ? MTLPixelFormatRGB10A2Unorm : MTLPixelFormatRGBA16Float;
}
#endif
if(colorFormat == MTLPixelFormatInvalid && surface->wideColor)
{
// at some point we tried using MTLPixelFormatBGR10_XR formats, but it seems that apple CoreImage have issues with that
// and we are not alone here, see for example https://forums.developer.apple.com/forums/thread/66166
// when application goes to background the colors are changed (more white-ish?)
// no matter what we tried, the issue persists
// NOTE: the most funny thing is when we set color space to be P3 we get same whitish colors always
// NOTE: but this time they become normal when going to background
// in all, it seems that using rgba f16 is the most robust option here, so we are back to it again
colorFormat = MTLPixelFormatRGBA16Float;
}
if(colorFormat == MTLPixelFormatInvalid)
colorFormat = surface->srgb ? MTLPixelFormatBGRA8Unorm_sRGB : MTLPixelFormatBGRA8Unorm;
return colorFormat;
}
static uint32_t GetCVPixelFormatForSurface(const UnityDisplaySurfaceMTL* surface)
{
// this makes sense only for ios (at least we dont support this on macos)
uint32_t colorFormat = kCVPixelFormatType_32BGRA;
#if PLATFORM_IOS || PLATFORM_TVOS || PLATFORM_VISIONOS
if (surface->wideColor && UnityIsWideColorSupported())
colorFormat = kCVPixelFormatType_30RGB;
#endif
return colorFormat;
}
extern "C" void CreateSystemRenderingSurfaceMTL(UnityDisplaySurfaceMTL* surface)
{
DestroySystemRenderingSurfaceMTL(surface);
MTLPixelFormat colorFormat = GetColorFormatForSurface(surface);
surface->layer.presentsWithTransaction = NO;
surface->layer.drawsAsynchronously = YES;
#if !PLATFORM_OSX
if (UnityPreserveFramebufferAlpha())
{
const CGFloat components[] = {1.0f, 1.0f, 1.0f, 0.0f};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGColorRef color = CGColorCreate(colorSpace, components);
surface->layer.opaque = NO;
surface->layer.backgroundColor = color;
CGColorRelease(color);
CGColorSpaceRelease(colorSpace);
}
#endif
#if PLATFORM_OSX
surface->layer.opaque = YES;
MetalUpdateDisplaySync();
#endif
CGColorSpaceRef colorSpaceRef = nil;
#if PLATFORM_OSX
if (surface->hdr)
{
if (@available(macOS 11.0, *)) // 0 = 10bit
colorSpaceRef = UnityHDRSurfaceDepth() == 0 ? CGColorSpaceCreateWithName(CFSTR("kCGColorSpaceITUR_2100_PQ")) : CGColorSpaceCreateWithName(CFSTR("kCGColorSpaceExtendedLinearITUR_2020"));
else
colorSpaceRef = UnityHDRSurfaceDepth() == 0 ? CGColorSpaceCreateWithName(CFSTR("kCGColorSpaceITUR_2020_PQ_EOTF")) : CGColorSpaceCreateWithName(CFSTR("kCGColorSpaceExtendedLinearITUR_2020"));
}
#endif
if(colorSpaceRef == nil)
{
if (surface->wideColor)
colorSpaceRef = CGColorSpaceCreateWithName(surface->srgb ? kCGColorSpaceExtendedLinearSRGB : kCGColorSpaceExtendedSRGB);
else
colorSpaceRef = CGColorSpaceCreateWithName(kCGColorSpaceSRGB);
}
surface->layer.colorspace = colorSpaceRef;
CGColorSpaceRelease(colorSpaceRef);
// Update the native screen resolution
UnityUpdateDrawableSize(surface);
surface->layer.device = surface->device;
surface->layer.pixelFormat = colorFormat;
surface->layer.framebufferOnly = (surface->framebufferOnly != 0);
surface->colorFormat = (unsigned)colorFormat;
MTLTextureDescriptor* txDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat: colorFormat width: surface->systemW height: surface->systemH mipmapped: NO];
#if PLATFORM_OSX
txDesc.resourceOptions = MTLResourceCPUCacheModeDefaultCache | MTLResourceStorageModeManaged;
#endif
txDesc.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
@synchronized(surface->layer)
{
#if PLATFORM_OSX
surface->proxySwaps = 0;
surface->proxyReady = 0;
surface->calledPresentDrawable = 0;
surface->vsync = 1; // by default, vsync is enabled for all surfaces
#endif
for (int i = 0; i < kUnityNumOffscreenSurfaces; i++)
{
UnityUnregisterMetalTextureForMemoryProfiler(surface->drawableProxyRT[i]);
// Allocating a proxy texture is cheap until it's being rendered to and the GPU driver does allocation
surface->drawableProxyRT[i] = [surface->device newTextureWithDescriptor: txDesc];
surface->drawableProxyRT[i].label = @"DrawableProxy";
#if PLATFORM_IOS || PLATFORM_TVOS || PLATFORM_VISIONOS
[surface->drawableProxyRT[i] setPurgeableState: MTLPurgeableStateEmpty];
#endif
// Mark each drawableProxy surface as needing a clear load action when next rendered to as its contents are undefined.
surface->drawableProxyNeedsClear[i] = true;
UnityRegisterExternalRenderSurfaceTextureForMemoryProfiler(surface->drawableProxyRT[i]);
}
}
}
extern "C" void CreateRenderingSurfaceMTL(UnityDisplaySurfaceMTL* surface)
{
DestroyRenderingSurfaceMTL(surface);
MTLPixelFormat colorFormat = GetColorFormatForSurface(surface);
const int w = surface->targetW, h = surface->targetH;
if (w != surface->systemW || h != surface->systemH || surface->useCVTextureCache)
{
#if PLATFORM_IOS || PLATFORM_TVOS || PLATFORM_VISIONOS
if (surface->useCVTextureCache)
surface->cvTextureCache = CreateCVTextureCache();
if (surface->cvTextureCache)
{
surface->cvTextureCacheTexture = CreateReadableRTFromCVTextureCache2(surface->cvTextureCache, surface->targetW, surface->targetH,
GetCVPixelFormatForSurface(surface), colorFormat, &surface->cvPixelBuffer);
surface->targetColorRT = GetMetalTextureFromCVTextureCache(surface->cvTextureCacheTexture);
}
else
#endif
{
MTLTextureDescriptor* txDesc = [MTLTextureDescriptor new];
txDesc.textureType = MTLTextureType2D;
txDesc.width = w;
txDesc.height = h;
txDesc.depth = 1;
txDesc.pixelFormat = colorFormat;
txDesc.arrayLength = 1;
txDesc.mipmapLevelCount = 1;
#if PLATFORM_OSX
txDesc.resourceOptions = MTLResourceStorageModeManaged;
#endif
txDesc.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
surface->targetColorRT = [surface->device newTextureWithDescriptor: txDesc];
}
surface->targetColorRT.label = @"targetColorRT";
UnityRegisterExternalRenderSurfaceTextureForMemoryProfiler(surface->targetColorRT);
}
if (surface->msaaSamples > 1)
{
MTLTextureDescriptor* txDesc = [MTLTextureDescriptor new];
txDesc.textureType = MTLTextureType2DMultisample;
txDesc.width = w;
txDesc.height = h;
txDesc.depth = 1;
txDesc.pixelFormat = colorFormat;
txDesc.arrayLength = 1;
txDesc.mipmapLevelCount = 1;
txDesc.sampleCount = surface->msaaSamples;
txDesc.resourceOptions = MTLResourceStorageModePrivate;
txDesc.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
if (![surface->device supportsTextureSampleCount: txDesc.sampleCount])
txDesc.sampleCount = 4;
surface->targetAAColorRT = [surface->device newTextureWithDescriptor: txDesc];
surface->targetAAColorRT.label = @"targetAAColorRT";
UnityRegisterExternalRenderSurfaceTextureForMemoryProfiler(surface->targetAAColorRT);
}
}
extern "C" void DestroyRenderingSurfaceMTL(UnityDisplaySurfaceMTL* surface)
{
UnityUnregisterMetalTextureForMemoryProfiler(surface->targetColorRT);
surface->targetColorRT = nil;
UnityUnregisterMetalTextureForMemoryProfiler(surface->targetAAColorRT);
surface->targetAAColorRT = nil;
if (surface->cvTextureCacheTexture)
CFRelease(surface->cvTextureCacheTexture);
if (surface->cvPixelBuffer)
CFRelease(surface->cvPixelBuffer);
if (surface->cvTextureCache)
CFRelease(surface->cvTextureCache);
surface->cvTextureCache = 0;
}
extern "C" void CreateSharedDepthbufferMTL(UnityDisplaySurfaceMTL* surface)
{
DestroySharedDepthbufferMTL(surface);
if (surface->disableDepthAndStencil)
return;
MTLPixelFormat pixelFormat = MTLPixelFormatDepth32Float_Stencil8;
MTLTextureDescriptor* depthTexDesc = [MTLTextureDescriptor texture2DDescriptorWithPixelFormat: pixelFormat width: surface->targetW height: surface->targetH mipmapped: NO];
depthTexDesc.resourceOptions = MTLResourceStorageModePrivate;
#if PLATFORM_IOS || PLATFORM_TVOS || PLATFORM_VISIONOS
if (surface->memorylessDepth)
depthTexDesc.storageMode = MTLStorageModeMemoryless;
#endif
depthTexDesc.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
if (surface->msaaSamples > 1)
{
depthTexDesc.textureType = MTLTextureType2DMultisample;
depthTexDesc.sampleCount = surface->msaaSamples;
if (![surface->device supportsTextureSampleCount: depthTexDesc.sampleCount])
depthTexDesc.sampleCount = 4;
}
surface->depthRB = [surface->device newTextureWithDescriptor: depthTexDesc];
surface->stencilRB = surface->depthRB;
UnityRegisterExternalRenderSurfaceTextureForMemoryProfiler(surface->depthRB);
}
extern "C" void DestroySharedDepthbufferMTL(UnityDisplaySurfaceMTL* surface)
{
UnityUnregisterMetalTextureForMemoryProfiler(surface->depthRB);
surface->depthRB = nil;
surface->stencilRB = nil;
}
extern "C" void CreateUnityRenderBuffersMTL(UnityDisplaySurfaceMTL* surface)
{
UnityRenderBufferDesc sys_desc = { surface->systemW, surface->systemH, 1, 1, 1 };
UnityRenderBufferDesc tgt_desc = { surface->targetW, surface->targetH, 1, (unsigned int)surface->msaaSamples, 1 };
// note that StartFrameRenderingMTL/AcquireDrawableMTL/EndFrameRenderingMTL happen on the render thread
// while CreateUnityRenderBuffersMTL/DestroyUnityRenderBuffersMTL happen on main
MTLTextureRef systemColorRB = nil;
@synchronized(surface->layer)
{
for (unsigned i = 0; i < kUnityNumOffscreenSurfaces; ++i)
surface->drawableProxyRS[i] = UnityCreateExternalColorSurfaceMTL(surface->drawableProxyRS[i], surface->drawableProxyRT[i], nil, &sys_desc, surface);
systemColorRB = surface->drawableProxyRT[0];
}
surface->systemColorRB = systemColorRB;
// we could unify all of it with ugly chain of ternary operators but what if karma exists?
if (surface->targetColorRT)
{
// render to interim RT: we do NOT need to request drawable
MTLTextureRef texRender = surface->targetAAColorRT ? surface->targetAAColorRT : surface->targetColorRT;
MTLTextureRef texResolve = surface->targetAAColorRT ? surface->targetColorRT : nil;
surface->unityColorBuffer = UnityCreateExternalColorSurfaceMTL(surface->unityColorBuffer, texRender, texResolve, &tgt_desc, nil);
}
else
{
// render to backbuffer directly: we will request drawable hence we need to pass surface
MTLTextureRef texRender = surface->targetAAColorRT ? surface->targetAAColorRT : systemColorRB;
MTLTextureRef texResolve = surface->targetAAColorRT ? systemColorRB : nil;
surface->unityColorBuffer = UnityCreateExternalColorSurfaceMTL(surface->unityColorBuffer, texRender, texResolve, &tgt_desc, surface);
}
if (surface->depthRB)
surface->unityDepthBuffer = UnityCreateExternalDepthSurfaceMTL(surface->unityDepthBuffer, surface->depthRB, surface->stencilRB, &tgt_desc);
else
surface->unityDepthBuffer = UnityCreateDummySurface(surface->unityDepthBuffer, false, &tgt_desc);
surface->systemColorBuffer = UnityCreateExternalColorSurfaceMTL(surface->systemColorBuffer, systemColorRB, nil, &sys_desc, surface);
surface->systemDepthBuffer = UnityCreateDummySurface(surface->systemDepthBuffer, false, &sys_desc);
}
extern "C" void DestroySystemRenderingSurfaceMTL(UnityDisplaySurfaceMTL* surface)
{
// before we needed to nil surface->systemColorRB (to release drawable we get from the view)
// but after we switched to proxy rt this is no longer needed
// even more it is harmful when running rendering on another thread (as is default now)
// as on render thread we do StartFrameRenderingMTL/AcquireDrawableMTL/EndFrameRenderingMTL
// and DestroySystemRenderingSurfaceMTL comes on main thread so we might end up with race condition for no reason
}
extern "C" void DestroyUnityRenderBuffersMTL(UnityDisplaySurfaceMTL* surface)
{
UnityDestroyExternalSurface(surface->unityColorBuffer);
UnityDestroyExternalSurface(surface->systemColorBuffer);
surface->unityColorBuffer = surface->systemColorBuffer = 0;
UnityDestroyExternalSurface(surface->unityDepthBuffer);
UnityDestroyExternalSurface(surface->systemDepthBuffer);
surface->unityDepthBuffer = surface->systemDepthBuffer = 0;
@synchronized(surface->layer)
{
for (unsigned i = 0; i < kUnityNumOffscreenSurfaces; ++i)
{
UnityDestroyExternalSurface(surface->drawableProxyRS[i]);
surface->drawableProxyRS[i] = 0;
}
}
}
extern "C" void PreparePresentMTL(UnityDisplaySurfaceMTL* surface)
{
if (surface->targetColorRT)
UnityBlitToBackbuffer(surface->unityColorBuffer, surface->systemColorBuffer, surface->systemDepthBuffer);
#if UNITY_TRAMPOLINE_IN_USE
APP_CONTROLLER_RENDER_PLUGIN_METHOD(onFrameResolved);
#endif
}
extern "C" void PresentMTL(UnityDisplaySurfaceMTL* surface)
{
//ARCHEOLOGY: we used to present using [MTLCommandBuffer presentDrawable:afterMinimumDuration:]
//however that was found to sometimes cause 0.5s-1s hangs when acquiring drawable after surface rebuild, or presenting hanging completely (UUM-9480)
//after some further investigation we found that using the more complex present logic didn't actually yield much benefit
//current implementation is made to align with our macOS present logic
if (surface->drawable)
{
id<CAMetalDrawable> drawable = surface->drawable;
[UnityCurrentMTLCommandBuffer() addScheduledHandler:^(id<MTLCommandBuffer> commandBuffer) {
[drawable present];
}];
}
surface->calledPresentDrawable = 1;
}
extern "C" MTLTextureRef AcquireDrawableMTL(UnityDisplaySurfaceMTL* surface)
{
if (!surface)
return nil;
if (!surface->drawable)
surface->drawable = [surface->layer nextDrawable];
// on A7 SoC nextDrawable may be nil before locking the screen
if (!surface->drawable)
return nil;
id<MTLTexture> drawableTex = [surface->drawable texture];
UnityUnregisterMetalTextureForMemoryProfiler(surface->drawableTex);
surface->drawableTex = surface->systemColorRB = drawableTex;
UnityRegisterExternalRenderSurfaceTextureForMemoryProfiler(drawableTex);
return drawableTex;
}
extern "C" int UnityCommandQueueMaxCommandBufferCountMTL()
{
// customizable argument to pass towards [MTLDevice newCommandQueueWithMaxCommandBufferCount:],
// the default value is 64 but with Parallel Render Encoder workloads, it might need to be increased
return 256;
}
extern "C" void StartFrameRenderingMTL(UnityDisplaySurfaceMTL* surface)
{
// we will acquire drawable lazily in AcquireDrawableMTL
if (surface->drawableTex)
UnityUnregisterMetalTextureForMemoryProfiler(surface->drawableTex);
surface->drawable = nil;
surface->drawableTex = nil;
surface->systemColorRB = surface->drawableProxyRT[0];
UnityRenderBufferDesc sys_desc = { surface->systemW, surface->systemH, 1, 1, 1};
UnityRenderBufferDesc tgt_desc = { surface->targetW, surface->targetH, 1, (unsigned int)surface->msaaSamples, 1};
surface->systemColorBuffer = UnityCreateExternalColorSurfaceMTL(surface->systemColorBuffer, surface->systemColorRB, nil, &sys_desc, surface);
if (surface->targetColorRT == nil)
{
if (surface->targetAAColorRT)
surface->unityColorBuffer = UnityCreateExternalColorSurfaceMTL(surface->unityColorBuffer, surface->targetAAColorRT, surface->systemColorRB, &tgt_desc, surface);
else
surface->unityColorBuffer = UnityCreateExternalColorSurfaceMTL(surface->unityColorBuffer, surface->systemColorRB, nil, &tgt_desc, surface);
}
}
extern "C" void EndFrameRenderingMTL(UnityDisplaySurfaceMTL* surface)
{
@autoreleasepool
{
if (surface->drawableTex)
UnityUnregisterMetalTextureForMemoryProfiler(surface->drawableTex);
surface->drawable = nil;
surface->drawableTex = nil;
surface->systemColorRB = surface->drawableProxyRT[0];
}
#if PLATFORM_OSX
@synchronized(surface->layer)
{
if (!surface->calledPresentDrawable)
return;
surface->calledPresentDrawable = 0;
std::swap(surface->drawableProxyRT[0], surface->drawableProxyRT[1]);
std::swap(surface->drawableProxyRS[0], surface->drawableProxyRS[1]);
surface->proxySwaps++;
surface->proxyReady = 1;
// Swap the needs clear state of the swapped proxy buffers, to ensure that each surface
// will get cleared at least once when the proxy buffer surfaces are recreated.
std::swap(surface->drawableProxyNeedsClear[0],
surface->drawableProxyNeedsClear[1]);
}
#endif
}
extern "C" void PreparePresentNonMainScreenMTL(UnityDisplaySurfaceMTL* surface)
{
if (surface->drawable)
[UnityCurrentMTLCommandBuffer() presentDrawable: surface->drawable];
}
extern "C" void SetDrawableSizeMTL(UnityDisplaySurfaceMTL* surface, int width, int height)
{
surface->layer.drawableSize = CGSizeMake(width, height);
}

View File

@ -0,0 +1,37 @@
#include "UnityRendering.h"
extern "C" void CreateUnityRenderBuffersNULL(UnityDisplaySurfaceBase* surface)
{
UnityRenderBufferDesc sys_desc = { surface->systemW, surface->systemH, 1, 1, 1 };
UnityRenderBufferDesc tgt_desc = { surface->targetW, surface->targetH, 1, (unsigned int)surface->msaaSamples, 1 };
surface->unityColorBuffer = UnityCreateDummySurface(surface->unityColorBuffer, true, &tgt_desc);
surface->unityDepthBuffer = UnityCreateDummySurface(surface->unityDepthBuffer, false, &tgt_desc);
surface->systemColorBuffer = UnityCreateDummySurface(surface->systemColorBuffer, true, &sys_desc);
surface->systemDepthBuffer = UnityCreateDummySurface(surface->systemDepthBuffer, false, &sys_desc);
}
extern "C" void DestroyUnityRenderBuffersNULL(UnityDisplaySurfaceBase* surface)
{
UnityDestroyExternalSurface(surface->unityColorBuffer);
UnityDestroyExternalSurface(surface->systemColorBuffer);
surface->unityColorBuffer = surface->systemColorBuffer = 0;
UnityDestroyExternalSurface(surface->unityDepthBuffer);
UnityDestroyExternalSurface(surface->systemDepthBuffer);
surface->unityDepthBuffer = surface->systemDepthBuffer = 0;
}
extern "C" void InitRenderingNULL() {}
extern "C" void CreateSystemRenderingSurfaceNULL(UnityDisplaySurfaceBase* surface) {}
extern "C" void CreateRenderingSurfaceNULL(UnityDisplaySurfaceBase* surface) {}
extern "C" void DestroyRenderingSurfaceNULL(UnityDisplaySurfaceBase* surface) {}
extern "C" void CreateSharedDepthbufferNULL(UnityDisplaySurfaceBase* surface) {}
extern "C" void DestroySharedDepthbufferNULL(UnityDisplaySurfaceBase* surface) {}
extern "C" void DestroySystemRenderingSurfaceNULL(UnityDisplaySurfaceBase* surface) {}
extern "C" void StartFrameRenderingNULL(UnityDisplaySurfaceBase* surface) {}
extern "C" void EndFrameRenderingNULL(UnityDisplaySurfaceBase* surface) {}
extern "C" void PreparePresentNULL(UnityDisplaySurfaceBase* surface) {}
extern "C" void PresentNULL(UnityDisplaySurfaceBase* surface) {}

View File

@ -0,0 +1,35 @@
#pragma once
#include <objc/objc.h>
#include <objc/runtime.h>
#include <objc/message.h>
// simulator and device differ in how they want objc_msgSendXXX to be called:
// device wants objc_msgSendXXX to be casted to proper type (same as selector we want to call)
// while simulator wants to call them directly
#if TARGET_IPHONE_SIMULATOR || TARGET_TVOS_SIMULATOR
#define UNITY_OBJC_SEND_MSG(selectorType, msgSendFunc) msgSendFunc
#else
#define UNITY_OBJC_SEND_MSG(selectorType, msgSendFunc) ((selectorType)msgSendFunc)
#endif
#define UNITY_OBJC_FORWARD_TO_SUPER(self_, super_, selector, selectorType, ...) \
do { \
struct objc_super super = { .receiver = self_, .super_class = super_ }; \
UNITY_OBJC_SEND_MSG(selectorType, objc_msgSendSuper)(&super, selector, __VA_ARGS__); \
} while(0)
#define UNITY_OBJC_CALL_ON_SELF(self_, selector, selectorType, ...) \
do { \
UNITY_OBJC_SEND_MSG(selectorType, objc_msgSend)(self_, selector, __VA_ARGS__); \
} while(0)
// method type encoding for methods we override
// to get this you need to do: method_getTypeEncoding(class_getInstanceMethod(class, sel)) or method_getTypeEncoding(class_getClassMethod(class, sel))
#define UIView_LayerClass_Enc "#8@0:4"
#define UIViewController_supportedInterfaceOrientations_Enc "Q16@0:8"
#define UIViewController_prefersStatusBarHidden_Enc "B16@0:8"
#define UIScreen_maximumFramesPerSecond_Enc "q16@0:8"
#define UIView_safeAreaInsets_Enc "{UIEdgeInsets=dddd}16@0:8"

View File

@ -0,0 +1,106 @@
#import "Foundation/Foundation.h"
#if ENABLE_IOS_ON_DEMAND_RESOURCES
#import "Foundation/NSBundle.h"
#endif
typedef void (*OnDemandResourcesRequestCompleteHandler)(void* handlerData, const char* error);
#if ENABLE_IOS_ON_DEMAND_RESOURCES
struct OnDemandResourcesRequestData
{
NSBundleResourceRequest* request;
};
extern "C" OnDemandResourcesRequestData* UnityOnDemandResourcesCreateRequest(NSSet * tags, OnDemandResourcesRequestCompleteHandler handler, void* handlerData)
{
OnDemandResourcesRequestData* data = new OnDemandResourcesRequestData();
data->request = [[NSBundleResourceRequest alloc] initWithTags: tags];
[data->request beginAccessingResourcesWithCompletionHandler:^(NSError* error) {
dispatch_async(dispatch_get_main_queue(), ^{
const char* errorMessage = error ? [[error localizedDescription] UTF8String] : NULL;
handler(handlerData, errorMessage);
});
}];
return data;
}
extern "C" void UnityOnDemandResourcesRelease(OnDemandResourcesRequestData* data)
{
[data->request endAccessingResources];
delete data;
}
extern "C" float UnityOnDemandResourcesGetProgress(OnDemandResourcesRequestData* data)
{
return data->request.progress.fractionCompleted;
}
extern "C" float UnityOnDemandResourcesGetLoadingPriority(OnDemandResourcesRequestData* data)
{
float priority = (float)data->request.loadingPriority;
return priority;
}
extern "C" void UnityOnDemandResourcesSetLoadingPriority(OnDemandResourcesRequestData* data, float priority)
{
if (priority < 0.0f)
priority = 0.0f;
if (priority > 1.0f)
data->request.loadingPriority = NSBundleResourceRequestLoadingPriorityUrgent;
else
data->request.loadingPriority = (double)priority;
}
extern "C" NSString* UnityOnDemandResourcesGetResourcePath(OnDemandResourcesRequestData * data, const char* resource)
{
NSString* path = [[data->request bundle] pathForResource: [NSString stringWithUTF8String: resource] ofType: nil];
return path;
}
#else // ENABLE_IOS_ON_DEMAND_RESOURCES
struct OnDemandResourcesRequestData
{
};
extern "C" OnDemandResourcesRequestData* UnityOnDemandResourcesCreateRequest(NSSet * tags, OnDemandResourcesRequestCompleteHandler handler, void* handlerData)
{
OnDemandResourcesRequestData* data = new OnDemandResourcesRequestData();
if (handler)
handler(handlerData, NULL);
return data;
}
extern "C" void UnityOnDemandResourcesRelease(OnDemandResourcesRequestData* data)
{
delete data;
}
extern "C" float UnityOnDemandResourcesGetProgress(OnDemandResourcesRequestData* data)
{
return 1.0f;
}
extern "C" float UnityOnDemandResourcesGetLoadingPriority(OnDemandResourcesRequestData* data)
{
return 0.5;
}
extern "C" void UnityOnDemandResourcesSetLoadingPriority(OnDemandResourcesRequestData* data, float priority)
{
}
extern "C" NSString* UnityOnDemandResourcesGetResourcePath(OnDemandResourcesRequestData * data, const char* resource)
{
return [NSString stringWithUTF8String: resource];
}
#endif // ENABLE_IOS_ON_DEMAND_RESOURCES

View File

@ -0,0 +1,144 @@
#pragma once
#include <stdint.h>
#include "UnitySharedDecls.h"
#ifdef __OBJC__
@class UIScreen;
@class UIWindow;
@class UIView;
@class UIViewController;
@class UIEvent;
@class NSString;
@class NSDictionary;
@class NSArray;
@class NSSet;
@class NSData;
@class NSError;
@class NSBundle;
@class UIKeyCommand;
@class UITouch;
@class UnityView;
@class UnityViewControllerBase;
#else
typedef struct objc_object UIScreen;
typedef struct objc_object UIWindow;
typedef struct objc_object UIView;
typedef struct objc_object UIViewController;
typedef struct objc_object UIEvent;
typedef struct objc_object NSString;
typedef struct objc_object NSDictionary;
typedef struct objc_object NSArray;
typedef struct objc_object NSSet;
typedef struct objc_object NSError;
typedef struct objc_object NSData;
typedef struct objc_object NSBundle;
typedef struct objc_object UIKeyCommand;
typedef struct objc_object UITouch;
typedef struct objc_object UnityViewControllerBase;
typedef struct objc_object UnityView;
#endif
// unity internal audio effect definition struct
struct UnityAudioEffectDefinition;
// new unity rendering api
struct IUnityInterfaces;
// be aware that this struct is shared with unity implementation so you should absolutely not change it
struct UnityFrameStats
{
uint64_t fixedBehaviourManagerDt;
uint64_t fixedPhysicsManagerDt;
uint64_t dynamicBehaviourManagerDt;
uint64_t coroutineDt;
uint64_t skinMeshUpdateDt;
uint64_t animationUpdateDt;
uint64_t renderDt;
uint64_t cullingDt;
uint64_t clearDt;
int fixedUpdateCount;
int batchCount;
uint64_t drawCallTime;
int drawCallCount;
int triCount;
int vertCount;
uint64_t dynamicBatchDt;
int dynamicBatchCount;
int dynamicBatchedDrawCallCount;
int dynamicBatchedTris;
int dynamicBatchedVerts;
int staticBatchCount;
int staticBatchedDrawCallCount;
int staticBatchedTris;
int staticBatchedVerts;
};
// be aware that this enum is shared with unity implementation so you should absolutely not change it
typedef enum
LogType
{
logError = 0,
logAssert = 1,
logWarning = 2,
logLog = 3,
logException = 4,
logDebug = 5,
}
LogType;
// this dictates touches processing on os level: should we transform touches to unity view coords or not.
// N.B. touch.position will always be adjusted to current resolution
// i.e. if you touch right border of view, touch.position.x will be Screen.width, not view.width
// to get coords in view space (os-coords), use touch.rawPosition
typedef enum ViewTouchProcessing
{
// the touches originated from view will be ignored by unity
touchesIgnored = 0,
// touches would be processed as if they were originated in unity view:
// coords will be transformed from view coords to unity view coords
touchesTransformedToUnityViewCoords = 1,
// touches coords will be kept intact (in originated view coords)
// it is default value
touchesKeptInOriginalViewCoords = 2,
}
ViewTouchProcessing;
// be aware that this enum is shared with unity implementation so you should absolutely not change it
typedef enum KeyboardStatus
{
Visible = 0,
Done = 1,
Canceled = 2,
LostFocus = 3,
}
KeyboardStatus;
// misc
#ifdef __cplusplus
extern "C" {
bool UnityiOS81orNewer();
bool UnityiOS82orNewer();
bool UnityiOS90orNewer();
bool UnityiOS91orNewer();
bool UnityiOS100orNewer();
bool UnityiOS101orNewer();
bool UnityiOS102orNewer();
bool UnityiOS103orNewer();
bool UnityiOS110orNewer();
bool UnityiOS111orNewer();
bool UnityiOS112orNewer();
bool UnityiOS130orNewer();
bool UnityiOS140orNewer();
bool UnityiOS150orNewer();
bool UnityiOS160orNewer();
}
#endif

View File

@ -0,0 +1,420 @@
#pragma once
#include <stdint.h>
#include <stdarg.h>
#include "UnityForwardDecls.h"
#include "UnityRendering.h"
#ifdef __OBJC__
#import "Foundation/Foundation.h"
#endif
// unity plugin functions
// audio plugin api
typedef int (*UnityPluginGetAudioEffectDefinitionsFunc)(struct UnityAudioEffectDefinition*** descptr);
// OLD rendering plugin api (will become obsolete soon)
typedef void (*UnityPluginSetGraphicsDeviceFunc)(void* device, int deviceType, int eventType);
typedef void (*UnityPluginRenderMarkerFunc)(int marker);
// new rendering plugin api
typedef void (*UnityPluginLoadFunc)(struct IUnityInterfaces* unityInterfaces);
typedef void (*UnityPluginUnloadFunc)(void);
// log handler function
#ifdef __cplusplus
typedef bool (*LogEntryHandler)(LogType logType, const char* log, va_list list);
#endif
//
// these are functions referenced in trampoline and implemented in unity player lib
//
#ifdef __cplusplus
extern "C" {
#endif
// life cycle management
void UnityInitRuntime(int argc, char* argv[]);
void UnityInitApplicationNoGraphics(const char* appPathName);
void UnityUnloadApplication(void);
void UnityQuitApplication(int exitCode);
void UnityInitApplicationGraphics(void);
void UnityCleanup(void);
void UnityLoadApplication(void);
void UnityLoadApplicationFromSceneLessState(void);
void UnityPlayerLoop(void); // normal player loop
void UnityBatchPlayerLoop(void); // batch mode like player loop, without rendering (usable for background processing)
void UnitySetPlayerFocus(int focused); // send OnApplicationFocus() message to scripts
void UnityLowMemory(void);
void UnityPause(int pause);
void UnitySuppressPauseMessage(void);
int UnityIsPaused(void); // 0 if player is running, 1 if paused
void UnityWillPause(void); // send the message that app will pause
void UnityWillResume(void); // send the message that app will resume
void UnityDeliverUIEvents(void); // unity processing impacting UI will be called in there
void UnityWaitForFrame();
void UnityInputProcess(void); // no longer used, will be removed soon
// rendering
int UnityGetRenderingAPI(void);
void UnityFinishRendering(void);
void UnityDisplayLinkCallback(double /*machAbsoluteTimeSeconds*/); // argument is not used anymore
// controling player internals
// TODO: needs some cleanup
void UnitySetAudioSessionActive(int active);
void UnityGLInvalidateState(void);
void UnityReloadResources(void);
int UnityIsCaptureScreenshotRequested(void);
void UnityCaptureScreenshot(void);
void UnitySendMessage(const char* obj, const char* method, const char* msg);
void UnityUpdateMuteState(int mute);
void UnityUpdateAudioOutputState(void);
int UnityShouldMuteOtherAudioSources(void);
int UnityShouldPrepareForIOSRecording(void);
int UnityIsAudioManagerAvailableAndEnabled(void);
#ifdef __cplusplus
void UnitySetLogEntryHandler(LogEntryHandler newHandler);
#endif
// plugins support
// WARNING: old UnityRegisterRenderingPlugin will become obsolete soon
void UnityRegisterRenderingPlugin(UnityPluginSetGraphicsDeviceFunc setDevice, UnityPluginRenderMarkerFunc renderMarker);
void UnityRegisterRenderingPluginV5(UnityPluginLoadFunc loadPlugin, UnityPluginUnloadFunc unloadPlugin);
void UnityRegisterAudioPlugin(UnityPluginGetAudioEffectDefinitionsFunc getAudioEffectDefinitions);
// resolution/orientation handling
void UnityGetRenderingResolution(unsigned* w, unsigned* h);
void UnityGetSystemResolution(unsigned* w, unsigned* h);
void UnityRequestRenderingResolution(unsigned w, unsigned h);
int UnityIsOrientationEnabled(unsigned /*ScreenOrientation*/ orientation);
int UnityHasOrientationRequest(void);
int UnityShouldAutorotate(void);
int UnityAutorotationStatusChanged(void);
int UnityShouldChangeAllowedOrientations(void);
int UnityRequestedScreenOrientation(void); // returns ScreenOrientation
void UnityOrientationRequestWasCommitted(void);
int UnityReportResizeView(unsigned w, unsigned h, unsigned /*ScreenOrientation*/ contentOrientation); // returns ScreenOrientation
void UnityReportSafeAreaChange(float x, float y, float w, float h);
void UnityReportBackbufferChange(UnityRenderBufferHandle colorBB, UnityRenderBufferHandle depthBB);
#if !PLATFORM_VISIONOS
float UnityCalculateScalingFactorFromTargetDPI(UIScreen* screen);
#endif
void UnityReportDisplayCutouts(const float* x, const float* y, const float* width, const float* height, int count);
// player settings
int UnityDisableDepthAndStencilBuffers(void);
int UnityUseAnimatedAutorotation(void);
int UnityGetDesiredMSAASampleCount(int defaultSampleCount);
int UnityGetSRGBRequested(void);
int UnityGetWideColorRequested(void);
int UnityGetHDRModeRequested(void);
int UnityGetShowActivityIndicatorOnLoading(void);
int UnityGetAccelerometerFrequency(void);
int UnityGetTargetFPS(void);
int UnityGetUseCustomAppBackgroundBehavior(void);
int UnityGetDeferSystemGesturesTopEdge(void);
int UnityGetDeferSystemGesturesBottomEdge(void);
int UnityGetDeferSystemGesturesLeftEdge(void);
int UnityGetDeferSystemGesturesRightEdge(void);
int UnityGetHideHomeButton(void);
int UnityMetalFramebufferOnly(void);
int UnityMetalMemorylessDepth(void);
int UnityPreserveFramebufferAlpha(void);
void UnitySetTargetFPS(int targetFPS);
void UnitySetAbsoluteURL(const char* url);
// native events
void UnityInvalidateDisplayDataCache(void* screen);
void UnityUpdateDisplayListCache(void** screens, int screenCount);
// profiler
void* UnityCreateProfilerCounter(const char*);
void UnityDestroyProfilerCounter(void*);
void UnityStartProfilerCounter(void*);
void UnityEndProfilerCounter(void*);
// sensors
void UnitySensorsSetGyroRotationRate(int idx, float x, float y, float z);
void UnitySensorsSetGyroRotationRateUnbiased(int idx, float x, float y, float z);
void UnitySensorsSetGravity(int idx, float x, float y, float z);
void UnitySensorsSetUserAcceleration(int idx, float x, float y, float z);
void UnitySensorsSetAttitude(int idx, float x, float y, float z, float w);
void UnityDidAccelerate(float x