methods.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341
  1. import os
  2. from compat import iteritems, itervalues, open_utf8, escape_string
  3. def add_source_files(self, sources, filetype, lib_env=None, shared=False):
  4. import glob
  5. import string
  6. # if not lib_objects:
  7. if not lib_env:
  8. lib_env = self
  9. if type(filetype) == type(""):
  10. dir = self.Dir('.').abspath
  11. list = glob.glob(dir + "/" + filetype)
  12. for f in list:
  13. sources.append(self.Object(f))
  14. else:
  15. for f in filetype:
  16. sources.append(self.Object(f))
  17. class LegacyGLHeaderStruct:
  18. def __init__(self):
  19. self.vertex_lines = []
  20. self.fragment_lines = []
  21. self.uniforms = []
  22. self.attributes = []
  23. self.feedbacks = []
  24. self.fbos = []
  25. self.conditionals = []
  26. self.enums = {}
  27. self.texunits = []
  28. self.texunit_names = []
  29. self.ubos = []
  30. self.ubo_names = []
  31. self.vertex_included_files = []
  32. self.fragment_included_files = []
  33. self.reading = ""
  34. self.line_offset = 0
  35. self.vertex_offset = 0
  36. self.fragment_offset = 0
  37. def include_file_in_legacygl_header(filename, header_data, depth):
  38. fs = open(filename, "r")
  39. line = fs.readline()
  40. while(line):
  41. if (line.find("[vertex]") != -1):
  42. header_data.reading = "vertex"
  43. line = fs.readline()
  44. header_data.line_offset += 1
  45. header_data.vertex_offset = header_data.line_offset
  46. continue
  47. if (line.find("[fragment]") != -1):
  48. header_data.reading = "fragment"
  49. line = fs.readline()
  50. header_data.line_offset += 1
  51. header_data.fragment_offset = header_data.line_offset
  52. continue
  53. while(line.find("#include ") != -1):
  54. includeline = line.replace("#include ", "").strip()[1:-1]
  55. import os.path
  56. included_file = os.path.relpath(os.path.dirname(filename) + "/" + includeline)
  57. if (not included_file in header_data.vertex_included_files and header_data.reading == "vertex"):
  58. header_data.vertex_included_files += [included_file]
  59. if(include_file_in_legacygl_header(included_file, header_data, depth + 1) == None):
  60. print("Error in file '" + filename + "': #include " + includeline + "could not be found!")
  61. elif (not included_file in header_data.fragment_included_files and header_data.reading == "fragment"):
  62. header_data.fragment_included_files += [included_file]
  63. if(include_file_in_legacygl_header(included_file, header_data, depth + 1) == None):
  64. print("Error in file '" + filename + "': #include " + includeline + "could not be found!")
  65. line = fs.readline()
  66. if (line.find("#ifdef ") != -1 or line.find("#elif defined(") != -1):
  67. if (line.find("#ifdef ") != -1):
  68. ifdefline = line.replace("#ifdef ", "").strip()
  69. else:
  70. ifdefline = line.replace("#elif defined(", "").strip()
  71. ifdefline = ifdefline.replace(")", "").strip()
  72. if (line.find("_EN_") != -1):
  73. enumbase = ifdefline[:ifdefline.find("_EN_")]
  74. ifdefline = ifdefline.replace("_EN_", "_")
  75. line = line.replace("_EN_", "_")
  76. if (enumbase not in header_data.enums):
  77. header_data.enums[enumbase] = []
  78. if (ifdefline not in header_data.enums[enumbase]):
  79. header_data.enums[enumbase].append(ifdefline)
  80. elif (not ifdefline in header_data.conditionals):
  81. header_data.conditionals += [ifdefline]
  82. if (line.find("uniform") != -1 and line.lower().find("texunit:") != -1):
  83. # texture unit
  84. texunitstr = line[line.find(":") + 1:].strip()
  85. if (texunitstr == "auto"):
  86. texunit = "-1"
  87. else:
  88. texunit = str(int(texunitstr))
  89. uline = line[:line.lower().find("//")]
  90. uline = uline.replace("uniform", "")
  91. uline = uline.replace("highp", "")
  92. uline = uline.replace(";", "")
  93. lines = uline.split(",")
  94. for x in lines:
  95. x = x.strip()
  96. x = x[x.rfind(" ") + 1:]
  97. if (x.find("[") != -1):
  98. # unfiorm array
  99. x = x[:x.find("[")]
  100. if (not x in header_data.texunit_names):
  101. header_data.texunits += [(x, texunit)]
  102. header_data.texunit_names += [x]
  103. elif (line.find("uniform") != -1 and line.lower().find("ubo:") != -1):
  104. # uniform buffer object
  105. ubostr = line[line.find(":") + 1:].strip()
  106. ubo = str(int(ubostr))
  107. uline = line[:line.lower().find("//")]
  108. uline = uline[uline.find("uniform") + len("uniform"):]
  109. uline = uline.replace("highp", "")
  110. uline = uline.replace(";", "")
  111. uline = uline.replace("{", "").strip()
  112. lines = uline.split(",")
  113. for x in lines:
  114. x = x.strip()
  115. x = x[x.rfind(" ") + 1:]
  116. if (x.find("[") != -1):
  117. # unfiorm array
  118. x = x[:x.find("[")]
  119. if (not x in header_data.ubo_names):
  120. header_data.ubos += [(x, ubo)]
  121. header_data.ubo_names += [x]
  122. elif (line.find("uniform") != -1 and line.find("{") == -1 and line.find(";") != -1):
  123. uline = line.replace("uniform", "")
  124. uline = uline.replace(";", "")
  125. lines = uline.split(",")
  126. for x in lines:
  127. x = x.strip()
  128. x = x[x.rfind(" ") + 1:]
  129. if (x.find("[") != -1):
  130. # unfiorm array
  131. x = x[:x.find("[")]
  132. if (not x in header_data.uniforms):
  133. header_data.uniforms += [x]
  134. if (line.strip().find("attribute ") == 0 and line.find("attrib:") != -1):
  135. uline = line.replace("in ", "")
  136. uline = uline.replace("attribute ", "")
  137. uline = uline.replace("highp ", "")
  138. uline = uline.replace(";", "")
  139. uline = uline[uline.find(" "):].strip()
  140. if (uline.find("//") != -1):
  141. name, bind = uline.split("//")
  142. if (bind.find("attrib:") != -1):
  143. name = name.strip()
  144. bind = bind.replace("attrib:", "").strip()
  145. header_data.attributes += [(name, bind)]
  146. if (line.strip().find("out ") == 0 and line.find("tfb:") != -1):
  147. uline = line.replace("out ", "")
  148. uline = uline.replace("highp ", "")
  149. uline = uline.replace(";", "")
  150. uline = uline[uline.find(" "):].strip()
  151. if (uline.find("//") != -1):
  152. name, bind = uline.split("//")
  153. if (bind.find("tfb:") != -1):
  154. name = name.strip()
  155. bind = bind.replace("tfb:", "").strip()
  156. header_data.feedbacks += [(name, bind)]
  157. line = line.replace("\r", "")
  158. line = line.replace("\n", "")
  159. if (header_data.reading == "vertex"):
  160. header_data.vertex_lines += [line]
  161. if (header_data.reading == "fragment"):
  162. header_data.fragment_lines += [line]
  163. line = fs.readline()
  164. header_data.line_offset += 1
  165. fs.close()
  166. return header_data
  167. def build_legacygl_header(filename, include, class_suffix, output_attribs, gles2=False):
  168. header_data = LegacyGLHeaderStruct()
  169. include_file_in_legacygl_header(filename, header_data, 0)
  170. out_file = filename + ".gen.h"
  171. fd = open(out_file, "w")
  172. enum_constants = []
  173. fd.write("/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\n")
  174. out_file_base = out_file
  175. out_file_base = out_file_base[out_file_base.rfind("/") + 1:]
  176. out_file_base = out_file_base[out_file_base.rfind("\\") + 1:]
  177. out_file_ifdef = out_file_base.replace(".", "_").upper()
  178. fd.write("#ifndef " + out_file_ifdef + class_suffix + "_120\n")
  179. fd.write("#define " + out_file_ifdef + class_suffix + "_120\n")
  180. out_file_class = out_file_base.replace(".glsl.gen.h", "").title().replace("_", "").replace(".", "") + "Shader" + class_suffix
  181. fd.write("\n\n")
  182. fd.write("#include \"" + include + "\"\n\n\n")
  183. fd.write("class " + out_file_class + " : public Shader" + class_suffix + " {\n\n")
  184. fd.write("\t virtual String get_shader_name() const { return \"" + out_file_class + "\"; }\n")
  185. fd.write("public:\n\n")
  186. if (len(header_data.conditionals)):
  187. fd.write("\tenum Conditionals {\n")
  188. for x in header_data.conditionals:
  189. fd.write("\t\t" + x.upper() + ",\n")
  190. fd.write("\t};\n\n")
  191. if (len(header_data.uniforms)):
  192. fd.write("\tenum Uniforms {\n")
  193. for x in header_data.uniforms:
  194. fd.write("\t\t" + x.upper() + ",\n")
  195. fd.write("\t};\n\n")
  196. fd.write("\t_FORCE_INLINE_ int get_uniform(Uniforms p_uniform) const { return _get_uniform(p_uniform); }\n\n")
  197. if (len(header_data.conditionals)):
  198. fd.write("\t_FORCE_INLINE_ void set_conditional(Conditionals p_conditional,bool p_enable) { _set_conditional(p_conditional,p_enable); }\n\n")
  199. fd.write("\t#define _FU if (get_uniform(p_uniform)<0) return; ERR_FAIL_COND( get_active()!=this );\n\n ")
  200. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\n\n")
  201. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, double p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\n\n")
  202. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint8_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  203. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int8_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  204. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint16_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  205. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int16_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  206. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint32_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  207. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int32_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  208. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Color& p_color) { _FU GLfloat col[4]={p_color.r,p_color.g,p_color.b,p_color.a}; glUniform4fv(get_uniform(p_uniform),1,col); }\n\n")
  209. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector2& p_vec2) { _FU GLfloat vec2[2]={p_vec2.x,p_vec2.y}; glUniform2fv(get_uniform(p_uniform),1,vec2); }\n\n")
  210. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector3& p_vec3) { _FU GLfloat vec3[3]={p_vec3.x,p_vec3.y,p_vec3.z}; glUniform3fv(get_uniform(p_uniform),1,vec3); }\n\n")
  211. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b) { _FU glUniform2f(get_uniform(p_uniform),p_a,p_b); }\n\n")
  212. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c) { _FU glUniform3f(get_uniform(p_uniform),p_a,p_b,p_c); }\n\n")
  213. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c, float p_d) { _FU glUniform4f(get_uniform(p_uniform),p_a,p_b,p_c,p_d); }\n\n")
  214. fd.write("""\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform& p_transform) { _FU
  215. const Transform &tr = p_transform;
  216. GLfloat matrix[16]={ /* build a 16x16 matrix */
  217. tr.basis.elements[0][0],
  218. tr.basis.elements[1][0],
  219. tr.basis.elements[2][0],
  220. 0,
  221. tr.basis.elements[0][1],
  222. tr.basis.elements[1][1],
  223. tr.basis.elements[2][1],
  224. 0,
  225. tr.basis.elements[0][2],
  226. tr.basis.elements[1][2],
  227. tr.basis.elements[2][2],
  228. 0,
  229. tr.origin.x,
  230. tr.origin.y,
  231. tr.origin.z,
  232. 1
  233. };
  234. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  235. }
  236. """)
  237. fd.write("""_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform2D& p_transform) { _FU
  238. const Transform2D &tr = p_transform;
  239. GLfloat matrix[16]={ /* build a 16x16 matrix */
  240. tr.elements[0][0],
  241. tr.elements[0][1],
  242. 0,
  243. 0,
  244. tr.elements[1][0],
  245. tr.elements[1][1],
  246. 0,
  247. 0,
  248. 0,
  249. 0,
  250. 1,
  251. 0,
  252. tr.elements[2][0],
  253. tr.elements[2][1],
  254. 0,
  255. 1
  256. };
  257. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  258. }
  259. """)
  260. fd.write("""_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const CameraMatrix& p_matrix) { _FU
  261. GLfloat matrix[16];
  262. for (int i=0;i<4;i++) {
  263. for (int j=0;j<4;j++) {
  264. matrix[i*4+j]=p_matrix.matrix[i][j];
  265. }
  266. }
  267. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  268. } """)
  269. fd.write("\n\n#undef _FU\n\n\n")
  270. fd.write("\tvirtual void init() {\n\n")
  271. enum_value_count = 0
  272. if (len(header_data.enums)):
  273. fd.write("\t\t//Written using math, given nonstandarity of 64 bits integer constants..\n")
  274. fd.write("\t\tstatic const Enum _enums[]={\n")
  275. bitofs = len(header_data.conditionals)
  276. enum_vals = []
  277. for xv in header_data.enums:
  278. x = header_data.enums[xv]
  279. bits = 1
  280. amt = len(x)
  281. while(2**bits < amt):
  282. bits += 1
  283. strs = "{"
  284. for i in range(amt):
  285. strs += "\"#define " + x[i] + "\\n\","
  286. v = {}
  287. v["set_mask"] = "uint64_t(" + str(i) + ")<<" + str(bitofs)
  288. v["clear_mask"] = "((uint64_t(1)<<40)-1) ^ (((uint64_t(1)<<" + str(bits) + ") - 1)<<" + str(bitofs) + ")"
  289. enum_vals.append(v)
  290. enum_constants.append(x[i])
  291. strs += "NULL}"
  292. fd.write("\t\t\t{(uint64_t(1<<" + str(bits) + ")-1)<<" + str(bitofs) + "," + str(bitofs) + "," + strs + "},\n")
  293. bitofs += bits
  294. fd.write("\t\t};\n\n")
  295. fd.write("\t\tstatic const EnumValue _enum_values[]={\n")
  296. enum_value_count = len(enum_vals)
  297. for x in enum_vals:
  298. fd.write("\t\t\t{" + x["set_mask"] + "," + x["clear_mask"] + "},\n")
  299. fd.write("\t\t};\n\n")
  300. conditionals_found = []
  301. if (len(header_data.conditionals)):
  302. fd.write("\t\tstatic const char* _conditional_strings[]={\n")
  303. if (len(header_data.conditionals)):
  304. for x in header_data.conditionals:
  305. fd.write("\t\t\t\"#define " + x + "\\n\",\n")
  306. conditionals_found.append(x)
  307. fd.write("\t\t};\n\n")
  308. else:
  309. fd.write("\t\tstatic const char **_conditional_strings=NULL;\n")
  310. if (len(header_data.uniforms)):
  311. fd.write("\t\tstatic const char* _uniform_strings[]={\n")
  312. if (len(header_data.uniforms)):
  313. for x in header_data.uniforms:
  314. fd.write("\t\t\t\"" + x + "\",\n")
  315. fd.write("\t\t};\n\n")
  316. else:
  317. fd.write("\t\tstatic const char **_uniform_strings=NULL;\n")
  318. if output_attribs:
  319. if (len(header_data.attributes)):
  320. fd.write("\t\tstatic AttributePair _attribute_pairs[]={\n")
  321. for x in header_data.attributes:
  322. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  323. fd.write("\t\t};\n\n")
  324. else:
  325. fd.write("\t\tstatic AttributePair *_attribute_pairs=NULL;\n")
  326. feedback_count = 0
  327. if (not gles2 and len(header_data.feedbacks)):
  328. fd.write("\t\tstatic const Feedback _feedbacks[]={\n")
  329. for x in header_data.feedbacks:
  330. name = x[0]
  331. cond = x[1]
  332. if (cond in conditionals_found):
  333. fd.write("\t\t\t{\"" + name + "\"," + str(conditionals_found.index(cond)) + "},\n")
  334. else:
  335. fd.write("\t\t\t{\"" + name + "\",-1},\n")
  336. feedback_count += 1
  337. fd.write("\t\t};\n\n")
  338. else:
  339. if gles2:
  340. pass
  341. else:
  342. fd.write("\t\tstatic const Feedback* _feedbacks=NULL;\n")
  343. if (len(header_data.texunits)):
  344. fd.write("\t\tstatic TexUnitPair _texunit_pairs[]={\n")
  345. for x in header_data.texunits:
  346. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  347. fd.write("\t\t};\n\n")
  348. else:
  349. fd.write("\t\tstatic TexUnitPair *_texunit_pairs=NULL;\n")
  350. if (not gles2 and len(header_data.ubos)):
  351. fd.write("\t\tstatic UBOPair _ubo_pairs[]={\n")
  352. for x in header_data.ubos:
  353. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  354. fd.write("\t\t};\n\n")
  355. else:
  356. if gles2:
  357. pass
  358. else:
  359. fd.write("\t\tstatic UBOPair *_ubo_pairs=NULL;\n")
  360. fd.write("\t\tstatic const char _vertex_code[]={\n")
  361. for x in header_data.vertex_lines:
  362. for i in range(len(x)):
  363. fd.write(str(ord(x[i])) + ",")
  364. fd.write(str(ord('\n')) + ",")
  365. fd.write("\t\t0};\n\n")
  366. fd.write("\t\tstatic const int _vertex_code_start=" + str(header_data.vertex_offset) + ";\n")
  367. fd.write("\t\tstatic const char _fragment_code[]={\n")
  368. for x in header_data.fragment_lines:
  369. for i in range(len(x)):
  370. fd.write(str(ord(x[i])) + ",")
  371. fd.write(str(ord('\n')) + ",")
  372. fd.write("\t\t0};\n\n")
  373. fd.write("\t\tstatic const int _fragment_code_start=" + str(header_data.fragment_offset) + ";\n")
  374. if output_attribs:
  375. if gles2:
  376. fd.write("\t\tsetup(_conditional_strings," + str(len(header_data.conditionals)) + ",_uniform_strings," + str(len(header_data.uniforms)) + ",_attribute_pairs," + str(len(header_data.attributes)) + ", _texunit_pairs," + str(len(header_data.texunits)) + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n")
  377. else:
  378. fd.write("\t\tsetup(_conditional_strings," + str(len(header_data.conditionals)) + ",_uniform_strings," + str(len(header_data.uniforms)) + ",_attribute_pairs," + str(len(header_data.attributes)) + ", _texunit_pairs," + str(len(header_data.texunits)) + ",_ubo_pairs," + str(len(header_data.ubos)) + ",_feedbacks," + str(feedback_count) + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n")
  379. else:
  380. if gles2:
  381. fd.write("\t\tsetup(_conditional_strings," + str(len(header_data.conditionals)) + ",_uniform_strings," + str(len(header_data.uniforms)) + ",_texunit_pairs," + str(len(header_data.texunits)) + ",_enums," + str(len(header_data.enums)) + ",_enum_values," + str(enum_value_count) + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n")
  382. else:
  383. fd.write("\t\tsetup(_conditional_strings," + str(len(header_data.conditionals)) + ",_uniform_strings," + str(len(header_data.uniforms)) + ",_texunit_pairs," + str(len(header_data.texunits)) + ",_enums," + str(len(header_data.enums)) + ",_enum_values," + str(enum_value_count) + ",_ubo_pairs," + str(len(header_data.ubos)) + ",_feedbacks," + str(feedback_count) + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n")
  384. fd.write("\t}\n\n")
  385. if (len(enum_constants)):
  386. fd.write("\tenum EnumConditionals {\n")
  387. for x in enum_constants:
  388. fd.write("\t\t" + x.upper() + ",\n")
  389. fd.write("\t};\n\n")
  390. fd.write("\tvoid set_enum_conditional(EnumConditionals p_cond) { _set_enum_conditional(p_cond); }\n")
  391. fd.write("};\n\n")
  392. fd.write("#endif\n\n")
  393. fd.close()
  394. def build_gles3_headers(target, source, env):
  395. for x in source:
  396. build_legacygl_header(str(x), include="drivers/gles3/shader_gles3.h", class_suffix="GLES3", output_attribs=True)
  397. def build_gles2_headers(target, source, env):
  398. for x in source:
  399. build_legacygl_header(str(x), include="drivers/gles2/shader_gles2.h", class_suffix="GLES2", output_attribs=True, gles2=True)
  400. def make_authors_header(target, source, env):
  401. sections = ["Project Founders", "Lead Developer", "Project Manager", "Developers"]
  402. sections_id = ["AUTHORS_FOUNDERS", "AUTHORS_LEAD_DEVELOPERS", "AUTHORS_PROJECT_MANAGERS", "AUTHORS_DEVELOPERS"]
  403. src = source[0].srcnode().abspath
  404. dst = target[0].srcnode().abspath
  405. f = open_utf8(src, "r")
  406. g = open_utf8(dst, "w")
  407. g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
  408. g.write("#ifndef _EDITOR_AUTHORS_H\n")
  409. g.write("#define _EDITOR_AUTHORS_H\n")
  410. current_section = ""
  411. reading = False
  412. def close_section():
  413. g.write("\t0\n")
  414. g.write("};\n")
  415. for line in f:
  416. if reading:
  417. if line.startswith(" "):
  418. g.write("\t\"" + escape_string(line.strip()) + "\",\n")
  419. continue
  420. if line.startswith("## "):
  421. if reading:
  422. close_section()
  423. reading = False
  424. for i in range(len(sections)):
  425. if line.strip().endswith(sections[i]):
  426. current_section = escape_string(sections_id[i])
  427. reading = True
  428. g.write("const char *const " + current_section + "[] = {\n")
  429. break
  430. if reading:
  431. close_section()
  432. g.write("#endif\n")
  433. g.close()
  434. f.close()
  435. def make_donors_header(target, source, env):
  436. sections = ["Platinum sponsors", "Gold sponsors", "Mini sponsors",
  437. "Gold donors", "Silver donors", "Bronze donors"]
  438. sections_id = ["DONORS_SPONSOR_PLAT", "DONORS_SPONSOR_GOLD", "DONORS_SPONSOR_MINI",
  439. "DONORS_GOLD", "DONORS_SILVER", "DONORS_BRONZE"]
  440. src = source[0].srcnode().abspath
  441. dst = target[0].srcnode().abspath
  442. f = open_utf8(src, "r")
  443. g = open_utf8(dst, "w")
  444. g.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
  445. g.write("#ifndef _EDITOR_DONORS_H\n")
  446. g.write("#define _EDITOR_DONORS_H\n")
  447. current_section = ""
  448. reading = False
  449. def close_section():
  450. g.write("\t0\n")
  451. g.write("};\n")
  452. for line in f:
  453. if reading >= 0:
  454. if line.startswith(" "):
  455. g.write("\t\"" + escape_string(line.strip()) + "\",\n")
  456. continue
  457. if line.startswith("## "):
  458. if reading:
  459. close_section()
  460. reading = False
  461. for i in range(len(sections)):
  462. if line.strip().endswith(sections[i]):
  463. current_section = escape_string(sections_id[i])
  464. reading = True
  465. g.write("const char *const " + current_section + "[] = {\n")
  466. break
  467. if reading:
  468. close_section()
  469. g.write("#endif\n")
  470. g.close()
  471. f.close()
  472. def make_license_header(target, source, env):
  473. src_copyright = source[0].srcnode().abspath
  474. src_license = source[1].srcnode().abspath
  475. dst = target[0].srcnode().abspath
  476. class LicenseReader:
  477. def __init__(self, license_file):
  478. self._license_file = license_file
  479. self.line_num = 0
  480. self.current = self.next_line()
  481. def next_line(self):
  482. line = self._license_file.readline()
  483. self.line_num += 1
  484. while line.startswith("#"):
  485. line = self._license_file.readline()
  486. self.line_num += 1
  487. self.current = line
  488. return line
  489. def next_tag(self):
  490. if not ':' in self.current:
  491. return ('',[])
  492. tag, line = self.current.split(":", 1)
  493. lines = [line.strip()]
  494. while self.next_line() and self.current.startswith(" "):
  495. lines.append(self.current.strip())
  496. return (tag, lines)
  497. from collections import OrderedDict
  498. projects = OrderedDict()
  499. license_list = []
  500. with open_utf8(src_copyright, "r") as copyright_file:
  501. reader = LicenseReader(copyright_file)
  502. part = {}
  503. while reader.current:
  504. tag, content = reader.next_tag()
  505. if tag in ("Files", "Copyright", "License"):
  506. part[tag] = content[:]
  507. elif tag == "Comment":
  508. # attach part to named project
  509. projects[content[0]] = projects.get(content[0], []) + [part]
  510. if not tag or not reader.current:
  511. # end of a paragraph start a new part
  512. if "License" in part and not "Files" in part:
  513. # no Files tag in this one, so assume standalone license
  514. license_list.append(part["License"])
  515. part = {}
  516. reader.next_line()
  517. data_list = []
  518. for project in itervalues(projects):
  519. for part in project:
  520. part["file_index"] = len(data_list)
  521. data_list += part["Files"]
  522. part["copyright_index"] = len(data_list)
  523. data_list += part["Copyright"]
  524. with open_utf8(dst, "w") as f:
  525. f.write("/* THIS FILE IS GENERATED DO NOT EDIT */\n")
  526. f.write("#ifndef _EDITOR_LICENSE_H\n")
  527. f.write("#define _EDITOR_LICENSE_H\n")
  528. f.write("const char *const GODOT_LICENSE_TEXT =")
  529. with open_utf8(src_license, "r") as license_file:
  530. for line in license_file:
  531. escaped_string = escape_string(line.strip())
  532. f.write("\n\t\t\"" + escaped_string + "\\n\"")
  533. f.write(";\n\n")
  534. f.write("struct ComponentCopyrightPart {\n"
  535. "\tconst char *license;\n"
  536. "\tconst char *const *files;\n"
  537. "\tconst char *const *copyright_statements;\n"
  538. "\tint file_count;\n"
  539. "\tint copyright_count;\n"
  540. "};\n\n")
  541. f.write("struct ComponentCopyright {\n"
  542. "\tconst char *name;\n"
  543. "\tconst ComponentCopyrightPart *parts;\n"
  544. "\tint part_count;\n"
  545. "};\n\n")
  546. f.write("const char *const COPYRIGHT_INFO_DATA[] = {\n")
  547. for line in data_list:
  548. f.write("\t\"" + escape_string(line) + "\",\n")
  549. f.write("};\n\n")
  550. f.write("const ComponentCopyrightPart COPYRIGHT_PROJECT_PARTS[] = {\n")
  551. part_index = 0
  552. part_indexes = {}
  553. for project_name, project in iteritems(projects):
  554. part_indexes[project_name] = part_index
  555. for part in project:
  556. f.write("\t{ \"" + escape_string(part["License"][0]) + "\", "
  557. + "&COPYRIGHT_INFO_DATA[" + str(part["file_index"]) + "], "
  558. + "&COPYRIGHT_INFO_DATA[" + str(part["copyright_index"]) + "], "
  559. + str(len(part["Files"])) + ", "
  560. + str(len(part["Copyright"])) + " },\n")
  561. part_index += 1
  562. f.write("};\n\n")
  563. f.write("const int COPYRIGHT_INFO_COUNT = " + str(len(projects)) + ";\n")
  564. f.write("const ComponentCopyright COPYRIGHT_INFO[] = {\n")
  565. for project_name, project in iteritems(projects):
  566. f.write("\t{ \"" + escape_string(project_name) + "\", "
  567. + "&COPYRIGHT_PROJECT_PARTS[" + str(part_indexes[project_name]) + "], "
  568. + str(len(project)) + " },\n")
  569. f.write("};\n\n")
  570. f.write("const int LICENSE_COUNT = " + str(len(license_list)) + ";\n")
  571. f.write("const char *const LICENSE_NAMES[] = {\n")
  572. for l in license_list:
  573. f.write("\t\"" + escape_string(l[0]) + "\",\n")
  574. f.write("};\n\n")
  575. f.write("const char *const LICENSE_BODIES[] = {\n\n")
  576. for l in license_list:
  577. for line in l[1:]:
  578. if line == ".":
  579. f.write("\t\"\\n\"\n")
  580. else:
  581. f.write("\t\"" + escape_string(line) + "\\n\"\n")
  582. f.write("\t\"\",\n\n")
  583. f.write("};\n\n")
  584. f.write("#endif\n")
  585. def add_module_version_string(self,s):
  586. self.module_version_string += "." + s
  587. def update_version(module_version_string=""):
  588. build_name = "custom_build"
  589. if (os.getenv("BUILD_NAME") != None):
  590. build_name = os.getenv("BUILD_NAME")
  591. print("Using custom build name: " + build_name)
  592. import version
  593. f = open("core/version_generated.gen.h", "w")
  594. f.write("#define VERSION_SHORT_NAME \"" + str(version.short_name) + "\"\n")
  595. f.write("#define VERSION_NAME \"" + str(version.name) + "\"\n")
  596. f.write("#define VERSION_MAJOR " + str(version.major) + "\n")
  597. f.write("#define VERSION_MINOR " + str(version.minor) + "\n")
  598. if (hasattr(version, 'patch')):
  599. f.write("#define VERSION_PATCH " + str(version.patch) + "\n")
  600. f.write("#define VERSION_STATUS \"" + str(version.status) + "\"\n")
  601. f.write("#define VERSION_BUILD \"" + str(build_name) + "\"\n")
  602. f.write("#define VERSION_MODULE_CONFIG \"" + str(version.module_config) + module_version_string + "\"\n")
  603. import datetime
  604. f.write("#define VERSION_YEAR " + str(datetime.datetime.now().year) + "\n")
  605. f.close()
  606. fhash = open("core/version_hash.gen.h", "w")
  607. githash = ""
  608. if os.path.isfile(".git/HEAD"):
  609. head = open(".git/HEAD", "r").readline().strip()
  610. if head.startswith("ref: "):
  611. head = ".git/" + head[5:]
  612. if os.path.isfile(head):
  613. githash = open(head, "r").readline().strip()
  614. else:
  615. githash = head
  616. fhash.write("#define VERSION_HASH \"" + githash + "\"")
  617. fhash.close()
  618. def parse_cg_file(fname, uniforms, sizes, conditionals):
  619. import re
  620. fs = open(fname, "r")
  621. line = fs.readline()
  622. while line:
  623. if re.match(r"^\s*uniform", line):
  624. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  625. type = res.groups(1)
  626. name = res.groups(2)
  627. uniforms.append(name)
  628. if (type.find("texobj") != -1):
  629. sizes.append(1)
  630. else:
  631. t = re.match(r"float(\d)x(\d)", type)
  632. if t:
  633. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  634. else:
  635. t = re.match(r"float(\d)", type)
  636. sizes.append(int(t.groups(1)))
  637. if line.find("[branch]") != -1:
  638. conditionals.append(name)
  639. line = fs.readline()
  640. fs.close()
  641. import glob
  642. def detect_modules():
  643. module_list = []
  644. includes_cpp = ""
  645. register_cpp = ""
  646. unregister_cpp = ""
  647. files = glob.glob("modules/*")
  648. files.sort() # so register_module_types does not change that often, and also plugins are registered in alphabetic order
  649. for x in files:
  650. if (not os.path.isdir(x)):
  651. continue
  652. if (not os.path.exists(x + "/config.py")):
  653. continue
  654. x = x.replace("modules/", "") # rest of world
  655. x = x.replace("modules\\", "") # win32
  656. module_list.append(x)
  657. try:
  658. with open("modules/" + x + "/register_types.h"):
  659. includes_cpp += '#include "modules/' + x + '/register_types.h"\n'
  660. register_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  661. register_cpp += '\tregister_' + x + '_types();\n'
  662. register_cpp += '#endif\n'
  663. unregister_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  664. unregister_cpp += '\tunregister_' + x + '_types();\n'
  665. unregister_cpp += '#endif\n'
  666. except IOError:
  667. pass
  668. modules_cpp = """
  669. // modules.cpp - THIS FILE IS GENERATED, DO NOT EDIT!!!!!!!
  670. #include "register_module_types.h"
  671. """ + includes_cpp + """
  672. void register_module_types() {
  673. """ + register_cpp + """
  674. }
  675. void unregister_module_types() {
  676. """ + unregister_cpp + """
  677. }
  678. """
  679. with open("modules/register_module_types.gen.cpp", "w") as f:
  680. f.write(modules_cpp)
  681. return module_list
  682. def win32_spawn(sh, escape, cmd, args, env):
  683. import subprocess
  684. newargs = ' '.join(args[1:])
  685. cmdline = cmd + " " + newargs
  686. startupinfo = subprocess.STARTUPINFO()
  687. for e in env:
  688. if type(env[e]) != type(""):
  689. env[e] = str(env[e])
  690. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  691. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  692. data, err = proc.communicate()
  693. rv = proc.wait()
  694. if rv:
  695. print("=====")
  696. print(err)
  697. print("=====")
  698. return rv
  699. """
  700. def win32_spawn(sh, escape, cmd, args, spawnenv):
  701. import win32file
  702. import win32event
  703. import win32process
  704. import win32security
  705. for var in spawnenv:
  706. spawnenv[var] = spawnenv[var].encode('ascii', 'replace')
  707. sAttrs = win32security.SECURITY_ATTRIBUTES()
  708. StartupInfo = win32process.STARTUPINFO()
  709. newargs = ' '.join(map(escape, args[1:]))
  710. cmdline = cmd + " " + newargs
  711. # check for any special operating system commands
  712. if cmd == 'del':
  713. for arg in args[1:]:
  714. win32file.DeleteFile(arg)
  715. exit_code = 0
  716. else:
  717. # otherwise execute the command.
  718. hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
  719. win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
  720. exit_code = win32process.GetExitCodeProcess(hProcess)
  721. win32file.CloseHandle(hProcess);
  722. win32file.CloseHandle(hThread);
  723. return exit_code
  724. """
  725. def android_add_flat_dir(self, dir):
  726. if (dir not in self.android_flat_dirs):
  727. self.android_flat_dirs.append(dir)
  728. def android_add_maven_repository(self, url):
  729. if (url not in self.android_maven_repos):
  730. self.android_maven_repos.append(url)
  731. def android_add_dependency(self, depline):
  732. if (depline not in self.android_dependencies):
  733. self.android_dependencies.append(depline)
  734. def android_add_java_dir(self, subpath):
  735. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  736. if (base_path not in self.android_java_dirs):
  737. self.android_java_dirs.append(base_path)
  738. def android_add_res_dir(self, subpath):
  739. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  740. if (base_path not in self.android_res_dirs):
  741. self.android_res_dirs.append(base_path)
  742. def android_add_asset_dir(self, subpath):
  743. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  744. if (base_path not in self.android_asset_dirs):
  745. self.android_asset_dirs.append(base_path)
  746. def android_add_aidl_dir(self, subpath):
  747. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  748. if (base_path not in self.android_aidl_dirs):
  749. self.android_aidl_dirs.append(base_path)
  750. def android_add_jni_dir(self, subpath):
  751. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  752. if (base_path not in self.android_jni_dirs):
  753. self.android_jni_dirs.append(base_path)
  754. def android_add_gradle_plugin(self, plugin):
  755. if (plugin not in self.android_gradle_plugins):
  756. self.android_gradle_plugins.append(plugin)
  757. def android_add_gradle_classpath(self, classpath):
  758. if (classpath not in self.android_gradle_classpath):
  759. self.android_gradle_classpath.append(classpath)
  760. def android_add_default_config(self, config):
  761. if (config not in self.android_default_config):
  762. self.android_default_config.append(config)
  763. def android_add_to_manifest(self, file):
  764. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  765. with open(base_path, "r") as f:
  766. self.android_manifest_chunk += f.read()
  767. def android_add_to_permissions(self, file):
  768. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  769. with open(base_path, "r") as f:
  770. self.android_permission_chunk += f.read()
  771. def android_add_to_attributes(self, file):
  772. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  773. with open(base_path, "r") as f:
  774. self.android_appattributes_chunk += f.read()
  775. def disable_module(self):
  776. self.disabled_modules.append(self.current_module)
  777. def use_windows_spawn_fix(self, platform=None):
  778. if (os.name != "nt"):
  779. return # not needed, only for windows
  780. # On Windows, due to the limited command line length, when creating a static library
  781. # from a very high number of objects SCons will invoke "ar" once per object file;
  782. # that makes object files with same names to be overwritten so the last wins and
  783. # the library looses symbols defined by overwritten objects.
  784. # By enabling quick append instead of the default mode (replacing), libraries will
  785. # got built correctly regardless the invocation strategy.
  786. # Furthermore, since SCons will rebuild the library from scratch when an object file
  787. # changes, no multiple versions of the same object file will be present.
  788. self.Replace(ARFLAGS='q')
  789. import subprocess
  790. def mySubProcess(cmdline, env):
  791. startupinfo = subprocess.STARTUPINFO()
  792. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  793. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  794. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  795. data, err = proc.communicate()
  796. rv = proc.wait()
  797. if rv:
  798. print("=====")
  799. print(err)
  800. print("=====")
  801. return rv
  802. def mySpawn(sh, escape, cmd, args, env):
  803. newargs = ' '.join(args[1:])
  804. cmdline = cmd + " " + newargs
  805. rv = 0
  806. env = {str(key): str(value) for key, value in iteritems(env)}
  807. if len(cmdline) > 32000 and cmd.endswith("ar"):
  808. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  809. for i in range(3, len(args)):
  810. rv = mySubProcess(cmdline + args[i], env)
  811. if rv:
  812. break
  813. else:
  814. rv = mySubProcess(cmdline, env)
  815. return rv
  816. self['SPAWN'] = mySpawn
  817. def split_lib(self, libname, src_list = None, env_lib = None):
  818. import string
  819. env = self
  820. num = 0
  821. cur_base = ""
  822. max_src = 64
  823. list = []
  824. lib_list = []
  825. if src_list == None:
  826. src_list = getattr(env, libname + "_sources")
  827. if type(env_lib) == type(None):
  828. env_lib = env
  829. for f in src_list:
  830. fname = ""
  831. if type(f) == type(""):
  832. fname = env.File(f).path
  833. else:
  834. fname = env.File(f)[0].path
  835. fname = fname.replace("\\", "/")
  836. base = string.join(fname.split("/")[:2], "/")
  837. if base != cur_base and len(list) > max_src:
  838. if num > 0:
  839. lib = env_lib.add_library(libname + str(num), list)
  840. lib_list.append(lib)
  841. list = []
  842. num = num + 1
  843. cur_base = base
  844. list.append(f)
  845. lib = env_lib.add_library(libname + str(num), list)
  846. lib_list.append(lib)
  847. if len(lib_list) > 0:
  848. import os, sys
  849. if os.name == 'posix' and sys.platform == 'msys':
  850. env.Replace(ARFLAGS=['rcsT'])
  851. lib = env_lib.add_library(libname + "_collated", lib_list)
  852. lib_list = [lib]
  853. lib_base = []
  854. env_lib.add_source_files(lib_base, "*.cpp")
  855. lib = env_lib.add_library(libname, lib_base)
  856. lib_list.insert(0, lib)
  857. env.Prepend(LIBS=lib_list)
  858. def save_active_platforms(apnames, ap):
  859. for x in ap:
  860. names = ['logo']
  861. if os.path.isfile(x + "/run_icon.png"):
  862. names.append('run_icon')
  863. for name in names:
  864. pngf = open(x + "/" + name + ".png", "rb")
  865. b = pngf.read(1)
  866. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  867. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  868. while(len(b) == 1):
  869. str += hex(ord(b))
  870. b = pngf.read(1)
  871. if (len(b) == 1):
  872. str += ","
  873. str += "};\n"
  874. pngf.close()
  875. wf = x + "/" + name + ".gen.h"
  876. with open(wf, "w") as pngw:
  877. pngw.write(str)
  878. def no_verbose(sys, env):
  879. colors = {}
  880. # Colors are disabled in non-TTY environments such as pipes. This means
  881. # that if output is redirected to a file, it will not contain color codes
  882. if sys.stdout.isatty():
  883. colors['cyan'] = '\033[96m'
  884. colors['purple'] = '\033[95m'
  885. colors['blue'] = '\033[94m'
  886. colors['green'] = '\033[92m'
  887. colors['yellow'] = '\033[93m'
  888. colors['red'] = '\033[91m'
  889. colors['end'] = '\033[0m'
  890. else:
  891. colors['cyan'] = ''
  892. colors['purple'] = ''
  893. colors['blue'] = ''
  894. colors['green'] = ''
  895. colors['yellow'] = ''
  896. colors['red'] = ''
  897. colors['end'] = ''
  898. compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  899. java_compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  900. compile_shared_source_message = '%sCompiling shared %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  901. link_program_message = '%sLinking Program %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  902. link_library_message = '%sLinking Static Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  903. ranlib_library_message = '%sRanlib Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  904. link_shared_library_message = '%sLinking Shared Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  905. java_library_message = '%sCreating Java Archive %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  906. env.Append(CXXCOMSTR=[compile_source_message])
  907. env.Append(CCCOMSTR=[compile_source_message])
  908. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  909. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  910. env.Append(ARCOMSTR=[link_library_message])
  911. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  912. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  913. env.Append(LINKCOMSTR=[link_program_message])
  914. env.Append(JARCOMSTR=[java_library_message])
  915. env.Append(JAVACCOMSTR=[java_compile_source_message])
  916. def detect_visual_c_compiler_version(tools_env):
  917. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  918. # (see the SCons documentation for more information on what it does)...
  919. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  920. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  921. # the proper vc version that will be called
  922. # There is no flag to give to visual c compilers to set the architecture, ie scons bits argument (32,64,ARM etc)
  923. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  924. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  925. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  926. # the following string values:
  927. # "" Compiler not detected
  928. # "amd64" Native 64 bit compiler
  929. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  930. # "x86" Native 32 bit compiler
  931. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  932. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  933. # and similar architectures/compilers
  934. # Set chosen compiler to "not detected"
  935. vc_chosen_compiler_index = -1
  936. vc_chosen_compiler_str = ""
  937. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  938. if 'VCINSTALLDIR' in tools_env:
  939. # print("Checking VCINSTALLDIR")
  940. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  941. # First test if amd64 and amd64_x86 compilers are present in the path
  942. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  943. if(vc_amd64_compiler_detection_index > -1):
  944. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  945. vc_chosen_compiler_str = "amd64"
  946. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  947. if(vc_amd64_x86_compiler_detection_index > -1
  948. and (vc_chosen_compiler_index == -1
  949. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  950. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  951. vc_chosen_compiler_str = "amd64_x86"
  952. # Now check the 32 bit compilers
  953. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  954. if(vc_x86_compiler_detection_index > -1
  955. and (vc_chosen_compiler_index == -1
  956. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  957. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  958. vc_chosen_compiler_str = "x86"
  959. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env['VCINSTALLDIR'] + "BIN\\x86_amd64;")
  960. if(vc_x86_amd64_compiler_detection_index > -1
  961. and (vc_chosen_compiler_index == -1
  962. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  963. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  964. vc_chosen_compiler_str = "x86_amd64"
  965. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  966. if 'VCTOOLSINSTALLDIR' in tools_env:
  967. # Newer versions have a different path available
  968. vc_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X64;")
  969. if(vc_amd64_compiler_detection_index > -1):
  970. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  971. vc_chosen_compiler_str = "amd64"
  972. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X86;")
  973. if(vc_amd64_x86_compiler_detection_index > -1
  974. and (vc_chosen_compiler_index == -1
  975. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  976. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  977. vc_chosen_compiler_str = "amd64_x86"
  978. vc_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X86;")
  979. if(vc_x86_compiler_detection_index > -1
  980. and (vc_chosen_compiler_index == -1
  981. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  982. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  983. vc_chosen_compiler_str = "x86"
  984. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X64;")
  985. if(vc_x86_amd64_compiler_detection_index > -1
  986. and (vc_chosen_compiler_index == -1
  987. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  988. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  989. vc_chosen_compiler_str = "x86_amd64"
  990. return vc_chosen_compiler_str
  991. def find_visual_c_batch_file(env):
  992. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file
  993. version = get_default_version(env)
  994. (host_platform, target_platform,req_target_platform) = get_host_target(env)
  995. return find_batch_file(env, version, host_platform, target_platform)[0]
  996. def generate_cpp_hint_file(filename):
  997. import os.path
  998. if os.path.isfile(filename):
  999. # Don't overwrite an existing hint file since the user may have customized it.
  1000. pass
  1001. else:
  1002. try:
  1003. with open(filename, "w") as fd:
  1004. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  1005. except IOError:
  1006. print("Could not write cpp.hint file.")
  1007. def generate_vs_project(env, num_jobs):
  1008. batch_file = find_visual_c_batch_file(env)
  1009. if batch_file:
  1010. def build_commandline(commands):
  1011. common_build_prefix = ['cmd /V /C set "plat=$(PlatformTarget)"',
  1012. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  1013. 'set "tools=yes"',
  1014. '(if "$(Configuration)"=="release" (set "tools=no"))',
  1015. 'call "' + batch_file + '" !plat!']
  1016. result = " ^& ".join(common_build_prefix + [commands])
  1017. return result
  1018. env.AddToVSProject(env.core_sources)
  1019. env.AddToVSProject(env.main_sources)
  1020. env.AddToVSProject(env.modules_sources)
  1021. env.AddToVSProject(env.scene_sources)
  1022. env.AddToVSProject(env.servers_sources)
  1023. env.AddToVSProject(env.editor_sources)
  1024. # windows allows us to have spaces in paths, so we need
  1025. # to double quote off the directory. However, the path ends
  1026. # in a backslash, so we need to remove this, lest it escape the
  1027. # last double quote off, confusing MSBuild
  1028. env['MSVSBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  1029. env['MSVSREBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! vsproj=yes -j' + str(num_jobs))
  1030. env['MSVSCLEANCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" --clean platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  1031. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  1032. # required for Visual Studio to understand that it needs to generate an NMAKE
  1033. # project. Do not modify without knowing what you are doing.
  1034. debug_variants = ['debug|Win32'] + ['debug|x64']
  1035. release_variants = ['release|Win32'] + ['release|x64']
  1036. release_debug_variants = ['release_debug|Win32'] + ['release_debug|x64']
  1037. variants = debug_variants + release_variants + release_debug_variants
  1038. debug_targets = ['bin\\godot.windows.tools.32.exe'] + ['bin\\godot.windows.tools.64.exe']
  1039. release_targets = ['bin\\godot.windows.opt.32.exe'] + ['bin\\godot.windows.opt.64.exe']
  1040. release_debug_targets = ['bin\\godot.windows.opt.tools.32.exe'] + ['bin\\godot.windows.opt.tools.64.exe']
  1041. targets = debug_targets + release_targets + release_debug_targets
  1042. msvproj = env.MSVSProject(target=['#godot' + env['MSVSPROJECTSUFFIX']],
  1043. incs=env.vs_incs,
  1044. srcs=env.vs_srcs,
  1045. runfile=targets,
  1046. buildtarget=targets,
  1047. auto_build_solution=1,
  1048. variant=variants)
  1049. else:
  1050. print("Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project.")
  1051. def precious_program(env, program, sources, **args):
  1052. program = env.ProgramOriginal(program, sources, **args)
  1053. env.Precious(program)
  1054. return program
  1055. def add_shared_library(env, name, sources, **args):
  1056. library = env.SharedLibrary(name, sources, **args)
  1057. env.NoCache(library)
  1058. return library
  1059. def add_library(env, name, sources, **args):
  1060. library = env.Library(name, sources, **args)
  1061. env.NoCache(library)
  1062. return library
  1063. def add_program(env, name, sources, **args):
  1064. program = env.Program(name, sources, **args)
  1065. env.NoCache(program)
  1066. return program
  1067. def CommandNoCache(env, target, sources, command, **args):
  1068. result = env.Command(target, sources, command, **args)
  1069. env.NoCache(result)
  1070. return result