engineAPI.h 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _ENGINEAPI_H_
  23. #define _ENGINEAPI_H_
  24. #include <tuple>
  25. #include <utility>
  26. #ifndef _CONSOLETYPES_H_
  27. #include "console/consoleTypes.h"
  28. #endif
  29. #ifndef _CONSOLE_H_
  30. #include "console/console.h"
  31. #endif
  32. #ifndef _STRINGFUNCTIONS_H_
  33. #include "core/strings/stringFunctions.h"
  34. #endif
  35. #ifndef _SIMOBJECT_H_
  36. #include "console/simObject.h"
  37. #endif
  38. #ifndef _ENGINEFUNCTIONS_H_
  39. #include "console/engineFunctions.h"
  40. #endif
  41. // Whatever types are used in API definitions, their DECLAREs must be visible to the
  42. // macros. We include the basic primitive and struct types here.
  43. #ifndef _ENGINEPRIMITIVES_H_
  44. #include "console/enginePrimitives.h"
  45. #endif
  46. #ifndef _ENGINESTRUCTS_H_
  47. #include "console/engineStructs.h"
  48. #endif
  49. // Needed for the executef macros. Blame GCC.
  50. #ifndef _SIMEVENTS_H_
  51. #include "console/simEvents.h"
  52. #endif
  53. /// @file
  54. /// Definitions for exposing engine functionality to the control layer.
  55. ///
  56. /// This file provides a convenience layer around the underlying engine interop system (which at
  57. /// the moment still includes the legacy TorqueScript interop a.k.a. "console system"). The
  58. /// macros exposed here will automatically take care of all marshalling, value type constraints,
  59. /// reflection info instancing, etc. involved in defining engine API call-ins and call-outs.
  60. ///
  61. /// @note At the moment, this file supplies both the legacy TorqueScript console system as well
  62. /// as the new engine export system with the structures and information they need. In the
  63. /// near future, the console-based parts will get purged. This will not result in visible
  64. /// changes to users of the functionality here except for the string-based marshalling
  65. /// functions currently exposed (which will also disappear).
  66. //TODO: Disable warning for extern "C" functions returning UDTs for now; need to take a closer look at this
  67. #pragma warning( disable : 4190 )
  68. // Disable some VC warnings that are irrelevant to us.
  69. #pragma warning( push )
  70. #pragma warning( disable : 4510 ) // default constructor could not be generated; all the Args structures are never constructed by us
  71. #pragma warning( disable : 4610 ) // can never be instantiated; again Args is never constructed by us
  72. namespace engineAPI {
  73. /// Flag for enabling legacy console behavior in the interop system while
  74. /// we still have it around. Will disappear along with console.
  75. extern bool gUseConsoleInterop;
  76. /// Flag to allow engine functions to detect whether the engine had been
  77. /// initialized or shut down.
  78. extern bool gIsInitialized;
  79. }
  80. //FIXME: this allows const char* to be used as a struct field type
  81. // Temp support for allowing const char* to remain in the API functions as long as we
  82. // still have the console system around. When that is purged, these definitions should
  83. // be deleted and all const char* uses be replaced with String.
  84. template<> struct EngineTypeTraits< const char* > : public EngineTypeTraits< String > {};
  85. template<> inline const EngineTypeInfo* TYPE< const char* >() { return TYPE< String >(); }
  86. /// @name Marshalling
  87. ///
  88. /// Functions for converting to/from string-based data representations.
  89. ///
  90. /// @note This functionality is specific to the console interop.
  91. /// @{
  92. /// Marshal a single piece of data from native into client form.
  93. template< typename T >
  94. inline const char* EngineMarshallData( const T& value )
  95. {
  96. return castConsoleTypeToString( value );
  97. }
  98. inline const char* EngineMarshallData( bool value )
  99. {
  100. if( value )
  101. return "1";
  102. else
  103. return "0";
  104. }
  105. inline const char* EngineMarshallData( const char* str )
  106. {
  107. // The API assumes that if you pass a plain "const char*" through it, then you are referring
  108. // to string storage with non-local lifetime that can be safely passed to the control layer.
  109. return str;
  110. }
  111. template< typename T >
  112. inline const char* EngineMarshallData( T* object )
  113. {
  114. return ( object ? object->getIdString() : "0" );
  115. }
  116. template< typename T >
  117. inline const char* EngineMarshallData( const T* object )
  118. {
  119. return ( object ? object->getIdString() : "0" );
  120. }
  121. inline const char* EngineMarshallData( U32 value )
  122. {
  123. return EngineMarshallData( S32( value ) );
  124. }
  125. /// Marshal data from native into client form stored directly in
  126. /// client function invocation vector.
  127. template< typename T >
  128. inline void EngineMarshallData( const T& arg, S32& argc, ConsoleValueRef *argv )
  129. {
  130. argv[ argc ] = castConsoleTypeToString( arg );
  131. argc ++;
  132. }
  133. inline void EngineMarshallData( bool arg, S32& argc, ConsoleValueRef *argv )
  134. {
  135. if( arg )
  136. argv[ argc ] = 1;
  137. else
  138. argv[ argc ] = 0;
  139. argc ++;
  140. }
  141. inline void EngineMarshallData( S32 arg, S32& argc, ConsoleValueRef *argv )
  142. {
  143. argv[ argc ] = arg;
  144. argc ++;
  145. }
  146. inline void EngineMarshallData( U32 arg, S32& argc, ConsoleValueRef *argv )
  147. {
  148. EngineMarshallData( S32( arg ), argc, argv );
  149. }
  150. inline void EngineMarshallData( F32 arg, S32& argc, ConsoleValueRef *argv )
  151. {
  152. argv[ argc ] = arg;
  153. argc ++;
  154. }
  155. inline void EngineMarshallData( const char* arg, S32& argc, ConsoleValueRef *argv )
  156. {
  157. argv[ argc ] = arg;
  158. argc ++;
  159. }
  160. inline void EngineMarshallData( char* arg, S32& argc, ConsoleValueRef *argv )
  161. {
  162. argv[ argc ] = arg;
  163. argc ++;
  164. }
  165. template< typename T >
  166. inline void EngineMarshallData( T* object, S32& argc, ConsoleValueRef *argv )
  167. {
  168. argv[ argc ] = object ? object->getId() : 0;
  169. argc ++;
  170. }
  171. template< typename T >
  172. inline void EngineMarshallData( const T* object, S32& argc, ConsoleValueRef *argv )
  173. {
  174. argv[ argc ] = object ? object->getId() : 0;
  175. argc ++;
  176. }
  177. /// Unmarshal data from client form to engine form.
  178. ///
  179. /// This is wrapped in an a struct as partial specializations on function
  180. /// templates are not allowed in C++.
  181. template< typename T >
  182. struct EngineUnmarshallData
  183. {
  184. T operator()( const char* str ) const
  185. {
  186. T value;
  187. castConsoleTypeFromString( value, str );
  188. return value;
  189. }
  190. };
  191. template<>
  192. struct EngineUnmarshallData< S32 >
  193. {
  194. S32 operator()( ConsoleValueRef &ref ) const
  195. {
  196. return (S32)ref;
  197. }
  198. S32 operator()( const char* str ) const
  199. {
  200. return dAtoi( str );
  201. }
  202. };
  203. template<>
  204. struct EngineUnmarshallData< U32 >
  205. {
  206. U32 operator()( ConsoleValueRef &ref ) const
  207. {
  208. return (U32)((S32)ref);
  209. }
  210. U32 operator()( const char* str ) const
  211. {
  212. return dAtoui( str );
  213. }
  214. };
  215. template<>
  216. struct EngineUnmarshallData< F32 >
  217. {
  218. F32 operator()( ConsoleValueRef &ref ) const
  219. {
  220. return (F32)ref;
  221. }
  222. F32 operator()( const char* str ) const
  223. {
  224. return dAtof( str );
  225. }
  226. };
  227. template<>
  228. struct EngineUnmarshallData< U8 >
  229. {
  230. U8 operator()( ConsoleValueRef &ref ) const
  231. {
  232. return (U8)((S32)ref);
  233. }
  234. U8 operator()( const char* str ) const
  235. {
  236. return dAtoui( str );
  237. }
  238. };
  239. template<>
  240. struct EngineUnmarshallData< const char* >
  241. {
  242. const char* operator()( ConsoleValueRef &ref ) const
  243. {
  244. return ref.getStringValue();
  245. }
  246. const char* operator()( const char* str ) const
  247. {
  248. return str;
  249. }
  250. };
  251. template< typename T >
  252. struct EngineUnmarshallData< T* >
  253. {
  254. T* operator()( ConsoleValueRef &ref ) const
  255. {
  256. return dynamic_cast< T* >( Sim::findObject( ref.getStringValue() ) );
  257. }
  258. T* operator()( const char* str ) const
  259. {
  260. return dynamic_cast< T* >( Sim::findObject( str ) );
  261. }
  262. };
  263. template<>
  264. struct EngineUnmarshallData< void >
  265. {
  266. void operator()( ConsoleValueRef& ) const {}
  267. void operator()( const char* ) const {}
  268. };
  269. template<>
  270. struct EngineUnmarshallData< ConsoleValueRef >
  271. {
  272. ConsoleValueRef operator()( ConsoleValueRef ref ) const
  273. {
  274. return ref;
  275. }
  276. };
  277. /// @}
  278. /// @name C to C++ Trampolines
  279. ///
  280. /// The trampolines serve two purposes:
  281. ///
  282. /// For one, they ensure that no matter what argument types are specified by users of the engine API macros, the correct
  283. /// argument value types are enforced on the functions exported by the engine. Let's say, for example, the user writes
  284. /// a function that takes a "Point3F direction" argument, then the template machinery here will automatically expose an
  285. /// API function that takes a "Point3F& direction" argument.
  286. ///
  287. /// Secondly, the templates jump the incoming calls from extern "C" space into C++ space. This is mostly relevant for
  288. /// methods only as they will need an implicit object type argument.
  289. ///
  290. /// @{
  291. // Helper type to factor out commonalities between function and method trampolines.
  292. template<typename T> struct _EngineTrampoline {
  293. struct Args {};
  294. };
  295. template< typename R, typename ...ArgTs >
  296. struct _EngineTrampoline< R( ArgTs ... ) >
  297. {
  298. typedef std::tuple<ArgTs ...> Args;
  299. std::tuple<ArgTs ...> argT;
  300. };
  301. template< typename T >
  302. struct _EngineFunctionTrampolineBase : public _EngineTrampoline< T >
  303. {
  304. typedef T FunctionType;
  305. };
  306. // Trampolines for any call-ins that aren't methods.
  307. template< typename T >
  308. struct _EngineFunctionTrampoline {};
  309. template< typename R, typename ...ArgTs >
  310. struct _EngineFunctionTrampoline< R(ArgTs...) > : public _EngineFunctionTrampolineBase< R(ArgTs...) >
  311. {
  312. private:
  313. using Super = _EngineFunctionTrampolineBase< R(ArgTs...) >;
  314. using ArgsType = typename Super::Args;
  315. template<size_t ...> struct Seq {};
  316. template<size_t N, size_t ...S> struct Gens : Gens<N-1, N-1, S...> {};
  317. template<size_t ...I> struct Gens<0, I...>{ typedef Seq<I...> type; };
  318. template<size_t ...I>
  319. static R dispatchHelper(typename Super::FunctionType fn, const ArgsType& args, Seq<I...>) {
  320. return R( fn(std::get<I>(args) ...) );
  321. }
  322. using SeqType = typename Gens<sizeof...(ArgTs)>::type;
  323. public:
  324. static R jmp(typename Super::FunctionType fn, const ArgsType& args )
  325. {
  326. return dispatchHelper(fn, args, SeqType());
  327. }
  328. };
  329. // Trampolines for engine methods
  330. template< typename T >
  331. struct _EngineMethodTrampolineBase : public _EngineTrampoline< T > {};
  332. template< typename Frame, typename T >
  333. struct _EngineMethodTrampoline {};
  334. template< typename Frame, typename R, typename ...ArgTs >
  335. struct _EngineMethodTrampoline< Frame, R(ArgTs ...) > : public _EngineMethodTrampolineBase< R(ArgTs ...) >
  336. {
  337. using FunctionType = R( typename Frame::ObjectType*, ArgTs ...);
  338. private:
  339. using Super = _EngineMethodTrampolineBase< R(ArgTs ...) >;
  340. using ArgsType = typename _EngineFunctionTrampolineBase< R(ArgTs ...) >::Args;
  341. template<size_t ...> struct Seq {};
  342. template<size_t N, size_t ...S> struct Gens : Gens<N-1, N-1, S...> {};
  343. template<size_t ...I> struct Gens<0, I...>{ typedef Seq<I...> type; };
  344. template<size_t ...I>
  345. static R dispatchHelper(Frame f, const ArgsType& args, Seq<I...>) {
  346. return R( f._exec(std::get<I>(args) ...) );
  347. }
  348. using SeqType = typename Gens<sizeof...(ArgTs)>::type;
  349. public:
  350. static R jmp( typename Frame::ObjectType* object, const ArgsType& args )
  351. {
  352. Frame f;
  353. f.object = object;
  354. return dispatchHelper(f, args, SeqType());
  355. }
  356. };
  357. /// @}
  358. /// @name Thunking
  359. ///
  360. /// Internal functionality for thunks placed between TorqueScript calls of engine functions and their native
  361. /// implementations.
  362. ///
  363. /// @note The functionality in this group is specific to the console interop system.
  364. /// @{
  365. // Helper function to return data from a thunk.
  366. template< typename T >
  367. inline const char* _EngineConsoleThunkReturnValue( const T& value )
  368. {
  369. return EngineMarshallData( value );
  370. }
  371. inline bool _EngineConsoleThunkReturnValue( bool value )
  372. {
  373. return value;
  374. }
  375. inline S32 _EngineConsoleThunkReturnValue( S32 value )
  376. {
  377. return value;
  378. }
  379. inline F32 _EngineConsoleThunkReturnValue( F32 value )
  380. {
  381. return value;
  382. }
  383. inline const char* _EngineConsoleThunkReturnValue( const String& str )
  384. {
  385. return Con::getReturnBuffer( str );
  386. }
  387. inline const char* _EngineConsoleThunkReturnValue( const char* value )
  388. {
  389. return EngineMarshallData( value );
  390. }
  391. template< typename T >
  392. inline const char* _EngineConsoleThunkReturnValue( T* value )
  393. {
  394. return ( value ? value->getIdString() : "" );
  395. }
  396. template< typename T >
  397. inline const char* _EngineConsoleThunkReturnValue( const T* value )
  398. {
  399. return ( value ? value->getIdString() : "" );
  400. }
  401. // Helper class to determine the type of callback registered with the console system.
  402. template< typename R >
  403. struct _EngineConsoleThunkType
  404. {
  405. typedef const char* ReturnType;
  406. typedef StringCallback CallbackType;
  407. };
  408. template<>
  409. struct _EngineConsoleThunkType< S32 >
  410. {
  411. typedef S32 ReturnType;
  412. typedef IntCallback CallbackType;
  413. };
  414. template<>
  415. struct _EngineConsoleThunkType< U32 >
  416. {
  417. typedef U32 ReturnType;
  418. typedef IntCallback CallbackType;
  419. };
  420. template<>
  421. struct _EngineConsoleThunkType< F32 >
  422. {
  423. typedef F32 ReturnType;
  424. typedef FloatCallback CallbackType;
  425. };
  426. template<>
  427. struct _EngineConsoleThunkType< bool >
  428. {
  429. typedef bool ReturnType;
  430. typedef BoolCallback CallbackType;
  431. };
  432. template<>
  433. struct _EngineConsoleThunkType< void >
  434. {
  435. typedef void ReturnType;
  436. typedef VoidCallback CallbackType;
  437. };
  438. // Helper struct to count the number of parameters in a function list.
  439. // The setup through operator () allows omitting the the argument list entirely.
  440. struct _EngineConsoleThunkCountArgs
  441. {
  442. template<typename ...ArgTs> U32 operator()(ArgTs... args){
  443. return sizeof...(ArgTs);
  444. }
  445. operator U32() const{ // FIXME: WHAT IS THIS?? I'm pretty sure it's incorrect, and it's the version that is invoked by all the macros
  446. return 0;
  447. }
  448. };
  449. // Encapsulation of a legacy console function invocation.
  450. namespace engineAPI{
  451. namespace detail{
  452. template<S32 startArgc, typename R, typename ...ArgTs>
  453. struct ThunkHelpers {
  454. using SelfType = ThunkHelpers<startArgc, R, ArgTs...>;
  455. using FunctionType = R(*)(ArgTs...);
  456. template<typename Frame> using MethodType = R(Frame::*)(ArgTs ...) const;
  457. template<size_t I> using IthArgType = typename std::tuple_element<I, std::tuple<ArgTs ...> >::type;
  458. template<size_t ...> struct Seq {};
  459. template<size_t N, size_t ...S> struct Gens : Gens<N-1, N-1, S...> {};
  460. template<size_t ...I> struct Gens<0, I...>{ typedef Seq<I...> type; };
  461. typedef typename _EngineConsoleThunkType< R >::ReturnType ReturnType;
  462. static const S32 NUM_ARGS = sizeof...(ArgTs) + startArgc;
  463. template<size_t index, size_t method_offset = 0, typename ...RealArgTs>
  464. static IthArgType<index> getRealArgValue(S32 argc, ConsoleValueRef *argv, const _EngineFunctionDefaultArguments< void(RealArgTs...) >& defaultArgs)
  465. {
  466. if((startArgc + index) < argc)
  467. {
  468. return EngineUnmarshallData< IthArgType<index> >()( argv[ startArgc + index ] );
  469. } else {
  470. return std::get<index + method_offset>(defaultArgs.mArgs);
  471. }
  472. }
  473. template<size_t ...I>
  474. static R dispatchHelper(S32 argc, ConsoleValueRef *argv, FunctionType fn, const _EngineFunctionDefaultArguments< void(ArgTs...) >& defaultArgs, Seq<I...>){
  475. return fn(SelfType::getRealArgValue<I>(argc, argv, defaultArgs) ...);
  476. }
  477. template<typename Frame, size_t ...I>
  478. static R dispatchHelper(S32 argc, ConsoleValueRef *argv, MethodType<Frame> fn, Frame* frame, const _EngineFunctionDefaultArguments< void( typename Frame::ObjectType*, ArgTs...) >& defaultArgs, Seq<I...>){
  479. return (frame->*fn)(SelfType::getRealArgValue<I,1>(argc, argv, defaultArgs) ...);
  480. }
  481. using SeqType = typename Gens<sizeof...(ArgTs)>::type;
  482. };
  483. template<typename ArgVT> struct MarshallHelpers {
  484. template<typename ...ArgTs> static void marshallEach(S32 &argc, ArgVT *argv, const ArgTs& ...args){}
  485. template<typename H, typename ...Tail> static void marshallEach(S32 &argc, ArgVT *argv, const H& head, const Tail& ...tail){
  486. argv[argc++] = EngineMarshallData(head);
  487. marshallEach(argc, argv, tail...);
  488. }
  489. };
  490. template<> struct MarshallHelpers<ConsoleValueRef> {
  491. template<typename ...ArgTs> static void marshallEach(S32 &argc, ConsoleValueRef *argv, const ArgTs& ...args){}
  492. template<typename H, typename ...Tail> static void marshallEach(S32 &argc, ConsoleValueRef *argv, const H& head, const Tail& ...tail){
  493. EngineMarshallData(head, argc, argv);
  494. marshallEach(argc, argv, tail...);
  495. }
  496. };
  497. }
  498. }
  499. template< S32 startArgc, typename T >
  500. struct _EngineConsoleThunk {};
  501. template< S32 startArgc, typename R, typename ...ArgTs >
  502. struct _EngineConsoleThunk< startArgc, R(ArgTs...) >
  503. {
  504. private:
  505. using Helper = engineAPI::detail::ThunkHelpers<startArgc, R, ArgTs...>;
  506. using SeqType = typename Helper::SeqType;
  507. public:
  508. typedef typename Helper::FunctionType FunctionType;
  509. typedef typename Helper::ReturnType ReturnType;
  510. template<typename Frame> using MethodType = typename Helper::template MethodType<Frame>;
  511. static const S32 NUM_ARGS = Helper::NUM_ARGS;
  512. static ReturnType thunk( S32 argc, ConsoleValueRef *argv, FunctionType fn, const _EngineFunctionDefaultArguments< void(ArgTs...) >& defaultArgs)
  513. {
  514. return _EngineConsoleThunkReturnValue( Helper::dispatchHelper(argc, argv, fn, defaultArgs, SeqType()));
  515. }
  516. template< typename Frame >
  517. static ReturnType thunk( S32 argc, ConsoleValueRef *argv, MethodType<Frame> fn, Frame* frame, const _EngineFunctionDefaultArguments< void( typename Frame::ObjectType*, ArgTs...) >& defaultArgs)
  518. {
  519. return _EngineConsoleThunkReturnValue( Helper::dispatchHelper(argc, argv, fn, frame, defaultArgs, SeqType()));
  520. }
  521. };
  522. // Have to do a partial specialization for void-returning functions :(
  523. template<S32 startArgc, typename ...ArgTs>
  524. struct _EngineConsoleThunk<startArgc, void(ArgTs...)> {
  525. private:
  526. using Helper = engineAPI::detail::ThunkHelpers<startArgc, void, ArgTs...>;
  527. using SeqType = typename Helper::SeqType;
  528. public:
  529. typedef typename Helper::FunctionType FunctionType;
  530. typedef typename Helper::ReturnType ReturnType;
  531. template<typename Frame> using MethodType = typename Helper::template MethodType<Frame>;
  532. static const S32 NUM_ARGS = Helper::NUM_ARGS;
  533. static void thunk( S32 argc, ConsoleValueRef *argv, FunctionType fn, const _EngineFunctionDefaultArguments< void(ArgTs...) >& defaultArgs)
  534. {
  535. Helper::dispatchHelper(argc, argv, fn, defaultArgs, SeqType());
  536. }
  537. template< typename Frame >
  538. static void thunk( S32 argc, ConsoleValueRef *argv, MethodType<Frame> fn, Frame* frame, const _EngineFunctionDefaultArguments< void( typename Frame::ObjectType*, ArgTs...) >& defaultArgs)
  539. {
  540. Helper::dispatchHelper(argc, argv, fn, frame, defaultArgs, SeqType());
  541. }
  542. };
  543. /// @}
  544. /// @name API Definition Macros
  545. ///
  546. /// The macros in this group allow to create engine API functions that work both with the
  547. /// legacy console system as well as with the new engine export system. As such, they only
  548. /// support those function features that are available in both systems. This means that for
  549. /// console-style variadic functions, the ConsoleXXX must be used and that for overloaded
  550. /// and/or C-style variadic functions as well as for placing functions in export scopes,
  551. /// DEFINE_CALLIN must be used directly.
  552. ///
  553. /// When the console system is removed, the console thunking functionality will be removed
  554. /// from these macros but otherwise they will remain unchanged and in place.
  555. ///
  556. /// @{
  557. // Helpers to implement initialization checks. Pulled out into separate macros so this can be deactivated easily.
  558. // Especially important for the initialize() function itself.
  559. #define _CHECK_ENGINE_INITIALIZED_IMPL( fnName, returnType ) \
  560. if( !engineAPI::gIsInitialized ) \
  561. { \
  562. Con::errorf( "EngineAPI: Engine not initialized when calling " #fnName ); \
  563. return EngineTypeTraits< returnType >::ReturnValue( EngineTypeTraits< returnType >::ReturnValueType() ); \
  564. }
  565. #define _CHECK_ENGINE_INITIALIZED( fnName, returnType ) _CHECK_ENGINE_INITIALIZED_IMPL( fnName, returnType )
  566. /// Define a call-in point for calling into the engine.
  567. ///
  568. /// @param name The name of the function as it should be seen by the control layer.
  569. /// @param returnType The value type returned to the control layer.
  570. /// @param args The argument list as it would appear on the function definition
  571. /// @param defaultArgs The list of default argument values.
  572. /// @param usage The usage doc string for the engine API reference.
  573. ///
  574. /// @code
  575. /// DefineEngineFunction( myFunction, int, ( float f, const String& s ), ( "value for s" ), "This is my function." )
  576. /// {
  577. /// return int( f ) + dAtoi( s );
  578. /// }
  579. /// @endcode
  580. #define DefineEngineFunction( name, returnType, args, defaultArgs, usage ) \
  581. static inline returnType _fn ## name ## impl args; \
  582. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## name \
  583. ( _EngineFunctionTrampoline< returnType args >::Args a ) \
  584. { \
  585. _CHECK_ENGINE_INITIALIZED( name, returnType ); \
  586. return EngineTypeTraits< returnType >::ReturnValue( \
  587. _EngineFunctionTrampoline< returnType args >::jmp( _fn ## name ## impl, a ) \
  588. ); \
  589. } \
  590. static _EngineFunctionDefaultArguments< void args > _fn ## name ## DefaultArgs defaultArgs; \
  591. static EngineFunctionInfo _fn ## name ## FunctionInfo( \
  592. #name, \
  593. &_SCOPE<>()(), \
  594. usage, \
  595. #returnType " " #name #args, \
  596. "fn" #name, \
  597. TYPE< returnType args >(), \
  598. &_fn ## name ## DefaultArgs, \
  599. ( void* ) &fn ## name, \
  600. 0 \
  601. ); \
  602. static _EngineConsoleThunkType< returnType >::ReturnType _ ## name ## caster( SimObject*, S32 argc, ConsoleValueRef *argv ) \
  603. { \
  604. return _EngineConsoleThunkType< returnType >::ReturnType( _EngineConsoleThunk< 1, returnType args >::thunk( \
  605. argc, argv, &_fn ## name ## impl, _fn ## name ## DefaultArgs \
  606. ) ); \
  607. } \
  608. static ConsoleFunctionHeader _ ## name ## header \
  609. ( #returnType, #args, #defaultArgs ); \
  610. static ConsoleConstructor \
  611. _ ## name ## obj( NULL, #name, _EngineConsoleThunkType< returnType >::CallbackType( _ ## name ## caster ), usage, \
  612. _EngineConsoleThunk< 1, returnType args >::NUM_ARGS - _EngineConsoleThunkCountArgs() defaultArgs, \
  613. _EngineConsoleThunk< 1, returnType args >::NUM_ARGS, \
  614. false, &_ ## name ## header \
  615. ); \
  616. static inline returnType _fn ## name ## impl args
  617. // The next thing is a bit tricky. DefineEngineMethod allows to make the 'object' (=this) argument to the function
  618. // implicit which presents quite an obstacle for the macro internals as the engine export system requires the
  619. // name of a DLL symbol that represents an extern "C" function with an explicit first object pointer argument.
  620. //
  621. // Even if we ignored the fact that we don't have a guarantee how the various C++ compilers implement implicit 'this' arguments,
  622. // we could still not just use a C++ method for this as then we would have to get past the C++ compiler's mangling to
  623. // get to the function symbol name (let alone the fact that typing this method correctly would be tricky).
  624. //
  625. // So, the trick employed here is to package all but the implicit 'this' argument in a structure and then define an
  626. // extern "C" function that takes the object pointer as a first argument and the struct type as the second argument.
  627. // This will result in a function with an identical stack call frame layout to the function we want.
  628. //
  629. // Unfortunately, that still requires that function to chain on to the real user-defined function. To do this
  630. // cleanly and portably, _EngineMethodTrampoline is used to unpack and jump the call from extern "C" into C++ space.
  631. // In optimized builds, the compiler should be smart enough to pretty much optimize all our trickery here away.
  632. #define _DefineMethodTrampoline( className, name, returnType, args ) \
  633. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType \
  634. fn ## className ## _ ## name ( className* object, _EngineMethodTrampoline< _ ## className ## name ## frame, returnType args >::Args a ) \
  635. { \
  636. _CHECK_ENGINE_INITIALIZED( className::name, returnType ); \
  637. return EngineTypeTraits< returnType >::ReturnValue( \
  638. _EngineMethodTrampoline< _ ## className ## name ## frame, returnType args >::jmp( object, a ) \
  639. ); \
  640. }
  641. /// Define a call-in point for calling a method on an engine object.
  642. ///
  643. /// @param name The name of the C++ class.
  644. /// @param name The name of the method as it should be seen by the control layer.
  645. /// @param returnType The value type returned to the control layer.
  646. /// @param args The argument list as it would appear on the function definition
  647. /// @param defaultArgs The list of default argument values.
  648. /// @param usage The usage doc string for the engine API reference.
  649. ///
  650. /// @code
  651. /// DefineEngineMethod( MyClass, myMethod, int, ( float f, const String& s ), ( "value for s" ), "This is my method." )
  652. /// {
  653. /// return object->someMethod( f, s );
  654. /// }
  655. /// @endcode
  656. #define DefineEngineMethod( className, name, returnType, args, defaultArgs, usage ) \
  657. struct _ ## className ## name ## frame \
  658. { \
  659. typedef className ObjectType; \
  660. className* object; \
  661. inline returnType _exec args const; \
  662. }; \
  663. _DefineMethodTrampoline( className, name, returnType, args ); \
  664. static _EngineFunctionDefaultArguments< _EngineMethodTrampoline< _ ## className ## name ## frame, void args >::FunctionType > \
  665. _fn ## className ## name ## DefaultArgs defaultArgs; \
  666. static EngineFunctionInfo _fn ## className ## name ## FunctionInfo( \
  667. #name, \
  668. &_SCOPE< className >()(), \
  669. usage, \
  670. "virtual " #returnType " " #name #args, \
  671. "fn" #className "_" #name, \
  672. TYPE< _EngineMethodTrampoline< _ ## className ## name ## frame, returnType args >::FunctionType >(), \
  673. &_fn ## className ## name ## DefaultArgs, \
  674. ( void* ) &fn ## className ## _ ## name, \
  675. 0 \
  676. ); \
  677. static _EngineConsoleThunkType< returnType >::ReturnType _ ## className ## name ## caster( SimObject* object, S32 argc, ConsoleValueRef *argv ) \
  678. { \
  679. _ ## className ## name ## frame frame; \
  680. frame.object = static_cast< className* >( object ); \
  681. return _EngineConsoleThunkType< returnType >::ReturnType( _EngineConsoleThunk< 2, returnType args >::thunk( \
  682. argc, argv, &_ ## className ## name ## frame::_exec, &frame, _fn ## className ## name ## DefaultArgs \
  683. ) ); \
  684. } \
  685. static ConsoleFunctionHeader _ ## className ## name ## header \
  686. ( #returnType, #args, #defaultArgs ); \
  687. static ConsoleConstructor \
  688. className ## name ## obj( #className, #name, \
  689. _EngineConsoleThunkType< returnType >::CallbackType( _ ## className ## name ## caster ), usage, \
  690. _EngineConsoleThunk< 2, returnType args >::NUM_ARGS - _EngineConsoleThunkCountArgs() defaultArgs, \
  691. _EngineConsoleThunk< 2, returnType args >::NUM_ARGS, \
  692. false, &_ ## className ## name ## header \
  693. ); \
  694. returnType _ ## className ## name ## frame::_exec args const
  695. /// Define a call-in point for calling into the engine. Unlike with DefineEngineFunction, the statically
  696. /// callable function will be confined to the namespace of the given class.
  697. ///
  698. /// @param name The name of the C++ class (or a registered export scope).
  699. /// @param name The name of the method as it should be seen by the control layer.
  700. /// @param returnType The value type returned to the control layer.
  701. /// @param args The argument list as it would appear on the function definition
  702. /// @param defaultArgs The list of default argument values.
  703. /// @param usage The usage doc string for the engine API reference.
  704. ///
  705. /// @code
  706. /// DefineEngineStaticMethod( MyClass, myMethod, int, ( float f, string s ), ( "value for s" ), "This is my method." )
  707. /// {
  708. /// }
  709. /// @endcode
  710. #define DefineEngineStaticMethod( className, name, returnType, args, defaultArgs, usage ) \
  711. static inline returnType _fn ## className ## name ## impl args; \
  712. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## className ## _ ## name \
  713. ( _EngineFunctionTrampoline< returnType args >::Args a ) \
  714. { \
  715. _CHECK_ENGINE_INITIALIZED( className::name, returnType ); \
  716. return EngineTypeTraits< returnType >::ReturnValue( \
  717. _EngineFunctionTrampoline< returnType args >::jmp( _fn ## className ## name ## impl, a ) \
  718. ); \
  719. } \
  720. static _EngineFunctionDefaultArguments< void args > _fn ## className ## name ## DefaultArgs defaultArgs; \
  721. static EngineFunctionInfo _fn ## name ## FunctionInfo( \
  722. #name, \
  723. &_SCOPE< className >()(), \
  724. usage, \
  725. #returnType " " #name #args, \
  726. "fn" #className "_" #name, \
  727. TYPE< returnType args >(), \
  728. &_fn ## className ## name ## DefaultArgs, \
  729. ( void* ) &fn ## className ## _ ## name, \
  730. 0 \
  731. ); \
  732. static _EngineConsoleThunkType< returnType >::ReturnType _ ## className ## name ## caster( SimObject*, S32 argc, ConsoleValueRef *argv )\
  733. { \
  734. return _EngineConsoleThunkType< returnType >::ReturnType( _EngineConsoleThunk< 1, returnType args >::thunk( \
  735. argc, argv, &_fn ## className ## name ## impl, _fn ## className ## name ## DefaultArgs \
  736. ) ); \
  737. } \
  738. static ConsoleFunctionHeader _ ## className ## name ## header \
  739. ( #returnType, #args, #defaultArgs, true ); \
  740. static ConsoleConstructor \
  741. _ ## className ## name ## obj( #className, #name, _EngineConsoleThunkType< returnType >::CallbackType( _ ## className ## name ## caster ), usage, \
  742. _EngineConsoleThunk< 1, returnType args >::NUM_ARGS - _EngineConsoleThunkCountArgs() defaultArgs, \
  743. _EngineConsoleThunk< 1, returnType args >::NUM_ARGS, \
  744. false, &_ ## className ## name ## header \
  745. ); \
  746. static inline returnType _fn ## className ## name ## impl args
  747. # define DefineEngineStringlyVariadicFunction(name,returnType,minArgs,maxArgs,usage) \
  748. static inline returnType _fn ## name ## impl (SimObject *, S32 argc, ConsoleValueRef *argv); \
  749. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## name \
  750. (S32 argc, const char** argv) \
  751. { \
  752. _CHECK_ENGINE_INITIALIZED( name, returnType ); \
  753. StringStackConsoleWrapper args(argc, argv); \
  754. return EngineTypeTraits< returnType >::ReturnValue( \
  755. _fn ## name ## impl(NULL, args.count(), args) \
  756. ); \
  757. } \
  758. static _EngineFunctionDefaultArguments< void (S32 argc, const char** argv) > _fn ## name ## DefaultArgs; \
  759. static EngineFunctionInfo _fn ## name ## FunctionInfo( \
  760. #name, \
  761. &_SCOPE<>()(), \
  762. usage, \
  763. #returnType " " #name "(S32 argc, const char** argv)", \
  764. "fn" #name, \
  765. TYPE< returnType (S32 argc, const char** argv) >(), \
  766. &_fn ## name ## DefaultArgs, \
  767. ( void* ) &fn ## name, \
  768. 0 \
  769. ); \
  770. ConsoleConstructor cc_##name##_obj(NULL,#name,_fn ## name ## impl,usage,minArgs,maxArgs); \
  771. returnType _fn ## name ## impl(SimObject *, S32 argc, ConsoleValueRef *argv)
  772. # define DefineEngineStringlyVariadicMethod(className, name,returnType,minArgs,maxArgs,usage) \
  773. static inline returnType _fn ## className ## _ ## name ## impl (className* object, S32 argc, ConsoleValueRef* argv); \
  774. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## className ## _ ## name \
  775. (className* object, S32 argc, const char** argv) \
  776. { \
  777. _CHECK_ENGINE_INITIALIZED( name, returnType ); \
  778. StringStackConsoleWrapper args(argc, argv); \
  779. return EngineTypeTraits< returnType >::ReturnValue( \
  780. _fn ## className ## _ ## name ## impl(object, args.count(), args) \
  781. ); \
  782. } \
  783. static _EngineFunctionDefaultArguments< void (className* object, S32 argc, const char** argv) > _fn ## className ## _ ## name ## DefaultArgs; \
  784. static EngineFunctionInfo _fn ## className ## _ ## name ## FunctionInfo( \
  785. #name, \
  786. &_SCOPE<>()(), \
  787. usage, \
  788. #returnType " " #name "(SimObject* object, S32 argc, const char** argv)", \
  789. "fn" #className "_" #name, \
  790. TYPE< returnType (SimObject* object, S32 argc, const char** argv) >(), \
  791. &_fn ## className ## _ ## name ## DefaultArgs, \
  792. ( void* ) &fn ## className ## _ ## name, \
  793. 0 \
  794. ); \
  795. returnType cm_##className##_##name##_caster(SimObject* object, S32 argc, ConsoleValueRef* argv) { \
  796. AssertFatal( dynamic_cast<className*>( object ), "Object passed to " #name " is not a " #className "!" ); \
  797. conmethod_return_##returnType ) _fn ## className ## _ ## name ## impl(static_cast<className*>(object),argc,argv); \
  798. }; \
  799. ConsoleConstructor cc_##className##_##name##_obj(#className,#name,cm_##className##_##name##_caster,usage,minArgs,maxArgs); \
  800. static inline returnType _fn ## className ## _ ## name ## impl(className *object, S32 argc, ConsoleValueRef *argv)
  801. // The following three macros are only temporary. They allow to define engineAPI functions using the framework
  802. // here in this file while being visible only in the new API. When the console interop is removed, these macros
  803. // can be removed and all their uses be replaced with their corresponding versions that now still include support
  804. // for the console (e.g. DefineNewEngineFunction should become DefineEngineFunction).
  805. #define DefineNewEngineFunction( name, returnType, args, defaultArgs, usage ) \
  806. static inline returnType _fn ## name ## impl args; \
  807. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## name \
  808. ( _EngineFunctionTrampoline< returnType args >::Args a ) \
  809. { \
  810. _CHECK_ENGINE_INITIALIZED( name, returnType ); \
  811. return EngineTypeTraits< returnType >::ReturnValue( \
  812. _EngineFunctionTrampoline< returnType args >::jmp( _fn ## name ## impl, a ) \
  813. ); \
  814. } \
  815. static _EngineFunctionDefaultArguments< void args > _fn ## name ## DefaultArgs defaultArgs; \
  816. static EngineFunctionInfo _fn ## name ## FunctionInfo( \
  817. #name, \
  818. &_SCOPE<>()(), \
  819. usage, \
  820. #returnType " " #name #args, \
  821. "fn" #name, \
  822. TYPE< returnType args >(), \
  823. &_fn ## name ## DefaultArgs, \
  824. ( void* ) &fn ## name, \
  825. 0 \
  826. ); \
  827. static inline returnType _fn ## name ## impl args
  828. #define DefineNewEngineMethod( className, name, returnType, args, defaultArgs, usage ) \
  829. struct _ ## className ## name ## frame \
  830. { \
  831. typedef className ObjectType; \
  832. className* object; \
  833. inline returnType _exec args const; \
  834. }; \
  835. _DefineMethodTrampoline( className, name, returnType, args ); \
  836. static _EngineFunctionDefaultArguments< _EngineMethodTrampoline< _ ## className ## name ## frame, void args >::FunctionType > \
  837. _fn ## className ## name ## DefaultArgs defaultArgs; \
  838. static EngineFunctionInfo _fn ## className ## name ## FunctionInfo( \
  839. #name, \
  840. &_SCOPE< className >()(), \
  841. usage, \
  842. "virtual " #returnType " " #name #args, \
  843. "fn" #className "_" #name, \
  844. TYPE< _EngineMethodTrampoline< _ ## className ## name ## frame, returnType args >::FunctionType >(), \
  845. &_fn ## className ## name ## DefaultArgs, \
  846. ( void* ) &fn ## className ## _ ## name, \
  847. 0 \
  848. ); \
  849. returnType _ ## className ## name ## frame::_exec args const
  850. #define DefineNewEngineStaticMethod( className, name, returnType, args, defaultArgs, usage ) \
  851. static inline returnType _fn ## className ## name ## impl args; \
  852. TORQUE_API EngineTypeTraits< returnType >::ReturnValueType fn ## className ## _ ## name \
  853. ( _EngineFunctionTrampoline< returnType args >::Args a ) \
  854. { \
  855. _CHECK_ENGINE_INITIALIZED( className::name, returnType ); \
  856. return EngineTypeTraits< returnType >::ReturnValue( \
  857. _EngineFunctionTrampoline< returnType args >::jmp( _fn ## className ## name ## impl, a ) \
  858. ); \
  859. } \
  860. static _EngineFunctionDefaultArguments< void args > _fn ## className ## name ## DefaultArgs defaultArgs; \
  861. static EngineFunctionInfo _fn ## name ## FunctionInfo( \
  862. #name, \
  863. &_SCOPE< className >()(), \
  864. usage, \
  865. #returnType " " #name #args, \
  866. "fn" #className "_" #name, \
  867. TYPE< returnType args >(), \
  868. &_fn ## className ## name ## DefaultArgs, \
  869. ( void* ) &fn ## className ## _ ## name, \
  870. 0 \
  871. ); \
  872. static inline returnType _fn ## className ## name ## impl args
  873. /// @}
  874. //=============================================================================
  875. // Callbacks.
  876. //=============================================================================
  877. /// Matching implement for DECLARE_CALLBACK.
  878. ///
  879. ///
  880. /// @warn With the new interop system, method-style callbacks <em>must not</em> be triggered on object
  881. /// that are being created! This is because the control layer will likely not yet have a fully valid wrapper
  882. /// object in place for the EngineObject under construction.
  883. #define IMPLEMENT_CALLBACK( class, name, returnType, args, argNames, usageString ) \
  884. struct _ ## class ## name ## frame { typedef class ObjectType; }; \
  885. TORQUE_API _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType* cb ## class ## _ ## name; \
  886. TORQUE_API void set_cb ## class ## _ ## name( \
  887. _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType fn ) \
  888. { cb ## class ## _ ## name = fn; } \
  889. _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType* cb ## class ## _ ## name; \
  890. namespace { \
  891. ::EngineFunctionInfo _cb ## class ## name( \
  892. #name, \
  893. &::_SCOPE< class >()(), \
  894. usageString, \
  895. "virtual " #returnType " " #name #args, \
  896. "cb" #class "_" #name, \
  897. ::TYPE< _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType >(), \
  898. NULL, \
  899. ( void* ) &cb ## class ## _ ## name, \
  900. EngineFunctionCallout \
  901. ); \
  902. } \
  903. returnType class::name ## _callback args \
  904. { \
  905. if( cb ## class ## _ ## name ) { \
  906. _EngineCallbackHelper cbh( this, reinterpret_cast< const void* >( cb ## class ## _ ## name ) ); \
  907. return returnType( cbh.call< returnType > argNames ); \
  908. } \
  909. if( engineAPI::gUseConsoleInterop ) \
  910. { \
  911. static StringTableEntry sName = StringTable->insert( #name ); \
  912. _EngineConsoleCallbackHelper cbh( sName, this ); \
  913. return returnType( cbh.call< returnType > argNames ); \
  914. } \
  915. return returnType(); \
  916. } \
  917. namespace { \
  918. ConsoleFunctionHeader _ ## class ## name ## header( \
  919. #returnType, #args, "" ); \
  920. ConsoleConstructor _ ## class ## name ## obj( #class, #name, usageString, &_ ## class ## name ## header ); \
  921. }
  922. /// Used to define global callbacks not associated with
  923. /// any particular class or namespace.
  924. #define IMPLEMENT_GLOBAL_CALLBACK( name, returnType, args, argNames, usageString ) \
  925. DEFINE_CALLOUT( cb ## name, name,, returnType, args, 0, usageString ); \
  926. returnType name ## _callback args \
  927. { \
  928. if( cb ## name ) \
  929. return returnType( cb ## name argNames ); \
  930. if( engineAPI::gUseConsoleInterop ) \
  931. { \
  932. static StringTableEntry sName = StringTable->insert( #name ); \
  933. _EngineConsoleCallbackHelper cbh( sName, NULL ); \
  934. return returnType( cbh.call< returnType > argNames ); \
  935. } \
  936. return returnType(); \
  937. } \
  938. namespace { \
  939. ConsoleFunctionHeader _ ## name ## header( \
  940. #returnType, #args, "" ); \
  941. ConsoleConstructor _ ## name ## obj( NULL, #name, usageString, &_ ## name ## header ); \
  942. }
  943. // Again, temporary macros to allow splicing the API while we still have the console interop around.
  944. #define IMPLEMENT_CONSOLE_CALLBACK( class, name, returnType, args, argNames, usageString ) \
  945. returnType class::name ## _callback args \
  946. { \
  947. if( engineAPI::gUseConsoleInterop ) \
  948. { \
  949. static StringTableEntry sName = StringTable->insert( #name ); \
  950. _EngineConsoleCallbackHelper cbh( sName, this ); \
  951. return returnType( cbh.call< returnType > argNames ); \
  952. } \
  953. return returnType(); \
  954. } \
  955. namespace { \
  956. ConsoleFunctionHeader _ ## class ## name ## header( \
  957. #returnType, #args, "" ); \
  958. ConsoleConstructor _ ## class ## name ## obj( #class, #name, usageString, &_ ## class ## name ## header ); \
  959. }
  960. #define IMPLEMENT_NEW_CALLBACK( class, name, returnType, args, argNames, usageString ) \
  961. struct _ ## class ## name ## frame { typedef class ObjectType; }; \
  962. TORQUE_API _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType* cb ## class ## _ ## name; \
  963. TORQUE_API void set_cb ## class ## _ ## name( \
  964. _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType fn ) \
  965. { cb ## class ## _ ## name = fn; } \
  966. _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType* cb ## class ## _ ## name; \
  967. namespace { \
  968. ::EngineFunctionInfo _cb ## class ## name( \
  969. #name, \
  970. &::_SCOPE< class >()(), \
  971. usageString, \
  972. "virtual " #returnType " " #name #args, \
  973. "cb" #class "_" #name, \
  974. ::TYPE< _EngineMethodTrampoline< _ ## class ## name ## frame, returnType args >::FunctionType >(), \
  975. NULL, \
  976. &cb ## class ## _ ## name, \
  977. EngineFunctionCallout \
  978. ); \
  979. } \
  980. returnType class::name ## _callback args \
  981. { \
  982. if( cb ## class ## _ ## name ) { \
  983. _EngineCallbackHelper cbh( this, reinterpret_cast< const void* >( cb ## class ## _ ## name ) ); \
  984. return returnType( cbh.call< returnType > argNames ); \
  985. } \
  986. return returnType(); \
  987. }
  988. // Internal helper class for doing call-outs in the new interop.
  989. struct _EngineCallbackHelper
  990. {
  991. protected:
  992. EngineObject* mThis;
  993. const void* mFn;
  994. public:
  995. _EngineCallbackHelper( EngineObject* pThis, const void* fn )
  996. : mThis( pThis ),
  997. mFn( fn ) {}
  998. template< typename R, typename ...ArgTs >
  999. R call(ArgTs ...args) const
  1000. {
  1001. typedef R( FunctionType )( EngineObject*, ArgTs... );
  1002. return R( reinterpret_cast< FunctionType* >( const_cast<void*>(mFn) )( mThis, args... ) );
  1003. }
  1004. };
  1005. #include "console/stringStack.h"
  1006. // Internal helper for callback support in legacy console system.
  1007. struct _BaseEngineConsoleCallbackHelper
  1008. {
  1009. public:
  1010. /// Matches up to storeArgs.
  1011. static const U32 MAX_ARGUMENTS = 11;
  1012. SimObject* mThis;
  1013. S32 mInitialArgc;
  1014. S32 mArgc;
  1015. StringTableEntry mCallbackName;
  1016. ConsoleValueRef mArgv[ MAX_ARGUMENTS + 2 ];
  1017. ConsoleValueRef _exec();
  1018. ConsoleValueRef _execLater(SimConsoleThreadExecEvent *evt);
  1019. _BaseEngineConsoleCallbackHelper() {;}
  1020. };
  1021. // Base helper for console callbacks
  1022. struct _EngineConsoleCallbackHelper : public _BaseEngineConsoleCallbackHelper
  1023. {
  1024. private:
  1025. using Helper = engineAPI::detail::MarshallHelpers<ConsoleValueRef>;
  1026. public:
  1027. _EngineConsoleCallbackHelper( StringTableEntry callbackName, SimObject* pThis )
  1028. {
  1029. mThis = pThis;
  1030. mArgc = mInitialArgc = pThis ? 2 : 1 ;
  1031. mCallbackName = callbackName;
  1032. }
  1033. template< typename R, typename ...ArgTs >
  1034. R call(ArgTs ...args)
  1035. {
  1036. if (Con::isMainThread())
  1037. {
  1038. ConsoleStackFrameSaver sav; sav.save();
  1039. CSTK.reserveValues(mArgc + sizeof...(ArgTs), mArgv);
  1040. mArgv[ 0 ].value->setStackStringValue(mCallbackName);
  1041. Helper::marshallEach(mArgc, mArgv, args...);
  1042. return R( EngineUnmarshallData< R >()( _exec() ) );
  1043. }
  1044. else
  1045. {
  1046. SimConsoleThreadExecCallback cb;
  1047. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(mArgc + sizeof...(ArgTs), NULL, false, &cb);
  1048. evt->populateArgs(mArgv);
  1049. mArgv[ 0 ].value->setStackStringValue(mCallbackName);
  1050. Helper::marshallEach(mArgc, mArgv, args...);
  1051. Sim::postEvent((SimObject*)Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1052. return R( EngineUnmarshallData< R >()( cb.waitForResult() ) );
  1053. }
  1054. }
  1055. };
  1056. // Override for when first parameter is presumably a SimObject*, in which case A will be absorbed as the callback
  1057. template<typename P1> struct _EngineConsoleExecCallbackHelper : public _BaseEngineConsoleCallbackHelper
  1058. {
  1059. private:
  1060. using Helper = engineAPI::detail::MarshallHelpers<ConsoleValueRef>;
  1061. public:
  1062. _EngineConsoleExecCallbackHelper( SimObject* pThis )
  1063. {
  1064. mThis = pThis;
  1065. mArgc = mInitialArgc = 2;
  1066. mCallbackName = NULL;
  1067. }
  1068. template< typename R, typename SCB, typename ...ArgTs >
  1069. R call( SCB simCB , ArgTs ...args )
  1070. {
  1071. if (Con::isMainThread())
  1072. {
  1073. ConsoleStackFrameSaver sav; sav.save();
  1074. CSTK.reserveValues(mArgc+sizeof...(ArgTs), mArgv);
  1075. mArgv[ 0 ].value->setStackStringValue(simCB);
  1076. Helper::marshallEach(mArgc, mArgv, args...);
  1077. return R( EngineUnmarshallData< R >()( _exec() ) );
  1078. }
  1079. else
  1080. {
  1081. SimConsoleThreadExecCallback cb;
  1082. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(mArgc+sizeof...(ArgTs), NULL, true, &cb);
  1083. evt->populateArgs(mArgv);
  1084. mArgv[ 0 ].value->setStackStringValue(simCB);
  1085. Helper::marshallEach(mArgc, mArgv, args...);
  1086. Sim::postEvent(mThis, evt, Sim::getCurrentTime());
  1087. return R( EngineUnmarshallData< R >()( cb.waitForResult() ) );
  1088. }
  1089. }
  1090. };
  1091. // Override for when first parameter is const char*
  1092. template<> struct _EngineConsoleExecCallbackHelper<const char*> : public _BaseEngineConsoleCallbackHelper
  1093. {
  1094. private:
  1095. using Helper = engineAPI::detail::MarshallHelpers<ConsoleValueRef>;
  1096. public:
  1097. _EngineConsoleExecCallbackHelper( const char *callbackName )
  1098. {
  1099. mThis = NULL;
  1100. mArgc = mInitialArgc = 1;
  1101. mCallbackName = StringTable->insert(callbackName);
  1102. }
  1103. template< typename R, typename ...ArgTs >
  1104. R call(ArgTs ...args)
  1105. {
  1106. if (Con::isMainThread())
  1107. {
  1108. ConsoleStackFrameSaver sav; sav.save();
  1109. CSTK.reserveValues(mArgc+sizeof...(ArgTs), mArgv);
  1110. mArgv[ 0 ].value->setStackStringValue(mCallbackName);
  1111. Helper::marshallEach(mArgc, mArgv, args...);
  1112. return R( EngineUnmarshallData< R >()( _exec() ) );
  1113. }
  1114. else
  1115. {
  1116. SimConsoleThreadExecCallback cb;
  1117. SimConsoleThreadExecEvent *evt = new SimConsoleThreadExecEvent(mArgc+sizeof...(ArgTs), NULL, false, &cb);
  1118. evt->populateArgs(mArgv);
  1119. mArgv[ 0 ].value->setStackStringValue(mCallbackName);
  1120. Helper::marshallEach(mArgc, mArgv, args...);
  1121. Sim::postEvent((SimObject*)Sim::getRootGroup(), evt, Sim::getCurrentTime());
  1122. return R( EngineUnmarshallData< R >()( cb.waitForResult() ) );
  1123. }
  1124. }
  1125. };
  1126. // Re-enable some VC warnings we disabled for this file.
  1127. #pragma warning( pop ) // 4510 and 4610
  1128. #endif // !_ENGINEAPI_H_