create_lua_library.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. import sys
  2. import CppHeaderParser
  3. import os
  4. import errno
  5. import re
  6. from zipfile import *
  7. import fnmatch
  8. import re
  9. def mkdir_p(path): # Same effect as mkdir -p, create dir and all necessary parent dirs
  10. try:
  11. os.makedirs(path)
  12. except OSError as e:
  13. if e.errno == errno.EEXIST: # Dir already exists; not really an error
  14. pass
  15. else: raise
  16. def template_returnPtrLookupArray(prefix, className, ptr):
  17. out = ""
  18. out += "%sfor i=1,count(%s) do\n" % (prefix, ptr)
  19. out += "%s\tlocal __c = _G[%s](\"__skip_ptr__\")\n" % (prefix, className)
  20. out += "%s\t__c.__ptr = %s[i]\n" % (prefix, ptr)
  21. out += "%s\t%s[i] = __c\n" % (prefix, ptr)
  22. out += "%send\n" % (prefix)
  23. out += "%sreturn %s\n" % (prefix,ptr)
  24. return out
  25. # Note we expect className to be a valid string
  26. def template_returnPtrLookup(prefix, className, ptr):
  27. out = ""
  28. out += "%slocal __c = _G[%s](\"__skip_ptr__\")\n" % (prefix, className)
  29. out += "%s__c.__ptr = %s\n" % (prefix, ptr)
  30. out += "%sreturn __c\n" % (prefix)
  31. return out
  32. def template_quote(str):
  33. return "\"%s\"" % str;
  34. def cleanDocs(docs):
  35. return docs.replace("/*", "").replace("*/", "").replace("*", "").replace("\n", "").replace("\r", "").replace("::", ".").replace("\t", "")
  36. def toLuaType(t):
  37. return t.replace("void", "nil").replace("int", "Integer").replace("bool", "Boolean")
  38. # FIXME: Some "unsigned int *" functions are still being generated on the polycode API?
  39. def typeFilter(ty):
  40. ty = ty.replace("Polycode::", "")
  41. ty = ty.replace("std::", "")
  42. ty = ty.replace("const", "")
  43. ty = ty.replace("inline", "")
  44. ty = ty.replace("static", "")
  45. ty = ty.replace("virtual", "")
  46. ty = ty.replace("&", "")
  47. ty = re.sub(r'^.*\sint\s*$', 'int', ty) # eg "unsigned int"
  48. ty = re.sub(r'^.*\slong\s*$', 'int', ty)
  49. ty = re.sub(r'^.*\sshort\s*$', 'int', ty)
  50. ty = re.sub(r'^.*\sfloat\s*$', 'Number', ty)
  51. ty = re.sub(r'^.*\sdouble\s*$', 'Number', ty) # eg "long double"
  52. ty = ty.replace("unsigned", "int")
  53. ty = ty.replace("long", "int")
  54. ty = ty.replace("float", "Number")
  55. ty = ty.replace("double", "Number")
  56. ty = ty.replace(" ", "") # Not very safe!
  57. return ty
  58. def createLUABindings(inputPath, prefix, mainInclude, libSmallName, libName, apiPath, apiClassPath, includePath, sourcePath, luaDocPath, inheritInModuleFiles):
  59. wrappersHeaderOut = "" # Def: Global C++ *LUAWrappers.h
  60. cppRegisterOut = "" # Def: Global C++ *LUA.cpp
  61. cppLoaderOut = "" # Def: Global C++ *LUA.cpp
  62. luaDocOut = ""
  63. luaIndexOut = "" # Def: Global Lua everything-gets-required-from-this-file file
  64. # Header boilerplate for wrappersHeaderOut and cppRegisterOut
  65. cppRegisterOut += "#include \"%sLUA.h\"\n" % (prefix)
  66. cppRegisterOut += "#include \"%sLUAWrappers.h\"\n" % (prefix)
  67. cppRegisterOut += "#include \"PolyCoreServices.h\"\n\n"
  68. cppRegisterOut += "using namespace Polycode;\n\n"
  69. cppRegisterOut += "int luaopen_%s(lua_State *L) {\n" % (prefix)
  70. # if prefix != "Polycode":
  71. # cppRegisterOut += "CoreServices *inst = (CoreServices*) *((void**)lua_touserdata(L, 1));\n"
  72. # cppRegisterOut += "CoreServices::setInstance(inst);\n"
  73. cppRegisterOut += "\tstatic const struct luaL_reg %sLib [] = {" % (libSmallName)
  74. wrappersHeaderOut += "#pragma once\n\n"
  75. wrappersHeaderOut += "extern \"C\" {\n\n"
  76. wrappersHeaderOut += "#include <stdio.h>\n"
  77. wrappersHeaderOut += "#include \"lua.h\"\n"
  78. wrappersHeaderOut += "#include \"lualib.h\"\n"
  79. wrappersHeaderOut += "#include \"lauxlib.h\"\n"
  80. wrappersHeaderOut += "} // extern \"C\" \n\n"
  81. luaDocOut += "<?xml version=\"1.0\" ?>\n"
  82. luaDocOut += "<docs>\n"
  83. luaDocOut += "<classes>\n"
  84. # Get list of headers to create bindings from
  85. inputPathIsDir = os.path.isdir(inputPath)
  86. if inputPathIsDir:
  87. files = os.listdir(inputPath)
  88. else:
  89. files = []
  90. with open(inputPath) as f:
  91. for line in f.readlines():
  92. files.append(line.strip()) # Strip whitespace, path/
  93. filteredFiles = []
  94. for fileName in files:
  95. if inputPathIsDir:
  96. fileName = "%s/%s" % (inputPath, fileName)
  97. head, tail = os.path.split(fileName)
  98. ignore = ["PolyGLSLProgram", "PolyGLSLShader", "PolyGLSLShaderModule", "PolyWinCore", "PolyCocoaCore", "PolyAGLCore", "PolySDLCore", "Poly_iPhone", "PolyGLES1Renderer", "PolyGLRenderer", "tinyxml", "tinystr", "OpenGLCubemap", "PolyiPhoneCore", "PolyGLES1Texture", "PolyGLTexture", "PolyGLVertexBuffer", "PolyThreaded", "PolyGLHeaders", "GLee", "PolyPeer", "PolySocket", "PolyClient", "PolyServer", "PolyServerWorld", "OSFILE", "OSFileEntry", "OSBasics", "PolyLogger"]
  99. if tail.split(".")[1] == "h" and tail.split(".")[0] not in ignore:
  100. filteredFiles.append(fileName)
  101. wrappersHeaderOut += "#include \"%s\"\n" % (tail)
  102. wrappersHeaderOut += "\nusing namespace std;\n\n"
  103. wrappersHeaderOut += "\nnamespace Polycode {\n\n"
  104. # list of classes that don't get the garbage collection in their meta table
  105. disable_gc = ["Entity", "ScreenEntity", "ScreenShape", "ScreenMesh", "ScreenLabel", "SceneLabel", "SceneMesh", "Screen", "Scene", "Texture", "Image", "Camera", "ScreenParticleEmitter", "SceneParticleEmitter", "Mesh", "Vertex", "Polygon", "Polycode::Polygon", "Material", "ScenePrimitive", "SceneLine", "SceneLight", "SceneSound", "ScreenImage", "SceneEntity"]
  106. # Special case: If we are building the Polycode library itself, inject the LuaEventHandler class.
  107. # Note: so that event callbacks can work, any object inheriting from EventHandler will secretly
  108. # be modified to actually inherit from LuaEventHandler instead.
  109. if prefix == "Polycode":
  110. wrappersHeaderOut += "class LuaEventHandler : public EventHandler {\n"
  111. wrappersHeaderOut += "public:\n"
  112. wrappersHeaderOut += " LuaEventHandler() : EventHandler() {}\n"
  113. wrappersHeaderOut += " void handleEvent(Event *e) {\n"
  114. wrappersHeaderOut += " lua_getfield (L, LUA_GLOBALSINDEX, \"__customError\");\n"
  115. wrappersHeaderOut += " int errH = lua_gettop(L);\n"
  116. wrappersHeaderOut += " lua_getfield(L, LUA_GLOBALSINDEX, \"__handleEvent\");\n"
  117. wrappersHeaderOut += " lua_rawgeti( L, LUA_REGISTRYINDEX, wrapperIndex );\n"
  118. wrappersHeaderOut += " PolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  119. wrappersHeaderOut += " *userdataPtr = (PolyBase*)e;\n"
  120. wrappersHeaderOut += " lua_pcall(L, 2, 0, errH);\n"
  121. wrappersHeaderOut += " lua_settop(L, 0);\n"
  122. wrappersHeaderOut += " }\n"
  123. wrappersHeaderOut += " int wrapperIndex;\n"
  124. wrappersHeaderOut += " lua_State *L;\n"
  125. wrappersHeaderOut += "};\n\n"
  126. # Iterate, process each input file
  127. for fileName in filteredFiles:
  128. # "Package owned" classes that ship with Polycode
  129. inheritInModule = ["PhysicsSceneEntity", "CollisionScene", "CollisionSceneEntity", "UIElement", "UIWindow"]
  130. # A file or comma-separated list of files can be given to specify classes which are "package owned"
  131. # and should not be inherited out of Polycode/. The files should contain one class name per line,
  132. # and the class name may be prefixed with a path (which will be ignored).
  133. if inheritInModuleFiles:
  134. for moduleFileName in inheritInModuleFiles.split(","):
  135. with open(moduleFileName) as f:
  136. for line in f.readlines():
  137. inheritInModule.append(line.strip().split("/",1)[-1]) # Strip whitespace, path/
  138. print("Parsing %s" % fileName)
  139. try: # One input file parse.
  140. f = open(fileName) # Def: Input file handle
  141. contents = f.read().replace("_PolyExport", "") # Def: Input file contents, strip out "_PolyExport"
  142. cppHeader = CppHeaderParser.CppHeader(contents, "string") # Def: Input file contents, parsed structure
  143. ignore_classes = ["PolycodeShaderModule", "Object", "Threaded", "OpenGLCubemap", "PolyBase"]
  144. # Iterate, check each class in this file.
  145. for ckey in cppHeader.classes:
  146. print(">> Parsing class %s" % ckey)
  147. c = cppHeader.classes[ckey] # Def: The class structure
  148. luaClassBindingOut = "" # Def: The local lua file to generate for this class.
  149. inherits = False
  150. parentClass = ""
  151. if len(c["inherits"]) > 0: # Does this class have parents?
  152. if c["inherits"][0]["class"] not in ignore_classes:
  153. if c["inherits"][0]["class"] in inheritInModule: # Parent class is in this module
  154. luaClassBindingOut += "require \"%s/%s\"\n\n" % (prefix, c["inherits"][0]["class"])
  155. else: # Parent class is in Polycore
  156. luaClassBindingOut += "require \"Polycode/%s\"\n\n" % (c["inherits"][0]["class"])
  157. if (ckey == "ScreenParticleEmitter" or ckey == "SceneParticleEmitter"):
  158. luaClassBindingOut += "require \"Polycode/ParticleEmitter\"\n\n"
  159. luaClassBindingOut += "class \"%s\" (%s)\n\n" % (ckey, c["inherits"][0]["class"])
  160. parentClass = c["inherits"][0]["class"]
  161. inherits = True
  162. if inherits == False: # Class does not have parents
  163. luaClassBindingOut += "class \"%s\"\n\n" % ckey
  164. if ckey in ignore_classes:
  165. continue
  166. if len(c["methods"]["public"]) < 2: # Used to, this was a continue.
  167. print("Warning: Lua-binding class with less than two methods")
  168. continue # FIXME: Remove this, move any non-compileable classes into ignore_classes
  169. extendString = ""
  170. if len(c["inherits"]) > 0:
  171. if c["inherits"][0]["class"] != "PolyBase":
  172. extendString = " extends=\"%s\"" % (c["inherits"][0]["class"])
  173. luaDocOut += "\t<class name=\"%s\"%s>\n" % (ckey, extendString)
  174. if 'doxygen' in c:
  175. luaDocOut += "\t\t<desc><![CDATA[%s]]></desc>\n" % (cleanDocs(c['doxygen']))
  176. parsed_methods = [] # Def: List of discovered methods
  177. ignore_methods = ["readByte32", "readByte16", "getCustomEntitiesByType", "Core", "Renderer", "Shader", "Texture", "handleEvent", "secondaryHandler", "getSTLString"]
  178. luaClassBindingOut += "\n\n"
  179. luaDocOut += "\t\t<static_members>\n"
  180. classProperties = [] # Def: List of found property structures ("properties" meaning "data members")
  181. for pp in c["properties"]["public"]:
  182. pp["type"] = pp["type"].replace("Polycode::", "")
  183. pp["type"] = pp["type"].replace("std::", "")
  184. if pp["type"].find("POLYIGNORE") != -1:
  185. continue
  186. if pp["type"].find("static ") != -1: # If static. FIXME: Static doesn't work?
  187. if "defaltValue" in pp: # FIXME: defaltValue is misspelled.
  188. defaltValue = pp["defaltValue"]
  189. # The "Default Value" is more or less a literal C++ string. This causes a problem:
  190. # Frequently we say static const int A = 1; static const int B = A + 1.
  191. # Put in a one-off hack to ensure namespacing works in this special case.
  192. if re.match(r'\s*[a-zA-Z_][a-zA-Z0-9_]*\s*\+', defaltValue):
  193. defaltValue = "%s.%s" % (ckey, defaltValue)
  194. luaClassBindingOut += "%s.%s = %s\n" % (ckey, pp["name"], defaltValue)
  195. luaDocOut += "\t\t\t<static_member name=\"%s\" type=\"%s\" value=\"%s\">\n" % (pp["name"], toLuaType(typeFilter(pp["type"])), pp["defaltValue"])
  196. if 'doxygen' in pp:
  197. luaDocOut += "\t\t\t\t<desc><![CDATA[%s]]></desc>\n" % (cleanDocs(pp['doxygen']))
  198. luaDocOut += "\t\t\t</static_member>\n"
  199. else: # FIXME: Nonstatic method ? variable ?? found.
  200. #there are some bugs in the class parser that cause it to return junk
  201. if pp["type"].find("*") == -1 and pp["type"].find("vector") == -1 and pp["name"] != "setScale" and pp["name"] != "setPosition" and pp["name"] != "BUFFER_CACHE_PRECISION" and not pp["name"].isdigit():
  202. classProperties.append(pp)
  203. luaDocOut += "\t\t</static_members>\n"
  204. # Iterate over properties, creating getters
  205. pidx = 0 # Def: Count of properties processed so far
  206. # TODO: Remove or generalize ParticleEmitter special casing. These lines are marked with #SPEC
  207. luaDocOut += "\t\t<members>\n"
  208. numGetVars = 0
  209. if len(classProperties) > 0: # If there are properties, add index lookup to the metatable
  210. luaClassBindingOut += "function %s:__getvar(name)\n" % ckey
  211. # Iterate over property structures, creating if/else clauses for each.
  212. # TODO: Could a table be more appropriate for
  213. for pp in classProperties:
  214. if pp["name"] == "" or pp["array"] == 1:
  215. continue
  216. numGetVars = numGetVars + 1
  217. pp["type"] = typeFilter(pp["type"])
  218. if pidx == 0:
  219. luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  220. else:
  221. luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  222. # Generate Lua side of binding:
  223. # If type is a primitive such as Number/String/int/bool
  224. if pp["type"] == "PolyKEY" or pp["type"] == "Number" or pp["type"] == "String" or pp["type"] == "int" or pp["type"] == "bool":
  225. luaClassBindingOut += "\t\treturn %s.%s_get_%s(self.__ptr)\n" % (libName, ckey, pp["name"])
  226. # If type is a particle emitter, specifically #SPEC
  227. elif (ckey == "ScreenParticleEmitter" or ckey == "SceneParticleEmitter") and pp["name"] == "emitter":
  228. luaClassBindingOut += "\t\tlocal ret = %s(\"__skip_ptr__\")\n" % (pp["type"])
  229. luaClassBindingOut += "\t\tret.__ptr = self.__ptr\n"
  230. luaClassBindingOut += "\t\treturn ret\n"
  231. # If type is a class
  232. else:
  233. luaClassBindingOut += "\t\tlocal retVal = %s.%s_get_%s(self.__ptr)\n" % (libName, ckey, pp["name"])
  234. luaClassBindingOut += template_returnPtrLookup("\t\t", template_quote(pp["type"]), "retVal")
  235. luaDocOut += "\t\t\t<member name=\"%s\" type=\"%s\">\n" % (pp["name"], toLuaType(typeFilter(pp["type"])))
  236. if 'doxygen' in pp:
  237. luaDocOut += "\t\t\t\t<desc><![CDATA[%s]]></desc>\n" % (cleanDocs(pp['doxygen']))
  238. luaDocOut += "\t\t\t</member>\n"
  239. # Generate C++ side of binding:
  240. if not ((ckey == "ScreenParticleEmitter" or ckey == "SceneParticleEmitter") and pp["name"] == "emitter"): #SPEC
  241. cppRegisterOut += "\t\t{\"%s_get_%s\", %s_%s_get_%s},\n" % (ckey, pp["name"], libName, ckey, pp["name"])
  242. wrappersHeaderOut += "static int %s_%s_get_%s(lua_State *L) {\n" % (libName, ckey, pp["name"])
  243. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  244. wrappersHeaderOut += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (ckey, ckey)
  245. outfunc = "this_shouldnt_happen"
  246. retFunc = ""
  247. if pp["type"] == "Number":
  248. outfunc = "lua_pushnumber"
  249. if pp["type"] == "String":
  250. outfunc = "lua_pushstring"
  251. retFunc = ".c_str()"
  252. if pp["type"] == "int" or pp["type"] == "PolyKEY":
  253. outfunc = "lua_pushinteger"
  254. if pp["type"] == "bool":
  255. outfunc = "lua_pushboolean"
  256. if pp["type"] == "Number" or pp["type"] == "String" or pp["type"] == "int" or pp["type"] == "bool" or pp["type"] == "PolyKEY":
  257. wrappersHeaderOut += "\t%s(L, inst->%s%s);\n" % (outfunc, pp["name"], retFunc)
  258. else:
  259. wrappersHeaderOut += "\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  260. wrappersHeaderOut += "\t*userdataPtr = (PolyBase*)&inst->%s%s;\n" % (pp["name"], retFunc)
  261. wrappersHeaderOut += "\treturn 1;\n"
  262. wrappersHeaderOut += "}\n\n"
  263. # Success
  264. pidx = pidx + 1
  265. if numGetVars != 0:
  266. luaClassBindingOut += "\tend\n"
  267. if inherits:
  268. luaClassBindingOut += "\tif %s[\"__getvar\"] ~= nil then\n" % (parentClass)
  269. luaClassBindingOut += "\t\treturn %s.__getvar(self, name)\n" % (parentClass)
  270. luaClassBindingOut += "\tend\n"
  271. luaClassBindingOut += "end\n"
  272. luaDocOut += "\t\t</members>\n"
  273. luaClassBindingOut += "\n\n"
  274. # Iterate over properties again, creating setters
  275. pidx = 0 # Def: Count of
  276. if len(classProperties) > 0: # If there are properties, add index setter to the metatable
  277. luaClassBindingOut += "function %s:__setvar(name,value)\n" % ckey
  278. for pp in classProperties:
  279. if pp["name"] == "" or pp["array"] == 1:
  280. continue
  281. pp["type"] = typeFilter(pp["type"])
  282. # If type is a primitive: Create lua and C++ sides at the same time.
  283. if pp["type"] == "Number" or pp["type"] == "String" or pp["type"] == "int" or pp["type"] == "bool" or pp["type"] == "PolyKEY":
  284. if pidx == 0:
  285. luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  286. else:
  287. luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  288. luaClassBindingOut += "\t\t%s.%s_set_%s(self.__ptr, value)\n" % (libName, ckey, pp["name"])
  289. luaClassBindingOut += "\t\treturn true\n"
  290. cppRegisterOut += "\t\t{\"%s_set_%s\", %s_%s_set_%s},\n" % (ckey, pp["name"], libName, ckey, pp["name"])
  291. wrappersHeaderOut += "static int %s_%s_set_%s(lua_State *L) {\n" % (libName, ckey, pp["name"])
  292. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  293. wrappersHeaderOut += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (ckey, ckey)
  294. outfunc = "this_shouldnt_happen"
  295. if pp["type"] == "Number":
  296. outfunc = "lua_tonumber"
  297. if pp["type"] == "String":
  298. outfunc = "lua_tostring"
  299. if pp["type"] == "int":
  300. outfunc = "lua_tointeger"
  301. if pp["type"] == "PolyKEY":
  302. outfunc = "(PolyKEY)lua_tointeger"
  303. if pp["type"] == "bool":
  304. outfunc = "lua_toboolean"
  305. wrappersHeaderOut += "\t%s param = %s(L, 2);\n" % (pp["type"], outfunc)
  306. wrappersHeaderOut += "\tinst->%s = param;\n" % (pp["name"])
  307. wrappersHeaderOut += "\treturn 0;\n"
  308. wrappersHeaderOut += "}\n\n"
  309. pidx = pidx + 1 # Success
  310. else:
  311. if pp["type"].find("*") == -1 and pp["type"].find("static") == -1:
  312. if pidx == 0:
  313. luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  314. else:
  315. luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  316. luaClassBindingOut += "\t\t%s.%s_set_%s(self.__ptr, value.__ptr)\n" % (libName, ckey, pp["name"])
  317. luaClassBindingOut += "\t\treturn true\n"
  318. cppRegisterOut += "\t\t{\"%s_set_%s\", %s_%s_set_%s},\n" % (ckey, pp["name"], libName, ckey, pp["name"])
  319. wrappersHeaderOut += "static int %s_%s_set_%s(lua_State *L) {\n" % (libName, ckey, pp["name"])
  320. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  321. wrappersHeaderOut += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (ckey, ckey)
  322. wrappersHeaderOut += "\tluaL_checktype(L, 2, LUA_TUSERDATA);\n"
  323. wrappersHeaderOut += "\t%s *argInst = (%s*) *((PolyBase**)lua_touserdata(L, 2));\n" % (typeFilter(pp["type"]), typeFilter(pp["type"]))
  324. wrappersHeaderOut += "\tinst->%s = *argInst;\n" % (pp["name"])
  325. wrappersHeaderOut += "\treturn 0;\n"
  326. wrappersHeaderOut += "}\n\n"
  327. pidx = pidx + 1 # Success
  328. # Notice: Setters for object types are not created.
  329. if pidx != 0:
  330. luaClassBindingOut += "\tend\n"
  331. if inherits:
  332. luaClassBindingOut += "\tif %s[\"__setvar\"] ~= nil then\n" % (parentClass)
  333. luaClassBindingOut += "\t\treturn %s.__setvar(self, name, value)\n" % (parentClass)
  334. luaClassBindingOut += "\telse\n"
  335. luaClassBindingOut += "\t\treturn false\n"
  336. luaClassBindingOut += "\tend\n"
  337. else:
  338. luaClassBindingOut += "\treturn false\n"
  339. luaClassBindingOut += "end\n"
  340. # Iterate over methods
  341. luaClassBindingOut += "\n\n"
  342. luaDocOut += "\t\t<methods>\n"
  343. for pm in c["methods"]["public"]:
  344. # Skip argument-overloaded methods and operators.
  345. # TODO: Instead of skipping arguemnt overloads, have special behavior.
  346. # TODO: Instead of skipping operators, add to metatable.
  347. if pm["name"] in parsed_methods or pm["name"].find("operator") > -1 or pm["rtnType"].find("POLYIGNORE") > -1 or pm["name"] in ignore_methods:
  348. continue
  349. # Skip destructors and methods which return templates.
  350. # TODO: Special-case certain kind of vector<>s?
  351. if pm["name"] == "~"+ckey or pm["name"] == "CoreServices":
  352. continue
  353. staticString = ""
  354. if pm["rtnType"].find("static ") != -1:
  355. staticString = " static=\"true\""
  356. if pm["rtnType"].find("std::vector") > -1:
  357. vectorReturnClass = pm["rtnType"].replace("std::vector<", "").replace(">","").replace(" ", "")
  358. luaDocOut += "\t\t\t<method name=\"%s\" return_array=\"true\" return_type=\"%s\"%s>\n" % (pm["name"], toLuaType(typeFilter(vectorReturnClass).replace("*", "")), staticString)
  359. else:
  360. luaDocOut += "\t\t\t<method name=\"%s\" return_type=\"%s\"%s>\n" % (pm["name"], toLuaType(typeFilter(pm["rtnType"].replace("*", ""))), staticString)
  361. docs = None
  362. if 'doxygen' in pm:
  363. if pm['doxygen'].find("@return") > -1:
  364. docs = cleanDocs(pm['doxygen']).split("@return")[0].split("@param")
  365. else:
  366. docs = cleanDocs(pm['doxygen']).split("@param")
  367. luaDocOut += "\t\t\t\t<desc><![CDATA[%s]]></desc>\n" % (docs[0])
  368. if len(pm["parameters"]) > 0:
  369. luaDocOut += "\t\t\t\t<params>\n"
  370. paramIndex = 0
  371. for param in pm["parameters"]:
  372. if "name" in param:
  373. if not "type" in param:
  374. continue
  375. if param["type"] == "0":
  376. continue
  377. if param["type"].find("vector<") != -1:
  378. vectorClass = param["type"].replace("std::vector<", "").replace(">","").replace(" ", "")
  379. luaDocOut += "\t\t\t\t\t<param name=\"%s\" param_array=\"true\" type=\"%s\">\n" % (param["name"], toLuaType(vectorClass.replace("*","")))
  380. else:
  381. luaDocOut += "\t\t\t\t\t<param name=\"%s\" type=\"%s\">\n" % (param["name"], toLuaType(typeFilter(param["type"]).replace("*","")))
  382. if docs != None:
  383. if len(docs) > paramIndex+1:
  384. cdoc = docs[paramIndex+1].split()
  385. cdoc.pop(0)
  386. luaDocOut += "\t\t\t\t\t\t<desc><![CDATA[%s]]></desc>\n" % (" ".join(cdoc).replace("\n", ""))
  387. luaDocOut += "\t\t\t\t\t</param>\n"
  388. paramIndex = paramIndex + 1
  389. luaDocOut += "\t\t\t\t</params>\n"
  390. luaDocOut += "\t\t\t</method>\n"
  391. basicType = False
  392. voidRet = False
  393. vectorReturn = False
  394. vectorReturnClass = ""
  395. # Def: True if method takes a lua_State* as argument (i.e.: no preprocessing by us)
  396. rawMethod = len(pm["parameters"]) > 0 and pm["parameters"][0].get("type","").find("lua_State") > -1
  397. # Basic setup, C++ side: Add function to registry and start building wrapper function.
  398. if pm["name"] == ckey: # It's a constructor
  399. cppRegisterOut += "\t\t{\"%s\", %s_%s},\n" % (ckey, libName, ckey)
  400. wrappersHeaderOut += "static int %s_%s(lua_State *L) {\n" % (libName, ckey)
  401. idx = 1 # Def: Current stack depth (TODO: Figure out, is this correct?)
  402. else: # It's not a constructor
  403. cppRegisterOut += "\t\t{\"%s_%s\", %s_%s_%s},\n" % (ckey, pm["name"], libName, ckey, pm["name"])
  404. wrappersHeaderOut += "static int %s_%s_%s(lua_State *L) {\n" % (libName, ckey, pm["name"])
  405. # Skip static methods (TODO: Figure out, why is this being done here?). # FIXME
  406. if pm["rtnType"].find("static ") == -1:
  407. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  408. wrappersHeaderOut += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (ckey, ckey)
  409. idx = 2
  410. else:
  411. idx = 1
  412. if rawMethod:
  413. wrappersHeaderOut += "\treturn inst->%s(L);\n" % (pm["name"])
  414. else:
  415. # Generate C++ side parameter pushing
  416. paramlist = []
  417. lparamlist = []
  418. for param in pm["parameters"]:
  419. if not "type" in param:
  420. continue
  421. if param["type"] == "0":
  422. continue
  423. param["type"] = typeFilter(param["type"])
  424. param["name"] = param["name"].replace("end", "_end").replace("repeat", "_repeat")
  425. if"type" in param:
  426. luatype = "LUA_TUSERDATA"
  427. checkfunc = "lua_isuserdata"
  428. if param["type"].find("*") > -1:
  429. luafunc = "(%s) *((PolyBase**)lua_touserdata" % (param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  430. elif param["type"].find("&") > -1:
  431. luafunc = "*(%s*) *((PolyBase**)lua_touserdata" % (param["type"].replace("const", "").replace("&", "").replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  432. else:
  433. luafunc = "*(%s*) *((PolyBase**)lua_touserdata" % (param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  434. lend = ".__ptr"
  435. luafuncsuffix = ")"
  436. if param["type"] == "int" or param["type"] == "unsigned int" or param["type"] == "short":
  437. luafunc = "lua_tointeger"
  438. luatype = "LUA_TNUMBER"
  439. checkfunc = "lua_isnumber"
  440. luafuncsuffix = ""
  441. lend = ""
  442. if param["type"] == "PolyKEY":
  443. luafunc = "(PolyKEY)lua_tointeger"
  444. luatype = "LUA_TNUMBER"
  445. checkfunc = "lua_isnumber"
  446. luafuncsuffix = ""
  447. lend = ""
  448. if param["type"] == "bool":
  449. luafunc = "lua_toboolean"
  450. luatype = "LUA_TBOOLEAN"
  451. checkfunc = "lua_isboolean"
  452. luafuncsuffix = ""
  453. lend = ""
  454. if param["type"] == "Number" or param["type"] == "float" or param["type"] == "double":
  455. luatype = "LUA_TNUMBER"
  456. luafunc = "lua_tonumber"
  457. checkfunc = "lua_isnumber"
  458. luafuncsuffix = ""
  459. lend = ""
  460. if param["type"] == "String":
  461. luatype = "LUA_TSTRING"
  462. luafunc = "lua_tostring"
  463. checkfunc = "lua_isstring"
  464. luafuncsuffix = ""
  465. lend = ""
  466. param["type"] = param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle")
  467. if "defaltValue" in param:
  468. if checkfunc != "lua_isuserdata" or (checkfunc == "lua_isuserdata" and param["defaltValue"] == "NULL"):
  469. #param["defaltValue"] = param["defaltValue"].replace(" 0f", ".0f")
  470. param["defaltValue"] = param["defaltValue"].replace(": :", "::")
  471. #param["defaltValue"] = param["defaltValue"].replace("0 ", "0.")
  472. param["defaltValue"] = re.sub(r'([0-9]+) ([0-9])+', r'\1.\2', param["defaltValue"])
  473. wrappersHeaderOut += "\t%s %s;\n" % (param["type"], param["name"])
  474. wrappersHeaderOut += "\tif(%s(L, %d)) {\n" % (checkfunc, idx)
  475. wrappersHeaderOut += "\t\t%s = %s(L, %d)%s;\n" % (param["name"], luafunc, idx, luafuncsuffix)
  476. wrappersHeaderOut += "\t} else {\n"
  477. wrappersHeaderOut += "\t\t%s = %s;\n" % (param["name"], param["defaltValue"])
  478. wrappersHeaderOut += "\t}\n"
  479. else:
  480. wrappersHeaderOut += "\tluaL_checktype(L, %d, %s);\n" % (idx, luatype);
  481. if param["type"] == "String":
  482. wrappersHeaderOut += "\t%s %s = String(%s(L, %d));\n" % (param["type"], param["name"], luafunc, idx)
  483. else:
  484. wrappersHeaderOut += "\t%s %s = %s(L, %d)%s;\n" % (param["type"], param["name"], luafunc, idx,luafuncsuffix)
  485. else:
  486. wrappersHeaderOut += "\tluaL_checktype(L, %d, %s);\n" % (idx, luatype);
  487. if param["type"] == "String":
  488. wrappersHeaderOut += "\t%s %s = String(%s(L, %d));\n" % (param["type"], param["name"], luafunc, idx)
  489. else:
  490. wrappersHeaderOut += "\t%s %s = %s(L, %d)%s;\n" % (param["type"], param["name"], luafunc, idx, luafuncsuffix)
  491. paramlist.append(param["name"])
  492. lparamlist.append(param["name"]+lend)
  493. idx = idx +1 # Param parse success-- mark the increased stack
  494. # Generate C++-side method call / generate return value
  495. if pm["name"] == ckey: # If constructor
  496. if ckey == "EventHandler": # See LuaEventHandler above
  497. wrappersHeaderOut += "\tLuaEventHandler *inst = new LuaEventHandler();\n"
  498. wrappersHeaderOut += "\tinst->wrapperIndex = luaL_ref(L, LUA_REGISTRYINDEX );\n"
  499. wrappersHeaderOut += "\tinst->L = L;\n"
  500. else:
  501. wrappersHeaderOut += "\t%s *inst = new %s(%s);\n" % (ckey, ckey, ", ".join(paramlist))
  502. wrappersHeaderOut += "\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  503. wrappersHeaderOut += "\t*userdataPtr = (PolyBase*)inst;\n"
  504. wrappersHeaderOut += "\tluaL_getmetatable(L, \"%s.%s\");\n" % (libName, ckey)
  505. wrappersHeaderOut += "\tlua_setmetatable(L, -2);\n"
  506. wrappersHeaderOut += "\treturn 1;\n"
  507. else: #If non-constructor
  508. if pm["rtnType"].find("static ") == -1: # If non-static
  509. call = "inst->%s(%s)" % (pm["name"], ", ".join(paramlist))
  510. else: # If static (FIXME: Why doesn't this work?)
  511. call = "%s::%s(%s)" % (ckey, pm["name"], ", ".join(paramlist))
  512. #check if returning a template
  513. if pm["rtnType"].find("<") > -1:
  514. #if returning a vector, convert to lua table
  515. if pm["rtnType"].find("std::vector") > -1:
  516. vectorReturnClass = pm["rtnType"].replace("std::vector<", "").replace(">","").replace(" ", "")
  517. if vectorReturnClass.find("&") == -1 and vectorReturnClass.find("*") > -1: #FIXME: return references to std::vectors and basic types
  518. vectorReturn = True
  519. wrappersHeaderOut += "\tstd::vector<%s> retVector = %s;\n" % (vectorReturnClass,call)
  520. wrappersHeaderOut += "\tlua_newtable(L);\n"
  521. wrappersHeaderOut += "\tfor(int i=0; i < retVector.size(); i++) {\n"
  522. wrappersHeaderOut += "\t\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  523. wrappersHeaderOut += "\t\t*userdataPtr = (PolyBase*)retVector[i];\n"
  524. wrappersHeaderOut += "\t\tlua_rawseti(L, -2, i+1);\n"
  525. wrappersHeaderOut += "\t}\n"
  526. wrappersHeaderOut += "\treturn 1;\n"
  527. else:
  528. wrappersHeaderOut += "\treturn 0;\n"
  529. # else If void-typed:
  530. elif pm["rtnType"] == "void" or pm["rtnType"] == "static void" or pm["rtnType"] == "virtual void" or pm["rtnType"] == "inline void":
  531. wrappersHeaderOut += "\t%s;\n" % (call)
  532. basicType = True
  533. voidRet = True
  534. vectorReturn = False
  535. wrappersHeaderOut += "\treturn 0;\n" # 0 arguments returned
  536. else: # If there is a return value:
  537. # What type is the return value? Default to pointer
  538. outfunc = "this_shouldnt_happen"
  539. retFunc = ""
  540. basicType = False
  541. vectorReturn = False
  542. if pm["rtnType"] == "Number" or pm["rtnType"] == "inline Number":
  543. outfunc = "lua_pushnumber"
  544. basicType = True
  545. if pm["rtnType"] == "String" or pm["rtnType"] == "static String": # TODO: Path for STL strings?
  546. outfunc = "lua_pushstring"
  547. basicType = True
  548. retFunc = ".c_str()"
  549. if pm["rtnType"] == "int" or pm["rtnType"] == "unsigned int" or pm["rtnType"] == "static int" or pm["rtnType"] == "size_t" or pm["rtnType"] == "static size_t" or pm["rtnType"] == "long" or pm["rtnType"] == "unsigned int" or pm["rtnType"] == "static long" or pm["rtnType"] == "short" or pm["rtnType"] == "PolyKEY":
  550. outfunc = "lua_pushinteger"
  551. basicType = True
  552. if pm["rtnType"] == "bool" or pm["rtnType"] == "static bool" or pm["rtnType"] == "virtual bool":
  553. outfunc = "lua_pushboolean"
  554. basicType = True
  555. if pm["rtnType"].find("*") > -1: # Returned var is definitely a pointer.
  556. wrappersHeaderOut += "\tPolyBase *ptrRetVal = (PolyBase*)%s%s;\n" % (call, retFunc)
  557. wrappersHeaderOut += "\tif(ptrRetVal == NULL) {\n"
  558. wrappersHeaderOut += "\t\tlua_pushnil(L);\n"
  559. wrappersHeaderOut += "\t} else {\n"
  560. wrappersHeaderOut += "\t\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  561. wrappersHeaderOut += "\t\t*userdataPtr = ptrRetVal;\n"
  562. wrappersHeaderOut += "\t}\n"
  563. elif basicType == True: # Returned var has been flagged as a recognized primitive type
  564. wrappersHeaderOut += "\t%s(L, %s%s);\n" % (outfunc, call, retFunc)
  565. else: # Some static object is being returned. Convert it to a pointer, then return that.
  566. className = pm["rtnType"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "")
  567. if className == "Polygon": # Deal with potential windows.h conflict
  568. className = "Polycode::Polygon"
  569. if className == "Rectangle":
  570. className = "Polycode::Rectangle"
  571. if className == "Polycode : : Rectangle":
  572. className = "Polycode::Rectangle"
  573. wrappersHeaderOut += "\t%s *retInst = new %s();\n" % (className, className)
  574. wrappersHeaderOut += "\t*retInst = %s;\n" % (call)
  575. wrappersHeaderOut += "\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  576. wrappersHeaderOut += "\tluaL_getmetatable(L, \"%s.%s\");\n" % (libName, className)
  577. wrappersHeaderOut += "\tlua_setmetatable(L, -2);\n"
  578. wrappersHeaderOut += "\t*userdataPtr = (PolyBase*)retInst;\n"
  579. wrappersHeaderOut += "\treturn 1;\n"
  580. wrappersHeaderOut += "}\n\n" # Close out C++ generation
  581. # Now generate the Lua side method.
  582. if rawMethod:
  583. luaClassBindingOut += "function %s:%s(...)\n" % (ckey, pm["name"])
  584. luaClassBindingOut += "\treturn %s.%s_%s(self.__ptr, ...)\n" % (libName, ckey, pm["name"])
  585. luaClassBindingOut += "end\n"
  586. elif pm["name"] == ckey: # Constructors
  587. luaClassBindingOut += "function %s:%s(...)\n" % (ckey, ckey)
  588. luaClassBindingOut += "\tlocal arg = {...}\n"
  589. if inherits:
  590. luaClassBindingOut += "\tif type(arg[1]) == \"table\" and count(arg) == 1 then\n"
  591. luaClassBindingOut += "\t\tif \"\"..arg[1].__classname == \"%s\" then\n" % (c["inherits"][0]["class"])
  592. luaClassBindingOut += "\t\t\tself.__ptr = arg[1].__ptr\n"
  593. luaClassBindingOut += "\t\t\treturn\n"
  594. luaClassBindingOut += "\t\tend\n"
  595. luaClassBindingOut += "\tend\n"
  596. luaClassBindingOut += "\tfor k,v in pairs(arg) do\n"
  597. luaClassBindingOut += "\t\tif type(v) == \"table\" then\n"
  598. luaClassBindingOut += "\t\t\tif v.__ptr ~= nil then\n"
  599. luaClassBindingOut += "\t\t\t\targ[k] = v.__ptr\n"
  600. luaClassBindingOut += "\t\t\tend\n"
  601. luaClassBindingOut += "\t\tend\n"
  602. luaClassBindingOut += "\tend\n"
  603. luaClassBindingOut += "\tif self.__ptr == nil and arg[1] ~= \"__skip_ptr__\" then\n"
  604. if ckey == "EventHandler": # See LuaEventHandler above
  605. luaClassBindingOut += "\t\tself.__ptr = %s.%s(self)\n" % (libName, ckey)
  606. else:
  607. luaClassBindingOut += "\t\tself.__ptr = %s.%s(unpack(arg))\n" % (libName, ckey)
  608. luaClassBindingOut += "\tend\n"
  609. luaClassBindingOut += "end\n\n"
  610. else: # Non-constructors.
  611. if pm["rtnType"].find("static ") == -1: # Non-static method
  612. luaClassBindingOut += "function %s:%s(%s)\n" % (ckey, pm["name"], ", ".join(paramlist))
  613. if len(lparamlist):
  614. luaClassBindingOut += "\tlocal retVal = %s.%s_%s(self.__ptr, %s)\n" % (libName, ckey, pm["name"], ", ".join(lparamlist))
  615. else:
  616. luaClassBindingOut += "\tlocal retVal = %s.%s_%s(self.__ptr)\n" % (libName, ckey, pm["name"])
  617. else: # Static method
  618. luaClassBindingOut += "function %s.%s(%s)\n" % (ckey, pm["name"], ", ".join(paramlist))
  619. if len(lparamlist):
  620. luaClassBindingOut += "\tlocal retVal = %s.%s_%s(%s)\n" % (libName, ckey, pm["name"], ", ".join(lparamlist))
  621. else:
  622. luaClassBindingOut += "\tlocal retVal = %s.%s_%s()\n" % (libName, ckey, pm["name"])
  623. if not voidRet: # Was there a return value?
  624. if basicType == True: # Yes, a primitive
  625. luaClassBindingOut += "\treturn retVal\n"
  626. else: # Yes, a pointer was returned
  627. luaClassBindingOut += "\tif retVal == nil then return nil end\n"
  628. if vectorReturn == True:
  629. className = vectorReturnClass.replace("*", "")
  630. luaClassBindingOut += template_returnPtrLookupArray("\t",template_quote(className),"retVal")
  631. else:
  632. className = pm["rtnType"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "").replace("*","").replace(" ", "")
  633. luaClassBindingOut += template_returnPtrLookup("\t",template_quote(className),"retVal")
  634. luaClassBindingOut += "end\n\n" # Close out Lua generation
  635. parsed_methods.append(pm["name"]) # Method parse success
  636. luaDocOut += "\t\t</methods>\n"
  637. # With methods out of the way, do some final cleanup:
  638. # user pointer metatable creation in C++
  639. cppLoaderOut += "\n\tluaL_newmetatable(L, \"%s.%s\");\n" % (libName, ckey)
  640. if ckey not in disable_gc:
  641. cppLoaderOut += "\tlua_pushstring(L, \"__gc\");\n"
  642. cppLoaderOut += "\tlua_pushcfunction(L, %s_delete_%s);\n" % (libName, ckey)
  643. cppLoaderOut += "\tlua_settable(L, -3);\n"
  644. cppLoaderOut +="\tlua_pop(L, 1);\n"
  645. # Delete method (C++ side)
  646. cppRegisterOut += "\t\t{\"delete_%s\", %s_delete_%s},\n" % (ckey, libName, ckey)
  647. wrappersHeaderOut += "static int %s_delete_%s(lua_State *L) {\n" % (libName, ckey)
  648. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  649. wrappersHeaderOut += "\tPolyBase **inst = (PolyBase**)lua_touserdata(L, 1);\n"
  650. wrappersHeaderOut += "\tdelete ((%s*) *inst);\n" % (ckey)
  651. wrappersHeaderOut += "\t*inst = NULL;\n"
  652. wrappersHeaderOut += "\treturn 0;\n"
  653. wrappersHeaderOut += "}\n\n"
  654. # Delete method (Lua side)
  655. luaClassBindingOut += "function %s:__delete()\n" % (ckey)
  656. luaClassBindingOut += "\tif self then %s.delete_%s(self.__ptr) end\n" % (libName, ckey)
  657. luaClassBindingOut += "end\n"
  658. # Add class to lua index file
  659. luaIndexOut += "require \"%s/%s\"\n" % (prefix, ckey)
  660. # Write lua file
  661. mkdir_p(apiClassPath)
  662. if ckey != "EventDispatcher":
  663. fout = open("%s/%s.lua" % (apiClassPath, ckey), "w")
  664. fout.write(luaClassBindingOut)
  665. luaDocOut += "\t</class>\n"
  666. except CppHeaderParser.CppParseError as e: # One input file parse; failed.
  667. print(e)
  668. sys.exit(1)
  669. luaDocOut += "</classes>\n"
  670. luaDocOut += "</docs>\n"
  671. # Footer boilerplate for wrappersHeaderOut and cppRegisterOut.
  672. wrappersHeaderOut += "} // namespace Polycode\n"
  673. cppRegisterOut += "\t\t{NULL, NULL}\n"
  674. cppRegisterOut += "\t};\n"
  675. cppRegisterOut += "\tluaL_openlib(L, \"%s\", %sLib, 0);\n" % (libName, libSmallName)
  676. cppRegisterOut += cppLoaderOut
  677. cppRegisterOut += "\treturn 1;\n"
  678. cppRegisterOut += "}"
  679. cppRegisterHeaderOut = "" # Def: Global C++ *LUA.h
  680. cppRegisterHeaderOut += "#pragma once\n"
  681. cppRegisterHeaderOut += "#include <%s>\n" % (mainInclude)
  682. cppRegisterHeaderOut += "extern \"C\" {\n"
  683. cppRegisterHeaderOut += "#include <stdio.h>\n"
  684. cppRegisterHeaderOut += "#include \"lua.h\"\n"
  685. cppRegisterHeaderOut += "#include \"lualib.h\"\n"
  686. cppRegisterHeaderOut += "#include \"lauxlib.h\"\n"
  687. cppRegisterHeaderOut += "int _PolyExport luaopen_%s(lua_State *L);\n" % (prefix)
  688. cppRegisterHeaderOut += "}\n"
  689. # Write out global files
  690. mkdir_p(includePath)
  691. mkdir_p(apiPath)
  692. mkdir_p(sourcePath)
  693. fout = open("%s/%sLUA.h" % (includePath, prefix), "w")
  694. fout.write(cppRegisterHeaderOut)
  695. if luaDocPath is None:
  696. luaDocPath = "../../../Documentation/Lua/xml"
  697. if luaDocPath != "-":
  698. fout = open("%s/%s.xml" % (luaDocPath, prefix), "w")
  699. fout.write(luaDocOut)
  700. fout = open("%s/%s.lua" % (apiPath, prefix), "w")
  701. fout.write(luaIndexOut)
  702. fout = open("%s/%sLUAWrappers.h" % (includePath, prefix), "w")
  703. fout.write(wrappersHeaderOut)
  704. fout = open("%s/%sLUA.cpp" % (sourcePath, prefix), "w")
  705. fout.write(cppRegisterOut)
  706. # Create .pak zip archive
  707. pattern = '*.lua'
  708. os.chdir(apiPath)
  709. if libName == "Polycore":
  710. with ZipFile("api.pak", 'w') as myzip:
  711. for root, dirs, files in os.walk("."):
  712. for filename in fnmatch.filter(files, pattern):
  713. myzip.write(os.path.join(root, filename))
  714. else:
  715. with ZipFile("%s.pak" % (libName), 'w') as myzip:
  716. for root, dirs, files in os.walk("."):
  717. for filename in fnmatch.filter(files, pattern):
  718. myzip.write(os.path.join(root, filename))
  719. if len(sys.argv) < 10:
  720. print ("Usage:\n%s [input path] [prefix] [main include] [lib small name] [lib name] [api path] [api class-path] [include path] [source path] [lua doc path (optional) (or - for omit)] [inherit-in-module-file path (optional)]" % (sys.argv[0]))
  721. sys.exit(1)
  722. else:
  723. createLUABindings(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7], sys.argv[8], sys.argv[9], sys.argv[10] if len(sys.argv)>10 else None, sys.argv[11] if len(sys.argv)>11 else None)