Application.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. //
  2. // Support for bubbling up to C# the virtual methods calls for Setup, Start and Stop in Application
  3. //
  4. // This is done by using an ApplicationProxy in C++ that bubbles up
  5. //
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Runtime.InteropServices;
  12. using System.Threading.Tasks;
  13. using Urho.IO;
  14. using Urho.Audio;
  15. using Urho.Resources;
  16. using Urho.Actions;
  17. using Urho.Gui;
  18. namespace Urho {
  19. public partial class Application {
  20. // references needed to prevent GC from collecting callbacks passed to native code
  21. static ActionIntPtr setupCallback;
  22. static ActionIntPtr startCallback;
  23. static ActionIntPtr stopCallback;
  24. static TaskCompletionSource<bool> exitTask;
  25. static int renderThreadId = -1;
  26. static readonly List<Action> actionsToDipatch = new List<Action>();
  27. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  28. public delegate void ActionIntPtr (IntPtr value);
  29. [DllImport (Consts.NativeImport, CallingConvention=CallingConvention.Cdecl)]
  30. static extern IntPtr ApplicationProxy_ApplicationProxy (IntPtr contextHandle, ActionIntPtr setup, ActionIntPtr start, ActionIntPtr stop, string args, IntPtr externalWindow);
  31. static Application current;
  32. public static Application Current
  33. {
  34. get
  35. {
  36. if (current == null)
  37. throw new InvalidOperationException("The application is not configured yet");
  38. return current;
  39. }
  40. private set { current = value; }
  41. }
  42. public static bool HasCurrent => current != null;
  43. static Context currentContext;
  44. public static Context CurrentContext
  45. {
  46. get
  47. {
  48. if (currentContext == null)
  49. throw new InvalidOperationException("The application is not configured yet");
  50. return currentContext;
  51. }
  52. private set { currentContext = value; }
  53. }
  54. public Application() : this(new Context(), null) {}
  55. public Application(ApplicationOptions options) : this(new Context(), options) {}
  56. /// <summary>
  57. /// Supports the simple style with callbacks
  58. /// </summary>
  59. Application (Context context, ApplicationOptions options = null) : base (UrhoObjectFlag.Empty)
  60. {
  61. if (context == null)
  62. throw new ArgumentNullException (nameof(context));
  63. if (context.Refs() < 1)
  64. context.AddRef();
  65. //keep references to callbacks (supposed to be passed to native code) as long as the App is alive
  66. setupCallback = ProxySetup;
  67. startCallback = ProxyStart;
  68. stopCallback = ProxyStop;
  69. Options = options ?? new ApplicationOptions(assetsFolder: null);
  70. handle = ApplicationProxy_ApplicationProxy (context.Handle, setupCallback, startCallback, stopCallback, Options.ToString(), Options.ExternalWindow);
  71. Runtime.RegisterObject (this);
  72. }
  73. public bool IsClosed { get; private set; }
  74. public IntPtr Handle => handle;
  75. public IUrhoSurface UrhoSurface { get; internal set; }
  76. /// <summary>
  77. /// Application options
  78. /// </summary>
  79. public ApplicationOptions Options { get; private set; }
  80. /// <summary>
  81. /// Frame update event
  82. /// </summary>
  83. public event Action<UpdateEventArgs> Update;
  84. /// <summary>
  85. /// Invoke actions in the Main Thread (the next Update call)
  86. /// </summary>
  87. public static void InvokeOnMain(Action action)
  88. {
  89. lock (actionsToDipatch)
  90. {
  91. actionsToDipatch.Add(action);
  92. }
  93. }
  94. /// <summary>
  95. /// Invoke actions in the Main Thread (the next Update call)
  96. /// </summary>
  97. public static Task InvokeOnMainAsync(Action action)
  98. {
  99. var tcs = new TaskCompletionSource<bool>();
  100. InvokeOnMain(() =>
  101. {
  102. action();
  103. tcs.TrySetResult(true);
  104. });
  105. return tcs.Task;
  106. }
  107. static Application GetApp(IntPtr h) => Runtime.LookupObject<Application>(h);
  108. void HandleUpdate(UpdateEventArgs args)
  109. {
  110. var timeStep = args.TimeStep;
  111. Update?.Invoke(args);
  112. ActionManager.Update(timeStep);
  113. OnUpdate(timeStep);
  114. if (actionsToDipatch.Count > 0)
  115. {
  116. lock (actionsToDipatch)
  117. {
  118. foreach (var action in actionsToDipatch)
  119. action();
  120. actionsToDipatch.Clear();
  121. }
  122. }
  123. }
  124. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  125. static void ProxySetup (IntPtr h)
  126. {
  127. Runtime.Setup();
  128. Current = GetApp(h);
  129. CurrentContext = Current.Context;
  130. Current.Setup ();
  131. }
  132. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  133. static void ProxyStart (IntPtr h)
  134. {
  135. Runtime.Start();
  136. Current = GetApp(h);
  137. Current.SubscribeToAppEvents();
  138. Current.Start();
  139. Started?.Invoke();
  140. #if ANDROID
  141. renderThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId;
  142. #endif
  143. }
  144. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  145. static void ProxyStop (IntPtr h)
  146. {
  147. LogSharp.Debug("ProxyStop");
  148. UrhoPlatformInitializer.Initialized = false;
  149. var context = Current.Context;
  150. var app = GetApp (h);
  151. app.IsClosed = true;
  152. app.UnsubscribeFromAppEvents();
  153. app.Stop ();
  154. LogSharp.Debug("ProxyStop: Runtime.Cleanup");
  155. Runtime.Cleanup();
  156. LogSharp.Debug("ProxyStop: Releasing context");
  157. #if ANDROID
  158. if (context.Refs() > 0)
  159. context.ReleaseRef();
  160. #endif
  161. LogSharp.Debug("ProxyStop: Disposing context");
  162. context.Dispose();
  163. Current = null;
  164. Stoped?.Invoke();
  165. LogSharp.Debug("ProxyStop: end");
  166. exitTask?.TrySetResult(true);
  167. }
  168. Subscription updateSubscription = null;
  169. void SubscribeToAppEvents()
  170. {
  171. updateSubscription = Engine.SubscribeToUpdate(HandleUpdate);
  172. }
  173. void UnsubscribeFromAppEvents()
  174. {
  175. updateSubscription?.Unsubscribe();
  176. }
  177. internal static async Task StopCurrent()
  178. {
  179. if (current == null)
  180. return;
  181. #if WINDOWS_UWP
  182. UWP.UrhoSurface.StopRendering().Wait();
  183. #endif
  184. #if ANDROID
  185. if (Current.UrhoSurface?.IsAlive == false)
  186. {
  187. Current.Engine.Exit();
  188. }
  189. else if (System.Threading.Thread.CurrentThread.ManagedThreadId != renderThreadId)
  190. {
  191. exitTask = new TaskCompletionSource<bool>();
  192. InvokeOnMainAsync(() => Current.Engine.Exit()).Wait();
  193. Current.UrhoSurface?.Remove();
  194. Current.UrhoSurface = null;
  195. await exitTask.Task;//.Wait();
  196. }
  197. else
  198. {
  199. Current.Engine.Exit();
  200. new Android.OS.Handler(Android.OS.Looper.MainLooper).PostAtFrontOfQueue(() => {
  201. Current.UrhoSurface?.Remove();
  202. Current.UrhoSurface = null;
  203. });
  204. }
  205. #else
  206. Current.Engine.Exit ();
  207. #endif
  208. #if IOS || WINDOWS_UWP
  209. ProxyStop(Current.Handle);
  210. #endif
  211. }
  212. public bool IsExiting => Runtime.IsClosing || Engine.Exiting;
  213. public Task Exit()
  214. {
  215. if (IsClosed)
  216. return Task.FromResult<object>(null);
  217. IsClosed = true;
  218. return StopCurrent();
  219. }
  220. protected override bool AllowNativeDelete => false;
  221. protected virtual void Setup () {}
  222. public static event Action Started;
  223. protected virtual void Start () {}
  224. public static event Action Stoped;
  225. protected virtual void Stop () {}
  226. protected virtual void OnUpdate(float timeStep) { }
  227. internal ActionManager ActionManager { get; } = new ActionManager();
  228. [DllImport(Consts.NativeImport, EntryPoint = "Urho_GetPlatform", CallingConvention = CallingConvention.Cdecl)]
  229. static extern IntPtr GetPlatform();
  230. static Platforms platform;
  231. public static Platforms Platform {
  232. get
  233. {
  234. Runtime.Validate(typeof(Application));
  235. if (platform == Platforms.Unknown)
  236. platform = PlatformsMap.FromString(Marshal.PtrToStringAnsi(GetPlatform()));
  237. return platform;
  238. }
  239. }
  240. //
  241. // GetSubsystem helpers
  242. //
  243. ResourceCache resourceCache;
  244. public ResourceCache ResourceCache {
  245. get
  246. {
  247. Runtime.Validate(typeof(Application));
  248. if (resourceCache == null)
  249. resourceCache = new ResourceCache (UrhoObject_GetSubsystem (handle, ResourceCache.TypeStatic.Code));
  250. return resourceCache;
  251. }
  252. }
  253. UrhoConsole console;
  254. public UrhoConsole Console {
  255. get
  256. {
  257. Runtime.Validate(typeof(Application));
  258. if (console == null)
  259. console = new UrhoConsole (UrhoObject_GetSubsystem (handle, UrhoConsole.TypeStatic.Code));
  260. return console;
  261. }
  262. }
  263. Urho.Network.Network network;
  264. public Urho.Network.Network Network {
  265. get
  266. {
  267. Runtime.Validate(typeof(Application));
  268. if (network == null)
  269. network = new Urho.Network.Network (UrhoObject_GetSubsystem (handle, Urho.Network.Network.TypeStatic.Code));
  270. return network;
  271. }
  272. }
  273. Time time;
  274. public Time Time {
  275. get
  276. {
  277. Runtime.Validate(typeof(Application));
  278. if (time == null)
  279. time = new Time (UrhoObject_GetSubsystem (handle, Time.TypeStatic.Code));
  280. return time;
  281. }
  282. }
  283. WorkQueue workQueue;
  284. public WorkQueue WorkQueue {
  285. get
  286. {
  287. Runtime.Validate(typeof(Application));
  288. if (workQueue == null)
  289. workQueue = new WorkQueue (UrhoObject_GetSubsystem (handle, WorkQueue.TypeStatic.Code));
  290. return workQueue;
  291. }
  292. }
  293. Profiler profiler;
  294. public Profiler Profiler {
  295. get
  296. {
  297. Runtime.Validate(typeof(Application));
  298. if (profiler == null)
  299. profiler = new Profiler (UrhoObject_GetSubsystem (handle, Profiler.TypeStatic.Code));
  300. return profiler;
  301. }
  302. }
  303. FileSystem fileSystem;
  304. public FileSystem FileSystem {
  305. get
  306. {
  307. Runtime.Validate(typeof(Application));
  308. if (fileSystem == null)
  309. fileSystem = new FileSystem (UrhoObject_GetSubsystem (handle, FileSystem.TypeStatic.Code));
  310. return fileSystem;
  311. }
  312. }
  313. Log log;
  314. public Log Log {
  315. get
  316. {
  317. Runtime.Validate(typeof(Application));
  318. if (log == null)
  319. log = new Log (UrhoObject_GetSubsystem (handle, Log.TypeStatic.Code));
  320. return log;
  321. }
  322. }
  323. Input input;
  324. public Input Input {
  325. get
  326. {
  327. Runtime.Validate(typeof(Application));
  328. if (input == null)
  329. input = new Input (UrhoObject_GetSubsystem (handle, Input.TypeStatic.Code));
  330. return input;
  331. }
  332. }
  333. Urho.Audio.Audio audio;
  334. public Urho.Audio.Audio Audio {
  335. get
  336. {
  337. Runtime.Validate(typeof(Application));
  338. if (audio == null)
  339. audio = new Audio.Audio (UrhoObject_GetSubsystem (handle, Urho.Audio.Audio.TypeStatic.Code));
  340. return audio;
  341. }
  342. }
  343. UI uI;
  344. public UI UI {
  345. get
  346. {
  347. Runtime.Validate(typeof(Application));
  348. if (uI == null)
  349. uI = new UI (UrhoObject_GetSubsystem (handle, UI.TypeStatic.Code));
  350. return uI;
  351. }
  352. }
  353. Graphics graphics;
  354. public Graphics Graphics {
  355. get
  356. {
  357. Runtime.Validate(typeof(Application));
  358. if (graphics == null)
  359. graphics = new Graphics (UrhoObject_GetSubsystem (handle, Graphics.TypeStatic.Code));
  360. return graphics;
  361. }
  362. }
  363. Renderer renderer;
  364. public Renderer Renderer {
  365. get
  366. {
  367. Runtime.Validate(typeof(Application));
  368. if (renderer == null)
  369. renderer = new Renderer (UrhoObject_GetSubsystem (handle, Renderer.TypeStatic.Code));
  370. return renderer;
  371. }
  372. }
  373. [DllImport (Consts.NativeImport, CallingConvention=CallingConvention.Cdecl)]
  374. extern static IntPtr Application_GetEngine (IntPtr handle);
  375. Engine engine;
  376. public Engine Engine {
  377. get
  378. {
  379. if (engine == null)
  380. engine = new Engine (Application_GetEngine (handle));
  381. return engine;
  382. }
  383. }
  384. public static T CreateInstance<T>(ApplicationOptions options = null) where T : Application
  385. {
  386. return (T)CreateInstance(typeof (T), options);
  387. }
  388. public static Application CreateInstance(Type applicationType, ApplicationOptions options = null)
  389. {
  390. var ctors = applicationType.GetTypeInfo().DeclaredConstructors.ToArray();
  391. var ctorWithOptions = ctors.FirstOrDefault(c => c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == typeof (ApplicationOptions));
  392. if (ctorWithOptions != null)
  393. {
  394. return (Application) Activator.CreateInstance(applicationType, options);
  395. }
  396. var ctorDefault = ctors.FirstOrDefault(c => c.GetParameters().Length == 0);
  397. if (ctorDefault != null)
  398. {
  399. return (Application) Activator.CreateInstance(applicationType);
  400. }
  401. throw new InvalidOperationException($"{applicationType} doesn't have parameterless constructor.");
  402. }
  403. }
  404. public interface IUrhoSurface
  405. {
  406. void Remove();
  407. bool IsAlive { get; }
  408. }
  409. }