engineFunctions.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 _ENGINEFUNCTIONS_H_
  23. #define _ENGINEFUNCTIONS_H_
  24. #include <tuple>
  25. #ifndef _FIXEDTUPLE_H_
  26. #include "fixedTuple.h"
  27. #endif
  28. #ifndef _ENGINEEXPORTS_H_
  29. #include "console/engineExports.h"
  30. #endif
  31. #ifndef _ENGINETYPEINFO_H_
  32. #include "console/engineTypeInfo.h"
  33. #endif
  34. /// @file
  35. /// Structures for function-type engine export information.
  36. #ifdef TORQUE_COMPILER_VISUALC
  37. #define TORQUE_API extern "C" __declspec( dllexport )
  38. #elif defined( TORQUE_COMPILER_GCC )
  39. #define TORQUE_API extern "C" __attribute__( ( visibility( "default" ) ) )
  40. #else
  41. #error Unsupported compiler.
  42. #endif
  43. // #pragma pack is bugged in GCC in that the packing in place at the template instantiation
  44. // sites rather than their definition sites is used. Enable workarounds.
  45. #ifdef TORQUE_COMPILER_GCC
  46. #define _PACK_BUG_WORKAROUNDS
  47. #endif
  48. /// Structure storing the default argument values for a function invocation
  49. /// frame.
  50. struct EngineFunctionDefaultArguments
  51. {
  52. /// Number of default arguments for the function call frame.
  53. ///
  54. /// @warn This is @b NOT the size of the memory block returned by getArgs() and also
  55. /// not the number of elements it contains.
  56. U32 mNumDefaultArgs;
  57. /// Return a pointer to the variable-sized array of default argument values.
  58. ///
  59. /// @warn The arguments must be stored @b IMMEDIATELY after #mNumDefaultArgs.
  60. /// @warn This is a @b FULL frame and not just the default arguments, i.e. it starts with the
  61. /// first argument that the function takes and ends with the last argument it takes.
  62. /// @warn If the compiler's #pragma pack is buggy, the elements in this structure are allowed
  63. /// to be 4-byte aligned rather than byte-aligned as they should be.
  64. const U8* getArgs() const
  65. {
  66. return ( const U8* ) &( mNumDefaultArgs ) + sizeof( mNumDefaultArgs );
  67. }
  68. };
  69. // Need byte-aligned packing for the default argument structures.
  70. #ifdef _WIN64
  71. #pragma pack( push, 8 )
  72. #else
  73. #pragma pack( push, 1 )
  74. #endif
  75. // Structure encapsulating default arguments to an engine API function.
  76. template< typename T >
  77. struct _EngineFunctionDefaultArguments {};
  78. template<typename ...ArgTs>
  79. struct _EngineFunctionDefaultArguments< void(ArgTs...) > : public EngineFunctionDefaultArguments
  80. {
  81. template<typename T> using DefVST = typename EngineTypeTraits<T>::DefaultArgumentValueStoreType;
  82. fixed_tuple<DefVST<ArgTs> ...> mFixedArgs;
  83. std::tuple<DefVST<ArgTs> ...> mArgs;
  84. private:
  85. using SelfType = _EngineFunctionDefaultArguments< void(ArgTs...) >;
  86. template<size_t ...> struct Seq {};
  87. template<size_t N, size_t ...S> struct Gens : Gens<N-1, N-1, S...> {};
  88. template<size_t ...I> struct Gens<0, I...>{ typedef Seq<I...> type; };
  89. template<typename ...TailTs, size_t ...I>
  90. static void copyHelper(std::tuple<DefVST<ArgTs> ...> &args, std::tuple<DefVST<TailTs> ...> &defaultArgs, Seq<I...>) {
  91. std::tie(std::get<I + (sizeof...(ArgTs) - sizeof...(TailTs))>(args)...) = defaultArgs;
  92. }
  93. #if defined(_MSC_VER) && (_MSC_VER >= 1910) && (_MSC_VER < 1920)
  94. template<typename ...TailTs>
  95. struct DodgyVCHelper
  96. {
  97. using type = typename std::enable_if<sizeof...(TailTs) <= sizeof...(ArgTs), decltype(mArgs)>::type;
  98. };
  99. template<typename ...TailTs> using MaybeSelfEnabled = typename DodgyVCHelper<TailTs...>::type;
  100. #else
  101. template<typename ...TailTs> using MaybeSelfEnabled = typename std::enable_if<sizeof...(TailTs) <= sizeof...(ArgTs), decltype(mArgs)>::type;
  102. #endif
  103. template<typename ...TailTs> static MaybeSelfEnabled<TailTs...> tailInit(TailTs ...tail) {
  104. std::tuple<DefVST<ArgTs>...> argsT;
  105. std::tuple<DefVST<TailTs>...> tailT = std::make_tuple(tail...);
  106. SelfType::copyHelper<TailTs...>(argsT, tailT, typename Gens<sizeof...(TailTs)>::type());
  107. return argsT;
  108. };
  109. public:
  110. template<typename ...TailTs> _EngineFunctionDefaultArguments(TailTs ...tail)
  111. : EngineFunctionDefaultArguments({sizeof...(TailTs)}), mArgs(SelfType::tailInit(tail...))
  112. {
  113. fixed_tuple_mutator<void(DefVST<ArgTs>...), void(DefVST<ArgTs>...)>::copy(mArgs, mFixedArgs);
  114. }
  115. };
  116. #pragma pack( pop )
  117. // Helper to allow flags argument to DEFINE_FUNCTION to be empty.
  118. struct _EngineFunctionFlags
  119. {
  120. U32 val;
  121. _EngineFunctionFlags()
  122. : val( 0 ) {}
  123. _EngineFunctionFlags( U32 val )
  124. : val( val ) {}
  125. operator U32() const { return val; }
  126. };
  127. ///
  128. enum EngineFunctionFlags
  129. {
  130. /// Function is a callback into the control layer. If this flag is not set,
  131. /// the function is a call-in.
  132. EngineFunctionCallout = BIT( 0 ),
  133. };
  134. /// A function exported by the engine for interfacing with the control layer.
  135. ///
  136. /// A function can either be a call-in, transfering control flow from the control layer to the engine, or a call-out,
  137. /// transfering control flow from the engine to the control layer.
  138. ///
  139. /// All engine API functions use the native C (@c cdecl) calling convention.
  140. ///
  141. /// Be aware that there a no implicit parameters to functions. This, for example, means that methods will simply
  142. /// list an object type parameter as their first argument but otherwise be indistinguishable from other functions.
  143. ///
  144. /// Variadic functions are supported.
  145. ///
  146. /// @section engineFunction_strings String Arguments and Return Values
  147. ///
  148. /// Strings passed through the API are assumed to be owned by the caller. They must persist for the entire duration
  149. /// of a call.
  150. ///
  151. /// Strings returned by a function are assumed to be in transient storage that will be overwritten by subsequent API
  152. /// calls. If the caller wants to preserve a string, it is responsible to copying strings to its own memory. This will
  153. /// happen with most higher-level control layers anyway.
  154. ///
  155. /// @section engineFunction_defaultargs Default Arguments
  156. ///
  157. /// As the engine API export system is set up to not require hand-written code in generated wrappers per se, the
  158. /// export system seeks to include a maximum possible amount of information in the export structures.
  159. /// To this end, where applicable, information about suggested default values for arguments to the engine API
  160. /// functions is stored in the export structures. It is up to the wrapper generator if and how it makes use of
  161. /// this information.
  162. ///
  163. /// Default arguments are represented by capturing raw stack frame vectors of the arguments to functions. These
  164. /// frames could be used as default images for passing arguments in stack frames, though wrapper generators
  165. /// may actually want to read out individual argument values and include them in function prototypes within
  166. /// the generated code.
  167. ///
  168. /// @section engineFunction_callin Call-ins
  169. ///
  170. /// Call-ins are exposed as native entry points. The control layer must be able to natively
  171. /// marshall arguments and call DLL function exports using C calling conventions.
  172. ///
  173. /// @section engineFunction_callout Call-outs
  174. ///
  175. /// Call-outs are exposed as pointer-sized memory locations into which the control layer needs
  176. /// to install addresses of functions that receive the call from the engine back into the control
  177. /// layer. The function has to follow C calling conventions and
  178. ///
  179. /// A call-out will initially be set to NULL and while being NULL, will simply cause the engine
  180. /// to skip and ignore the call-out. This allows the control layer to only install call-outs
  181. /// it is actually interested in.
  182. ///
  183. class EngineFunctionInfo : public EngineExport
  184. {
  185. public:
  186. DECLARE_CLASS( EngineFunctionInfo, EngineExport );
  187. protected:
  188. /// A combination of EngineFunctionFlags.
  189. BitSet32 mFunctionFlags;
  190. /// The type of the function.
  191. const EngineTypeInfo* mFunctionType;
  192. /// Default values for the function arguments.
  193. const EngineFunctionDefaultArguments* mDefaultArgumentValues;
  194. /// Name of the DLL symbol denoting the address of the exported entity.
  195. const char* mBindingName;
  196. /// Full function prototype string. Useful for quick printing and most importantly,
  197. /// this will be the only place containing information about the argument names.
  198. const char* mPrototypeString;
  199. /// Address of either the function implementation or the variable taking the address
  200. /// of a call-out.
  201. void* mAddress;
  202. /// Next function in the global link chain of engine functions.
  203. EngineFunctionInfo* mNextFunction;
  204. /// First function in the global link chain of engine functions.
  205. static EngineFunctionInfo* smFirstFunction;
  206. public:
  207. ///
  208. EngineFunctionInfo( const char* name,
  209. EngineExportScope* scope,
  210. const char* docString,
  211. const char* protoypeString,
  212. const char* bindingName,
  213. const EngineTypeInfo* functionType,
  214. const EngineFunctionDefaultArguments* defaultArgs,
  215. void* address,
  216. U32 flags );
  217. /// Return the name of the function.
  218. const char* getFunctionName() const { return getExportName(); }
  219. /// Return the function's full prototype string including the return type, function name,
  220. /// and argument list.
  221. const char* getPrototypeString() const { return mPrototypeString; }
  222. /// Return the DLL export symbol name.
  223. const char* getBindingName() const { return mBindingName; }
  224. /// Test whether this is a callout function.
  225. bool isCallout() const { return mFunctionFlags.test( EngineFunctionCallout ); }
  226. /// Test whether the function is variadic, i.e. takes a variable number of arguments.
  227. bool isVariadic() const { return mFunctionType->isVariadic(); }
  228. /// Return the type of this function.
  229. const EngineTypeInfo* getFunctionType() const { return mFunctionType; }
  230. /// Return the return type of the function.
  231. const EngineTypeInfo* getReturnType() const { return getFunctionType()->getArgumentTypeTable()->getReturnType(); }
  232. /// Return the number of arguments that this function takes. If the function is variadic,
  233. /// this is the number of fixed arguments.
  234. U32 getNumArguments() const { return getFunctionType()->getArgumentTypeTable()->getNumArguments(); }
  235. ///
  236. const EngineTypeInfo* getArgumentType( U32 index ) const { return ( *( getFunctionType()->getArgumentTypeTable() ) )[ index ]; }
  237. /// Return the vector storing the default argument values.
  238. const EngineFunctionDefaultArguments* getDefaultArguments() const { return mDefaultArgumentValues; }
  239. /// Reset all callout function pointers back to NULL. This deactivates all callbacks.
  240. static void resetAllCallouts();
  241. };
  242. ///
  243. ///
  244. /// Due to the given argument types and return type being directly used as is, it is not possible
  245. /// to use this macro with engine types that have more complex value passing semantics (like e.g.
  246. /// String). Use engineAPI in this case.
  247. ///
  248. /// @note The method of defining functions exposed by this macro is very low-level. To more
  249. /// conveniently define API functions and methods, use the facilities provided in engineAPI.h.
  250. ///
  251. /// @see engineAPI.h
  252. #define DEFINE_CALLIN( bindingName, exportName, scope, returnType, args, defaultArgs, flags, doc ) \
  253. TORQUE_API returnType bindingName args; \
  254. namespace { namespace _ ## bindingName { \
  255. _EngineFunctionDefaultArguments< void args > sDefaultArgs defaultArgs; \
  256. EngineFunctionInfo sFunctionInfo( \
  257. #exportName, \
  258. &_SCOPE< scope >()(), \
  259. doc, \
  260. #returnType " " #exportName #args, \
  261. #bindingName, \
  262. TYPE< returnType args >(), \
  263. &sDefaultArgs, \
  264. ( void* ) &bindingName, \
  265. _EngineFunctionFlags( flags ) \
  266. ); \
  267. } } \
  268. TORQUE_API returnType bindingName args
  269. ///
  270. ///
  271. /// Not all control layers may be able to access data variables in a DLL so this macro exposes
  272. /// both the variable and a set_XXX function to set the variable programmatically.
  273. #define DEFINE_CALLOUT( bindingName, exportName, scope, returnType, args, flags, doc ) \
  274. TORQUE_API returnType ( *bindingName ) args; \
  275. TORQUE_API void set_ ## bindingName( returnType ( *fn ) args ) \
  276. { bindingName = fn; } \
  277. returnType ( *bindingName ) args; \
  278. namespace { \
  279. ::EngineFunctionInfo _cb ## bindingName( \
  280. #exportName, \
  281. &::_SCOPE< scope >()(), \
  282. doc, \
  283. #returnType " " #exportName #args, \
  284. #bindingName, \
  285. ::TYPE< returnType args >(), \
  286. NULL, \
  287. ( void* ) &bindingName, \
  288. EngineFunctionCallout | EngineFunctionFlags( flags ) \
  289. ); \
  290. }
  291. #endif // !_ENGINEFUNCTIONS_H_