Application.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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.Linq;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Threading.Tasks;
  12. using Urho.IO;
  13. using Urho.Audio;
  14. using Urho.Resources;
  15. using Urho.Actions;
  16. using Urho.Gui;
  17. namespace Urho {
  18. public partial class Application {
  19. // references needed to prevent GC from collecting callbacks passed to native code
  20. static ActionIntPtr setupCallback;
  21. static ActionIntPtr startCallback;
  22. static ActionIntPtr stopCallback;
  23. static readonly List<Action> actionsToDipatch = new List<Action>();
  24. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  25. public delegate void ActionIntPtr (IntPtr value);
  26. [DllImport (Consts.NativeImport, CallingConvention=CallingConvention.Cdecl)]
  27. static extern IntPtr ApplicationProxy_ApplicationProxy (IntPtr contextHandle, ActionIntPtr setup, ActionIntPtr start, ActionIntPtr stop, string args, IntPtr externalWindow);
  28. static Application current;
  29. public static Application Current
  30. {
  31. get
  32. {
  33. if (current == null)
  34. throw new InvalidOperationException("The application is not configured yet");
  35. return current;
  36. }
  37. private set { current = value; }
  38. }
  39. static Context currentContext;
  40. public static Context CurrentContext
  41. {
  42. get
  43. {
  44. if (currentContext == null)
  45. throw new InvalidOperationException("The application is not configured yet");
  46. return currentContext;
  47. }
  48. private set { currentContext = value; }
  49. }
  50. /// <summary>
  51. /// Call UrhoEngine.Init() to initialize the engine
  52. /// </summary>
  53. public static bool EngineInited { get; set; }
  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. Engine.SubscribeToUpdate(HandleUpdate);
  73. }
  74. /// <summary>
  75. /// Application options
  76. /// </summary>
  77. public ApplicationOptions Options { get; private set; }
  78. /// <summary>
  79. /// Frame update event
  80. /// </summary>
  81. public event Action<UpdateEventArgs> Update;
  82. /// <summary>
  83. /// Waits given _game_ time.
  84. /// </summary>
  85. public static Task Delay(float durationSec)
  86. {
  87. var tcs = new TaskCompletionSource<bool>();
  88. var state = Current.ActionManager.AddAction(new Sequence(new DelayTime(durationSec), new CallFunc(() => tcs.TrySetResult(true))), null);
  89. return tcs.Task;
  90. }
  91. /// <summary>
  92. /// Invoke actions in the Main Thread (the next Update call)
  93. /// </summary>
  94. public static void InvokeOnMain(Action action)
  95. {
  96. lock (actionsToDipatch)
  97. {
  98. actionsToDipatch.Add(action);
  99. }
  100. }
  101. static Application GetApp(IntPtr h) => Runtime.LookupObject<Application>(h);
  102. void HandleUpdate(UpdateEventArgs args)
  103. {
  104. var timeStep = args.TimeStep;
  105. Update?.Invoke(args);
  106. ActionManager.Update(timeStep);
  107. OnUpdate(timeStep);
  108. if (actionsToDipatch.Count > 0)
  109. {
  110. lock (actionsToDipatch)
  111. {
  112. foreach (var action in actionsToDipatch)
  113. action();
  114. actionsToDipatch.Clear();
  115. }
  116. }
  117. }
  118. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  119. static void ProxySetup (IntPtr h)
  120. {
  121. Current = GetApp(h);
  122. CurrentContext = Current.Context;
  123. Current.Setup ();
  124. }
  125. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  126. static void ProxyStart (IntPtr h)
  127. {
  128. Runtime.Initialize();
  129. if (!EngineInited)
  130. {
  131. throw new InvalidOperationException("Urho is not initialized. Please, call UrhoEngine.Init() before app.Run().");
  132. }
  133. GetApp (h).Start ();
  134. }
  135. [MonoPInvokeCallback(typeof(ActionIntPtr))]
  136. static void ProxyStop (IntPtr h)
  137. {
  138. var context = Current.Context;
  139. GetApp (h).Stop ();
  140. Runtime.Cleanup();
  141. if (context.Refs() > 0)
  142. context.ReleaseRef();
  143. context.Dispose();
  144. Current = null;
  145. }
  146. protected virtual void Setup () {}
  147. protected virtual void Start () {}
  148. protected virtual void Stop () {}
  149. protected virtual void OnUpdate(float timeStep) { }
  150. internal ActionManager ActionManager { get; } = new ActionManager();
  151. [DllImport(Consts.NativeImport, EntryPoint = "Urho_GetPlatform", CallingConvention = CallingConvention.Cdecl)]
  152. static extern IntPtr GetPlatform();
  153. static Platforms platform;
  154. public static Platforms Platform {
  155. get {
  156. if (platform == Platforms.Unknown)
  157. platform = PlatformsMap.FromString(Marshal.PtrToStringAnsi(GetPlatform()));
  158. return platform;
  159. }
  160. }
  161. //
  162. // GetSubsystem helpers
  163. //
  164. ResourceCache resourceCache;
  165. public ResourceCache ResourceCache {
  166. get {
  167. if (resourceCache == null)
  168. resourceCache = new ResourceCache (UrhoObject_GetSubsystem (handle, ResourceCache.TypeStatic.Code));
  169. return resourceCache;
  170. }
  171. }
  172. UrhoConsole console;
  173. public UrhoConsole Console {
  174. get {
  175. if (console == null)
  176. console = new UrhoConsole (UrhoObject_GetSubsystem (handle, UrhoConsole.TypeStatic.Code));
  177. return console;
  178. }
  179. }
  180. Urho.Network.Network network;
  181. public Urho.Network.Network Network {
  182. get {
  183. if (network == null)
  184. network = new Urho.Network.Network (UrhoObject_GetSubsystem (handle, Urho.Network.Network.TypeStatic.Code));
  185. return network;
  186. }
  187. }
  188. Time time;
  189. public Time Time {
  190. get {
  191. if (time == null)
  192. time = new Time (UrhoObject_GetSubsystem (handle, Time.TypeStatic.Code));
  193. return time;
  194. }
  195. }
  196. WorkQueue workQueue;
  197. public WorkQueue WorkQueue {
  198. get {
  199. if (workQueue == null)
  200. workQueue = new WorkQueue (UrhoObject_GetSubsystem (handle, WorkQueue.TypeStatic.Code));
  201. return workQueue;
  202. }
  203. }
  204. Profiler profiler;
  205. public Profiler Profiler {
  206. get {
  207. if (profiler == null)
  208. profiler = new Profiler (UrhoObject_GetSubsystem (handle, Profiler.TypeStatic.Code));
  209. return profiler;
  210. }
  211. }
  212. FileSystem fileSystem;
  213. public FileSystem FileSystem {
  214. get {
  215. if (fileSystem == null)
  216. fileSystem = new FileSystem (UrhoObject_GetSubsystem (handle, FileSystem.TypeStatic.Code));
  217. return fileSystem;
  218. }
  219. }
  220. Log log;
  221. public Log Log {
  222. get {
  223. if (log == null)
  224. log = new Log (UrhoObject_GetSubsystem (handle, Log.TypeStatic.Code));
  225. return log;
  226. }
  227. }
  228. Input input;
  229. public Input Input {
  230. get {
  231. if (input == null)
  232. input = new Input (UrhoObject_GetSubsystem (handle, Input.TypeStatic.Code));
  233. return input;
  234. }
  235. }
  236. Urho.Audio.Audio audio;
  237. public Urho.Audio.Audio Audio {
  238. get {
  239. if (audio == null)
  240. audio = new Audio.Audio (UrhoObject_GetSubsystem (handle, Urho.Audio.Audio.TypeStatic.Code));
  241. return audio;
  242. }
  243. }
  244. UI uI;
  245. public UI UI {
  246. get {
  247. if (uI == null)
  248. uI = new UI (UrhoObject_GetSubsystem (handle, UI.TypeStatic.Code));
  249. return uI;
  250. }
  251. }
  252. Graphics graphics;
  253. public Graphics Graphics {
  254. get {
  255. if (graphics == null)
  256. graphics = new Graphics (UrhoObject_GetSubsystem (handle, Graphics.TypeStatic.Code));
  257. return graphics;
  258. }
  259. }
  260. Renderer renderer;
  261. public Renderer Renderer {
  262. get {
  263. if (renderer == null)
  264. renderer = new Renderer (UrhoObject_GetSubsystem (handle, Renderer.TypeStatic.Code));
  265. return renderer;
  266. }
  267. }
  268. [DllImport (Consts.NativeImport, CallingConvention=CallingConvention.Cdecl)]
  269. extern static IntPtr Application_GetEngine (IntPtr handle);
  270. Engine engine;
  271. public Engine Engine {
  272. get {
  273. if (engine == null)
  274. engine = new Engine (Application_GetEngine (handle));
  275. return engine;
  276. }
  277. }
  278. public static T CreateInstance<T>(ApplicationOptions options = null) where T : Application
  279. {
  280. return (T)CreateInstance(typeof (T), options);
  281. }
  282. public static Application CreateInstance(Type applicationType, ApplicationOptions options = null)
  283. {
  284. var ctors = applicationType.GetTypeInfo().DeclaredConstructors.ToArray();
  285. var ctorWithOptions = ctors.FirstOrDefault(c => c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == typeof (ApplicationOptions));
  286. if (ctorWithOptions != null)
  287. {
  288. return (Application) Activator.CreateInstance(applicationType, options);
  289. }
  290. var ctorDefault = ctors.FirstOrDefault(c => c.GetParameters().Length == 0);
  291. if (ctorDefault != null)
  292. {
  293. return (Application) Activator.CreateInstance(applicationType);
  294. }
  295. throw new InvalidOperationException($"{applicationType} doesn't have parameterless constructor.");
  296. }
  297. }
  298. }