methods.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797
  1. import os
  2. from compat import iteritems
  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. def build_shader_header(target, source, env):
  18. for x in source:
  19. print(x)
  20. name = str(x)
  21. name = name[name.rfind("/") + 1:]
  22. name = name[name.rfind("\\") + 1:]
  23. name = name.replace(".", "_")
  24. fs = open(str(x), "r")
  25. fd = open(str(x) + ".gen.h", "w")
  26. fd.write("/* this file has been generated by SCons, do not edit! */\n")
  27. fd.write("static const char *" + name + "=\n")
  28. line = fs.readline()
  29. while(line):
  30. line = line.replace("\r", "")
  31. line = line.replace("\n", "")
  32. line = line.replace("\\", "\\\\")
  33. line = line.replace("\"", "\\\"")
  34. fd.write("\"" + line + "\\n\"\n")
  35. line = fs.readline()
  36. fd.write(";\n")
  37. return 0
  38. def build_glsl_header(filename):
  39. fs = open(filename, "r")
  40. line = fs.readline()
  41. vertex_lines = []
  42. fragment_lines = []
  43. uniforms = []
  44. attributes = []
  45. fbos = []
  46. conditionals = []
  47. texunits = []
  48. texunit_names = []
  49. ubos = []
  50. ubo_names = []
  51. reading = ""
  52. line_offset = 0
  53. vertex_offset = 0
  54. fragment_offset = 0
  55. while(line):
  56. if (line.find("[vertex]") != -1):
  57. reading = "vertex"
  58. line = fs.readline()
  59. line_offset += 1
  60. vertex_offset = line_offset
  61. continue
  62. if (line.find("[fragment]") != -1):
  63. reading = "fragment"
  64. line = fs.readline()
  65. line_offset += 1
  66. fragment_offset = line_offset
  67. continue
  68. if (line.find("#ifdef ") != -1):
  69. ifdefline = line.replace("#ifdef ", "").strip()
  70. if (not ifdefline in conditionals):
  71. conditionals += [ifdefline]
  72. if (line.find("#elif defined(") != -1):
  73. ifdefline = line.replace("#elif defined(", "").strip()
  74. ifdefline = ifdefline.replace(")", "").strip()
  75. if (not ifdefline in conditionals):
  76. conditionals += [ifdefline]
  77. import re
  78. if re.search(r"^\s*uniform", line):
  79. if (line.lower().find("texunit:") != -1):
  80. # texture unit
  81. texunit = str(int(line[line.find(":") + 1:].strip()))
  82. uline = line[:line.lower().find("//")]
  83. uline = uline.replace("uniform", "")
  84. uline = uline.replace(";", "")
  85. lines = uline.split(",")
  86. for x in lines:
  87. x = x.strip()
  88. x = x[x.rfind(" ") + 1:]
  89. if (x.find("[") != -1):
  90. # unfiorm array
  91. x = x[:x.find("[")]
  92. if (not x in texunit_names):
  93. texunits += [(x, texunit)]
  94. texunit_names += [x]
  95. elif (line.lower().find("ubo:") != -1):
  96. # ubo
  97. uboidx = str(int(line[line.find(":") + 1:].strip()))
  98. uline = line[:line.lower().find("//")]
  99. uline = uline[uline.find("uniform") + len("uniform"):]
  100. uline = uline.replace(";", "")
  101. uline = uline.replace("{", "").strip()
  102. lines = uline.split(",")
  103. for x in lines:
  104. x = x.strip()
  105. x = x[x.rfind(" ") + 1:]
  106. if (x.find("[") != -1):
  107. # unfiorm array
  108. x = x[:x.find("[")]
  109. if (not x in ubo_names):
  110. ubos += [(x, uboidx)]
  111. ubo_names += [x]
  112. else:
  113. uline = line.replace("uniform", "")
  114. uline = uline.replace(";", "")
  115. lines = uline.split(",")
  116. for x in lines:
  117. x = x.strip()
  118. x = x[x.rfind(" ") + 1:]
  119. if (x.find("[") != -1):
  120. # unfiorm array
  121. x = x[:x.find("[")]
  122. if (not x in uniforms):
  123. uniforms += [x]
  124. if ((line.strip().find("in ") == 0 or line.strip().find("attribute ") == 0) and line.find("attrib:") != -1):
  125. uline = line.replace("in ", "")
  126. uline = uline.replace("attribute ", "")
  127. uline = uline.replace(";", "")
  128. uline = uline[uline.find(" "):].strip()
  129. if (uline.find("//") != -1):
  130. name, bind = uline.split("//")
  131. if (bind.find("attrib:") != -1):
  132. name = name.strip()
  133. bind = bind.replace("attrib:", "").strip()
  134. attributes += [(name, bind)]
  135. if (line.strip().find("out ") == 0):
  136. uline = line.replace("out", "").strip()
  137. uline = uline.replace(";", "")
  138. uline = uline[uline.find(" "):].strip()
  139. if (uline.find("//") != -1):
  140. name, bind = uline.split("//")
  141. if (bind.find("drawbuffer:") != -1):
  142. name = name.strip()
  143. bind = bind.replace("drawbuffer:", "").strip()
  144. fbos += [(name, bind)]
  145. line = line.replace("\r", "")
  146. line = line.replace("\n", "")
  147. line = line.replace("\\", "\\\\")
  148. line = line.replace("\"", "\\\"")
  149. # line=line+"\\n\\" no need to anymore
  150. if (reading == "vertex"):
  151. vertex_lines += [line]
  152. if (reading == "fragment"):
  153. fragment_lines += [line]
  154. line = fs.readline()
  155. line_offset += 1
  156. fs.close()
  157. out_file = filename + ".gen.h"
  158. fd = open(out_file, "w")
  159. fd.write("/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\n")
  160. out_file_base = out_file
  161. out_file_base = out_file_base[out_file_base.rfind("/") + 1:]
  162. out_file_base = out_file_base[out_file_base.rfind("\\") + 1:]
  163. # print("out file "+out_file+" base " +out_file_base)
  164. out_file_ifdef = out_file_base.replace(".", "_").upper()
  165. fd.write("#ifndef " + out_file_ifdef + "\n")
  166. fd.write("#define " + out_file_ifdef + "\n")
  167. out_file_class = out_file_base.replace(".glsl.h", "").title().replace("_", "").replace(".", "") + "ShaderGL"
  168. fd.write("\n\n")
  169. fd.write("#include \"drivers/opengl/shader_gl.h\"\n\n\n")
  170. fd.write("class " + out_file_class + " : public ShaderGL {\n\n")
  171. fd.write("\t virtual String get_shader_name() const { return \"" + out_file_class + "\"; }\n")
  172. fd.write("public:\n\n")
  173. if (len(conditionals)):
  174. fd.write("\tenum Conditionals {\n")
  175. for x in conditionals:
  176. fd.write("\t\t" + x + ",\n")
  177. fd.write("\t};\n\n")
  178. if (len(uniforms)):
  179. fd.write("\tenum Uniforms {\n")
  180. for x in uniforms:
  181. fd.write("\t\t" + x.upper() + ",\n")
  182. fd.write("\t};\n\n")
  183. fd.write("\t_FORCE_INLINE_ int get_uniform(Uniforms p_uniform) const { return _get_uniform(p_uniform); }\n\n")
  184. if (len(conditionals)):
  185. fd.write("\t_FORCE_INLINE_ void set_conditional(Conditionals p_conditional,bool p_enable) { _set_conditional(p_conditional,p_enable); }\n\n")
  186. fd.write("\t#define _FU if (get_uniform(p_uniform)<0) return; ERR_FAIL_COND( get_active()!=this );\n\n ")
  187. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, bool p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value?1:0); }\n\n")
  188. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\n\n")
  189. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, double p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\n\n")
  190. 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")
  191. 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")
  192. 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")
  193. 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")
  194. 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")
  195. 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")
  196. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint64_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n");
  197. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int64_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n");
  198. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, unsigned long p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  199. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, long p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n")
  200. 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")
  201. 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")
  202. 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")
  203. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Plane& p_plane) { _FU GLfloat plane[4]={p_plane.normal.x,p_plane.normal.y,p_plane.normal.z,p_plane.d}; glUniform4fv(get_uniform(p_uniform),1,plane); }\n\n")
  204. 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")
  205. 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")
  206. 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")
  207. fd.write("""\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform& p_transform) { _FU
  208. const Transform &tr = p_transform;
  209. GLfloat matrix[16]={ /* build a 16x16 matrix */
  210. tr.basis.elements[0][0],
  211. tr.basis.elements[1][0],
  212. tr.basis.elements[2][0],
  213. 0,
  214. tr.basis.elements[0][1],
  215. tr.basis.elements[1][1],
  216. tr.basis.elements[2][1],
  217. 0,
  218. tr.basis.elements[0][2],
  219. tr.basis.elements[1][2],
  220. tr.basis.elements[2][2],
  221. 0,
  222. tr.origin.x,
  223. tr.origin.y,
  224. tr.origin.z,
  225. 1
  226. };
  227. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  228. }
  229. """)
  230. fd.write("""\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform2D& p_transform) { _FU
  231. const Transform2D &tr = p_transform;
  232. GLfloat matrix[16]={ /* build a 16x16 matrix */
  233. tr.elements[0][0],
  234. tr.elements[0][1],
  235. 0,
  236. 0,
  237. tr.elements[1][0],
  238. tr.elements[1][1],
  239. 0,
  240. 0,
  241. 0,
  242. 0,
  243. 1,
  244. 0,
  245. tr.elements[2][0],
  246. tr.elements[2][1],
  247. 0,
  248. 1
  249. };
  250. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  251. }
  252. """)
  253. fd.write("""\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const CameraMatrix& p_matrix) { _FU
  254. GLfloat matrix[16];
  255. for (int i=0;i<4;i++) {
  256. for (int j=0;j<4;j++) {
  257. matrix[i*4+j]=p_matrix.matrix[i][j];
  258. }
  259. }
  260. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  261. }; """)
  262. fd.write("\n\n#undef _FU\n\n\n")
  263. fd.write("\tvirtual void init() {\n\n")
  264. if (len(conditionals)):
  265. fd.write("\t\tstatic const char* _conditional_strings[]={\n")
  266. if (len(conditionals)):
  267. for x in conditionals:
  268. fd.write("\t\t\t\"#define " + x + "\\n\",\n")
  269. fd.write("\t\t};\n\n")
  270. else:
  271. fd.write("\t\tstatic const char **_conditional_strings=NULL;\n")
  272. if (len(uniforms)):
  273. fd.write("\t\tstatic const char* _uniform_strings[]={\n")
  274. if (len(uniforms)):
  275. for x in uniforms:
  276. fd.write("\t\t\t\"" + x + "\",\n")
  277. fd.write("\t\t};\n\n")
  278. else:
  279. fd.write("\t\tstatic const char **_uniform_strings=NULL;\n")
  280. if (len(attributes)):
  281. fd.write("\t\tstatic AttributePair _attribute_pairs[]={\n")
  282. for x in attributes:
  283. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  284. fd.write("\t\t};\n\n")
  285. else:
  286. fd.write("\t\tstatic AttributePair *_attribute_pairs=NULL;\n")
  287. if (len(fbos)):
  288. fd.write("\t\tstatic FBOPair _fbo_pairs[]={\n")
  289. for x in fbos:
  290. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  291. fd.write("\t\t};\n\n")
  292. else:
  293. fd.write("\t\tstatic FBOPair *_fbo_pairs=NULL;\n")
  294. if (len(ubos)):
  295. fd.write("\t\tstatic UBOPair _ubo_pairs[]={\n")
  296. for x in ubos:
  297. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  298. fd.write("\t\t};\n\n")
  299. else:
  300. fd.write("\t\tstatic UBOPair *_ubo_pairs=NULL;\n")
  301. if (len(texunits)):
  302. fd.write("\t\tstatic TexUnitPair _texunit_pairs[]={\n")
  303. for x in texunits:
  304. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  305. fd.write("\t\t};\n\n")
  306. else:
  307. fd.write("\t\tstatic TexUnitPair *_texunit_pairs=NULL;\n")
  308. fd.write("\t\tstatic const char* _vertex_code=\"\\\n")
  309. for x in vertex_lines:
  310. fd.write("\t\t\t" + x + "\n")
  311. fd.write("\t\t\";\n\n")
  312. fd.write("\t\tstatic const int _vertex_code_start=" + str(vertex_offset) + ";\n")
  313. fd.write("\t\tstatic const char* _fragment_code=\"\\\n")
  314. for x in fragment_lines:
  315. fd.write("\t\t\t" + x + "\n")
  316. fd.write("\t\t\";\n\n")
  317. fd.write("\t\tstatic const int _fragment_code_start=" + str(fragment_offset) + ";\n")
  318. fd.write("\t\tsetup(_conditional_strings," + str(len(conditionals)) + ",_uniform_strings," + str(len(uniforms)) + ",_attribute_pairs," + str(len(attributes)) + ",_fbo_pairs," + str(len(fbos)) + ",_ubo_pairs," + str(len(ubos)) + ",_texunit_pairs," + str(len(texunits)) + ",_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n")
  319. fd.write("\t};\n\n")
  320. fd.write("};\n\n")
  321. fd.write("#endif\n\n")
  322. fd.close()
  323. def build_glsl_headers(target, source, env):
  324. for x in source:
  325. build_glsl_header(str(x))
  326. return 0
  327. def build_hlsl_dx9_header(filename):
  328. fs = open(filename, "r")
  329. line = fs.readline()
  330. vertex_lines = []
  331. fragment_lines = []
  332. uniforms = []
  333. fragment_uniforms = []
  334. attributes = []
  335. fbos = []
  336. conditionals = []
  337. reading = ""
  338. line_offset = 0
  339. vertex_offset = 0
  340. fragment_offset = 0
  341. while(line):
  342. if (line.find("[vertex]") != -1):
  343. reading = "vertex"
  344. line = fs.readline()
  345. line_offset += 1
  346. vertex_offset = line_offset
  347. continue
  348. if (line.find("[fragment]") != -1):
  349. reading = "fragment"
  350. line = fs.readline()
  351. line_offset += 1
  352. fragment_offset = line_offset
  353. continue
  354. if (line.find("#ifdef ") != -1):
  355. ifdefline = line.replace("#ifdef ", "").strip()
  356. if (not ifdefline in conditionals):
  357. conditionals += [ifdefline]
  358. if (line.find("#elif defined(") != -1):
  359. ifdefline = line.replace("#elif defined(", "").strip()
  360. ifdefline = ifdefline.replace(")", "").strip()
  361. if (not ifdefline in conditionals):
  362. conditionals += [ifdefline]
  363. if (line.find("uniform") != -1):
  364. uline = line.replace("uniform", "")
  365. uline = uline.replace(";", "")
  366. lines = uline.split(",")
  367. for x in lines:
  368. x = x.strip()
  369. x = x[x.rfind(" ") + 1:]
  370. if (x.find("[") != -1):
  371. # unfiorm array
  372. x = x[:x.find("[")]
  373. if (not x in uniforms):
  374. uniforms += [x]
  375. fragment_uniforms += [reading == "fragment"]
  376. line = line.replace("\r", "")
  377. line = line.replace("\n", "")
  378. line = line.replace("\\", "\\\\")
  379. line = line.replace("\"", "\\\"")
  380. line = line + "\\n\\"
  381. if (reading == "vertex"):
  382. vertex_lines += [line]
  383. if (reading == "fragment"):
  384. fragment_lines += [line]
  385. line = fs.readline()
  386. line_offset += 1
  387. fs.close()
  388. out_file = filename + ".gen.h"
  389. fd = open(out_file, "w")
  390. fd.write("/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\n")
  391. out_file_base = out_file
  392. out_file_base = out_file_base[out_file_base.rfind("/") + 1:]
  393. out_file_base = out_file_base[out_file_base.rfind("\\") + 1:]
  394. # print("out file "+out_file+" base " +out_file_base)
  395. out_file_ifdef = out_file_base.replace(".", "_").upper()
  396. fd.write("#ifndef " + out_file_ifdef + "\n")
  397. fd.write("#define " + out_file_ifdef + "\n")
  398. out_file_class = out_file_base.replace(".hlsl.h", "").title().replace("_", "").replace(".", "") + "ShaderDX9"
  399. fd.write("\n\n")
  400. fd.write("#include \"drivers/directx9/shader_dx9.h\"\n\n\n")
  401. fd.write("class " + out_file_class + " : public ShaderDX9 {\n\n")
  402. fd.write("\t virtual String get_shader_name() const { return \"" + out_file_class + "\"; }\n")
  403. fd.write("public:\n\n")
  404. if (len(conditionals)):
  405. fd.write("\tenum Conditionals {\n")
  406. for x in conditionals:
  407. fd.write("\t\t" + x + ",\n")
  408. fd.write("\t};\n\n")
  409. if (len(uniforms)):
  410. fd.write("\tenum Uniforms {\n")
  411. for x in uniforms:
  412. fd.write("\t\t" + x.upper() + ",\n")
  413. fd.write("\t};\n\n")
  414. if (len(conditionals)):
  415. fd.write("\t_FORCE_INLINE_ void set_conditional(Conditionals p_conditional,bool p_enable) { _set_conditional(p_conditional,p_enable); }\n\n")
  416. fd.write("\t#define _FU if (!_uniform_valid(p_uniform)) return; ERR_FAIL_COND( get_active()!=this );\n\n ")
  417. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, bool p_value) { _FU set_uniformb(p_uniform,p_value); }\n\n")
  418. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_value) { _FU set_uniformf(p_uniform,p_value); }\n\n")
  419. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, double p_value) { _FU set_uniformf(p_uniform,p_value); }\n\n")
  420. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint8_t p_value) { _FU set_uniformi(p_uniform,p_value); }\n\n")
  421. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int8_t p_value) { _FU set_uniformi(p_uniform,p_value); }\n\n")
  422. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint16_t p_value) { _FU set_uniformi(p_uniform,p_value); }\n\n")
  423. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int16_t p_value) { _FU set_uniformi(p_uniform,p_value); }\n\n")
  424. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint32_t p_value) { _FU set_uniformi(p_uniform,p_value); }\n\n")
  425. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int32_t p_value) { _FU set_uniformi(p_uniform,p_value); }\n\n")
  426. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint64_t p_value) { _FU set_uniformi(p_uniform,p_value); }\n\n");
  427. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int64_t p_value) { _FU set_uniformi(p_uniform,p_value); }\n\n");
  428. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, unsigned long p_value) { _FU set_uniformi(p_uniform,p_value); }\n\n")
  429. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, long p_value) { _FU set_uniformi(p_uniform,p_value); }\n\n")
  430. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Color& p_color) { _FU float col[4]={p_color.r,p_color.g,p_color.b,p_color.a}; set_uniformfv(p_uniform,col); }\n\n")
  431. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector2& p_vec2) { _FU float vec2[4]={p_vec2.x,p_vec2.y,0,0}; set_uniformfv(p_uniform,vec2); }\n\n")
  432. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Vector3& p_vec3) { _FU float vec3[4]={p_vec3.x,p_vec3.y,p_vec3.z,0}; set_uniformfv(p_uniform,vec3); }\n\n")
  433. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b) { _FU float vec2[4]={p_a,p_b,0,0}; set_uniformfv(p_uniform,vec2); }\n\n")
  434. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c) { _FU float vec3[4]={p_a,p_b,p_c,0}; set_uniformfv(p_uniform,vec3); }\n\n")
  435. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_a, float p_b, float p_c, float p_d) { _FU float vec4[4]={p_a,p_b,p_c,p_d}; set_uniformfv(p_uniform,vec4); }\n\n")
  436. fd.write("""\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform& p_transform) { _FU
  437. const Transform &tr = p_transform;
  438. float matrix[16]={ /* build a 16x16 matrix */
  439. tr.basis.elements[0][0],
  440. tr.basis.elements[0][1],
  441. tr.basis.elements[0][2],
  442. tr.origin.x,
  443. tr.basis.elements[1][0],
  444. tr.basis.elements[1][1],
  445. tr.basis.elements[1][2],
  446. tr.origin.y,
  447. tr.basis.elements[2][0],
  448. tr.basis.elements[2][1],
  449. tr.basis.elements[2][2],
  450. tr.origin.z,
  451. 0,
  452. 0,
  453. 0,
  454. 1
  455. };
  456. set_uniformfv(p_uniform,&matrix[0],4);
  457. }
  458. """)
  459. fd.write("""\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const CameraMatrix& p_matrix) { _FU
  460. float matrix[16];
  461. for (int i=0;i<4;i++) {
  462. for (int j=0;j<4;j++) {
  463. matrix[i*4+j]=p_matrix.matrix[j][i];
  464. }
  465. }
  466. set_uniformfv(p_uniform,&matrix[0],4);
  467. }; """)
  468. fd.write("\n\n#undef _FU\n\n\n")
  469. fd.write("\tvirtual void init(IDirect3DDevice9 *p_device,ShaderSupport p_version) {\n\n")
  470. if (len(conditionals)):
  471. fd.write("\t\tstatic const char* _conditional_strings[]={\n")
  472. if (len(conditionals)):
  473. for x in conditionals:
  474. fd.write("\t\t\t\"" + x + "\",\n")
  475. fd.write("\t\t};\n\n")
  476. else:
  477. fd.write("\t\tstatic const char **_conditional_strings=NULL;\n")
  478. if (len(uniforms)):
  479. fd.write("\t\tstatic const char* _uniform_strings[]={\n")
  480. if (len(uniforms)):
  481. for x in uniforms:
  482. fd.write("\t\t\t\"" + x + "\",\n")
  483. fd.write("\t\t};\n\n")
  484. fd.write("\t\tstatic const bool _fragment_uniforms[]={\n")
  485. if (len(uniforms)):
  486. for x in fragment_uniforms:
  487. if (x):
  488. fd.write("\t\t\ttrue,\n")
  489. else:
  490. fd.write("\t\t\tfalse,\n")
  491. fd.write("\t\t};\n\n")
  492. else:
  493. fd.write("\t\tstatic const char **_uniform_strings=NULL;\n")
  494. fd.write("\t\tstatic const bool *_fragment_uniforms=NULL;\n")
  495. fd.write("\t\tstatic const char* _vertex_code=\"\\\n")
  496. for x in vertex_lines:
  497. fd.write("\t\t\t" + x + "\n")
  498. fd.write("\t\t\";\n\n")
  499. fd.write("\t\tstatic const int _vertex_code_start=" + str(vertex_offset) + ";\n")
  500. fd.write("\t\tstatic const char* _fragment_code=\"\\\n")
  501. for x in fragment_lines:
  502. fd.write("\t\t\t" + x + "\n")
  503. fd.write("\t\t\";\n\n")
  504. fd.write("\t\tstatic const int _fragment_code_start=" + str(fragment_offset) + ";\n")
  505. fd.write("\t\tsetup(p_device,p_version,_conditional_strings," + str(len(conditionals)) + ",_uniform_strings," + str(len(uniforms)) + ",_fragment_uniforms,_vertex_code,_fragment_code,_vertex_code_start,_fragment_code_start);\n")
  506. fd.write("\t};\n\n")
  507. fd.write("};\n\n")
  508. fd.write("#endif\n\n")
  509. fd.close()
  510. def build_hlsl_dx9_headers(target, source, env):
  511. for x in source:
  512. build_hlsl_dx9_header(str(x))
  513. return 0
  514. class LegacyGLHeaderStruct:
  515. def __init__(self):
  516. self.vertex_lines = []
  517. self.fragment_lines = []
  518. self.uniforms = []
  519. self.attributes = []
  520. self.feedbacks = []
  521. self.fbos = []
  522. self.conditionals = []
  523. self.enums = {}
  524. self.texunits = []
  525. self.texunit_names = []
  526. self.ubos = []
  527. self.ubo_names = []
  528. self.vertex_included_files = []
  529. self.fragment_included_files = []
  530. self.reading = ""
  531. self.line_offset = 0
  532. self.vertex_offset = 0
  533. self.fragment_offset = 0
  534. def include_file_in_legacygl_header(filename, header_data, depth):
  535. fs = open(filename, "r")
  536. line = fs.readline()
  537. while(line):
  538. if (line.find("[vertex]") != -1):
  539. header_data.reading = "vertex"
  540. line = fs.readline()
  541. header_data.line_offset += 1
  542. header_data.vertex_offset = header_data.line_offset
  543. continue
  544. if (line.find("[fragment]") != -1):
  545. header_data.reading = "fragment"
  546. line = fs.readline()
  547. header_data.line_offset += 1
  548. header_data.fragment_offset = header_data.line_offset
  549. continue
  550. while(line.find("#include ") != -1):
  551. includeline = line.replace("#include ", "").strip()[1:-1]
  552. import os.path
  553. included_file = os.path.relpath(os.path.dirname(filename) + "/" + includeline)
  554. if (not included_file in header_data.vertex_included_files and header_data.reading == "vertex"):
  555. header_data.vertex_included_files += [included_file]
  556. if(include_file_in_legacygl_header(included_file, header_data, depth + 1) == None):
  557. print("Error in file '" + filename + "': #include " + includeline + "could not be found!")
  558. elif (not included_file in header_data.fragment_included_files and header_data.reading == "fragment"):
  559. header_data.fragment_included_files += [included_file]
  560. if(include_file_in_legacygl_header(included_file, header_data, depth + 1) == None):
  561. print("Error in file '" + filename + "': #include " + includeline + "could not be found!")
  562. line = fs.readline()
  563. if (line.find("#ifdef ") != -1 or line.find("#elif defined(") != -1):
  564. if (line.find("#ifdef ") != -1):
  565. ifdefline = line.replace("#ifdef ", "").strip()
  566. else:
  567. ifdefline = line.replace("#elif defined(", "").strip()
  568. ifdefline = ifdefline.replace(")", "").strip()
  569. if (line.find("_EN_") != -1):
  570. enumbase = ifdefline[:ifdefline.find("_EN_")]
  571. ifdefline = ifdefline.replace("_EN_", "_")
  572. line = line.replace("_EN_", "_")
  573. # print(enumbase+":"+ifdefline);
  574. if (enumbase not in header_data.enums):
  575. header_data.enums[enumbase] = []
  576. if (ifdefline not in header_data.enums[enumbase]):
  577. header_data.enums[enumbase].append(ifdefline)
  578. elif (not ifdefline in header_data.conditionals):
  579. header_data.conditionals += [ifdefline]
  580. if (line.find("uniform") != -1 and line.lower().find("texunit:") != -1):
  581. # texture unit
  582. texunitstr = line[line.find(":") + 1:].strip()
  583. if (texunitstr == "auto"):
  584. texunit = "-1"
  585. else:
  586. texunit = str(int(texunitstr))
  587. uline = line[:line.lower().find("//")]
  588. uline = uline.replace("uniform", "")
  589. uline = uline.replace("highp", "")
  590. uline = uline.replace(";", "")
  591. lines = uline.split(",")
  592. for x in lines:
  593. x = x.strip()
  594. x = x[x.rfind(" ") + 1:]
  595. if (x.find("[") != -1):
  596. # unfiorm array
  597. x = x[:x.find("[")]
  598. if (not x in header_data.texunit_names):
  599. header_data.texunits += [(x, texunit)]
  600. header_data.texunit_names += [x]
  601. elif (line.find("uniform") != -1 and line.lower().find("ubo:") != -1):
  602. # uniform buffer object
  603. ubostr = line[line.find(":") + 1:].strip()
  604. ubo = str(int(ubostr))
  605. uline = line[:line.lower().find("//")]
  606. uline = uline[uline.find("uniform") + len("uniform"):]
  607. uline = uline.replace("highp", "")
  608. uline = uline.replace(";", "")
  609. uline = uline.replace("{", "").strip()
  610. lines = uline.split(",")
  611. for x in lines:
  612. x = x.strip()
  613. x = x[x.rfind(" ") + 1:]
  614. if (x.find("[") != -1):
  615. # unfiorm array
  616. x = x[:x.find("[")]
  617. if (not x in header_data.ubo_names):
  618. header_data.ubos += [(x, ubo)]
  619. header_data.ubo_names += [x]
  620. elif (line.find("uniform") != -1 and line.find("{") == -1 and line.find(";") != -1):
  621. uline = line.replace("uniform", "")
  622. uline = uline.replace(";", "")
  623. lines = uline.split(",")
  624. for x in lines:
  625. x = x.strip()
  626. x = x[x.rfind(" ") + 1:]
  627. if (x.find("[") != -1):
  628. # unfiorm array
  629. x = x[:x.find("[")]
  630. if (not x in header_data.uniforms):
  631. header_data.uniforms += [x]
  632. if (line.strip().find("attribute ") == 0 and line.find("attrib:") != -1):
  633. uline = line.replace("in ", "")
  634. uline = uline.replace("attribute ", "")
  635. uline = uline.replace("highp ", "")
  636. uline = uline.replace(";", "")
  637. uline = uline[uline.find(" "):].strip()
  638. if (uline.find("//") != -1):
  639. name, bind = uline.split("//")
  640. if (bind.find("attrib:") != -1):
  641. name = name.strip()
  642. bind = bind.replace("attrib:", "").strip()
  643. header_data.attributes += [(name, bind)]
  644. if (line.strip().find("out ") == 0 and line.find("tfb:") != -1):
  645. uline = line.replace("out ", "")
  646. uline = uline.replace("highp ", "")
  647. uline = uline.replace(";", "")
  648. uline = uline[uline.find(" "):].strip()
  649. if (uline.find("//") != -1):
  650. name, bind = uline.split("//")
  651. if (bind.find("tfb:") != -1):
  652. name = name.strip()
  653. bind = bind.replace("tfb:", "").strip()
  654. header_data.feedbacks += [(name, bind)]
  655. line = line.replace("\r", "")
  656. line = line.replace("\n", "")
  657. # line=line.replace("\\","\\\\")
  658. # line=line.replace("\"","\\\"")
  659. # line=line+"\\n\\"
  660. if (header_data.reading == "vertex"):
  661. header_data.vertex_lines += [line]
  662. if (header_data.reading == "fragment"):
  663. header_data.fragment_lines += [line]
  664. line = fs.readline()
  665. header_data.line_offset += 1
  666. fs.close()
  667. return header_data
  668. def build_legacygl_header(filename, include, class_suffix, output_attribs):
  669. header_data = LegacyGLHeaderStruct()
  670. include_file_in_legacygl_header(filename, header_data, 0)
  671. out_file = filename + ".gen.h"
  672. fd = open(out_file, "w")
  673. enum_constants = []
  674. fd.write("/* WARNING, THIS FILE WAS GENERATED, DO NOT EDIT */\n")
  675. out_file_base = out_file
  676. out_file_base = out_file_base[out_file_base.rfind("/") + 1:]
  677. out_file_base = out_file_base[out_file_base.rfind("\\") + 1:]
  678. # print("out file "+out_file+" base " +out_file_base)
  679. out_file_ifdef = out_file_base.replace(".", "_").upper()
  680. fd.write("#ifndef " + out_file_ifdef + class_suffix + "_120\n")
  681. fd.write("#define " + out_file_ifdef + class_suffix + "_120\n")
  682. out_file_class = out_file_base.replace(".glsl.gen.h", "").title().replace("_", "").replace(".", "") + "Shader" + class_suffix
  683. fd.write("\n\n")
  684. fd.write("#include \"" + include + "\"\n\n\n")
  685. fd.write("class " + out_file_class + " : public Shader" + class_suffix + " {\n\n")
  686. fd.write("\t virtual String get_shader_name() const { return \"" + out_file_class + "\"; }\n")
  687. fd.write("public:\n\n")
  688. if (len(header_data.conditionals)):
  689. fd.write("\tenum Conditionals {\n")
  690. for x in header_data.conditionals:
  691. fd.write("\t\t" + x.upper() + ",\n")
  692. fd.write("\t};\n\n")
  693. if (len(header_data.uniforms)):
  694. fd.write("\tenum Uniforms {\n")
  695. for x in header_data.uniforms:
  696. fd.write("\t\t" + x.upper() + ",\n")
  697. fd.write("\t};\n\n")
  698. fd.write("\t_FORCE_INLINE_ int get_uniform(Uniforms p_uniform) const { return _get_uniform(p_uniform); }\n\n")
  699. if (len(header_data.conditionals)):
  700. fd.write("\t_FORCE_INLINE_ void set_conditional(Conditionals p_conditional,bool p_enable) { _set_conditional(p_conditional,p_enable); }\n\n")
  701. fd.write("\t#define _FU if (get_uniform(p_uniform)<0) return; ERR_FAIL_COND( get_active()!=this );\n\n ")
  702. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, float p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\n\n")
  703. fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, double p_value) { _FU glUniform1f(get_uniform(p_uniform),p_value); }\n\n")
  704. 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")
  705. 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")
  706. 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")
  707. 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")
  708. 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")
  709. 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")
  710. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, uint64_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n");
  711. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, int64_t p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n");
  712. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, unsigned long p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n");
  713. #fd.write("\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, long p_value) { _FU glUniform1i(get_uniform(p_uniform),p_value); }\n\n");
  714. 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")
  715. 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")
  716. 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")
  717. 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")
  718. 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")
  719. 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")
  720. fd.write("""\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform& p_transform) { _FU
  721. const Transform &tr = p_transform;
  722. GLfloat matrix[16]={ /* build a 16x16 matrix */
  723. tr.basis.elements[0][0],
  724. tr.basis.elements[1][0],
  725. tr.basis.elements[2][0],
  726. 0,
  727. tr.basis.elements[0][1],
  728. tr.basis.elements[1][1],
  729. tr.basis.elements[2][1],
  730. 0,
  731. tr.basis.elements[0][2],
  732. tr.basis.elements[1][2],
  733. tr.basis.elements[2][2],
  734. 0,
  735. tr.origin.x,
  736. tr.origin.y,
  737. tr.origin.z,
  738. 1
  739. };
  740. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  741. }
  742. """)
  743. fd.write("""\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const Transform2D& p_transform) { _FU
  744. const Transform2D &tr = p_transform;
  745. GLfloat matrix[16]={ /* build a 16x16 matrix */
  746. tr.elements[0][0],
  747. tr.elements[0][1],
  748. 0,
  749. 0,
  750. tr.elements[1][0],
  751. tr.elements[1][1],
  752. 0,
  753. 0,
  754. 0,
  755. 0,
  756. 1,
  757. 0,
  758. tr.elements[2][0],
  759. tr.elements[2][1],
  760. 0,
  761. 1
  762. };
  763. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  764. }
  765. """)
  766. fd.write("""\t_FORCE_INLINE_ void set_uniform(Uniforms p_uniform, const CameraMatrix& p_matrix) { _FU
  767. GLfloat matrix[16];
  768. for (int i=0;i<4;i++) {
  769. for (int j=0;j<4;j++) {
  770. matrix[i*4+j]=p_matrix.matrix[i][j];
  771. }
  772. }
  773. glUniformMatrix4fv(get_uniform(p_uniform),1,false,matrix);
  774. }; """)
  775. fd.write("\n\n#undef _FU\n\n\n")
  776. fd.write("\tvirtual void init() {\n\n")
  777. enum_value_count = 0
  778. if (len(header_data.enums)):
  779. fd.write("\t\t//Written using math, given nonstandarity of 64 bits integer constants..\n")
  780. fd.write("\t\tstatic const Enum _enums[]={\n")
  781. bitofs = len(header_data.conditionals)
  782. enum_vals = []
  783. for xv in header_data.enums:
  784. x = header_data.enums[xv]
  785. bits = 1
  786. amt = len(x)
  787. # print(x)
  788. while(2**bits < amt):
  789. bits += 1
  790. # print("amount: "+str(amt)+" bits "+str(bits));
  791. strs = "{"
  792. for i in range(amt):
  793. strs += "\"#define " + x[i] + "\\n\","
  794. v = {}
  795. v["set_mask"] = "uint64_t(" + str(i) + ")<<" + str(bitofs)
  796. v["clear_mask"] = "((uint64_t(1)<<40)-1) ^ (((uint64_t(1)<<" + str(bits) + ") - 1)<<" + str(bitofs) + ")"
  797. enum_vals.append(v)
  798. enum_constants.append(x[i])
  799. strs += "NULL}"
  800. fd.write("\t\t\t{(uint64_t(1<<" + str(bits) + ")-1)<<" + str(bitofs) + "," + str(bitofs) + "," + strs + "},\n")
  801. bitofs += bits
  802. fd.write("\t\t};\n\n")
  803. fd.write("\t\tstatic const EnumValue _enum_values[]={\n")
  804. enum_value_count = len(enum_vals)
  805. for x in enum_vals:
  806. fd.write("\t\t\t{" + x["set_mask"] + "," + x["clear_mask"] + "},\n")
  807. fd.write("\t\t};\n\n")
  808. conditionals_found = []
  809. if (len(header_data.conditionals)):
  810. fd.write("\t\tstatic const char* _conditional_strings[]={\n")
  811. if (len(header_data.conditionals)):
  812. for x in header_data.conditionals:
  813. fd.write("\t\t\t\"#define " + x + "\\n\",\n")
  814. conditionals_found.append(x)
  815. fd.write("\t\t};\n\n")
  816. else:
  817. fd.write("\t\tstatic const char **_conditional_strings=NULL;\n")
  818. if (len(header_data.uniforms)):
  819. fd.write("\t\tstatic const char* _uniform_strings[]={\n")
  820. if (len(header_data.uniforms)):
  821. for x in header_data.uniforms:
  822. fd.write("\t\t\t\"" + x + "\",\n")
  823. fd.write("\t\t};\n\n")
  824. else:
  825. fd.write("\t\tstatic const char **_uniform_strings=NULL;\n")
  826. if output_attribs:
  827. if (len(header_data.attributes)):
  828. fd.write("\t\tstatic AttributePair _attribute_pairs[]={\n")
  829. for x in header_data.attributes:
  830. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  831. fd.write("\t\t};\n\n")
  832. else:
  833. fd.write("\t\tstatic AttributePair *_attribute_pairs=NULL;\n")
  834. feedback_count = 0
  835. if (len(header_data.feedbacks)):
  836. fd.write("\t\tstatic const Feedback _feedbacks[]={\n")
  837. for x in header_data.feedbacks:
  838. name = x[0]
  839. cond = x[1]
  840. if (cond in conditionals_found):
  841. fd.write("\t\t\t{\"" + name + "\"," + str(conditionals_found.index(cond)) + "},\n")
  842. else:
  843. fd.write("\t\t\t{\"" + name + "\",-1},\n")
  844. feedback_count += 1
  845. fd.write("\t\t};\n\n")
  846. else:
  847. fd.write("\t\tstatic const Feedback* _feedbacks=NULL;\n")
  848. if (len(header_data.texunits)):
  849. fd.write("\t\tstatic TexUnitPair _texunit_pairs[]={\n")
  850. for x in header_data.texunits:
  851. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  852. fd.write("\t\t};\n\n")
  853. else:
  854. fd.write("\t\tstatic TexUnitPair *_texunit_pairs=NULL;\n")
  855. if (len(header_data.ubos)):
  856. fd.write("\t\tstatic UBOPair _ubo_pairs[]={\n")
  857. for x in header_data.ubos:
  858. fd.write("\t\t\t{\"" + x[0] + "\"," + x[1] + "},\n")
  859. fd.write("\t\t};\n\n")
  860. else:
  861. fd.write("\t\tstatic UBOPair *_ubo_pairs=NULL;\n")
  862. fd.write("\t\tstatic const char _vertex_code[]={\n")
  863. for x in header_data.vertex_lines:
  864. for i in range(len(x)):
  865. fd.write(str(ord(x[i])) + ",")
  866. fd.write(str(ord('\n')) + ",")
  867. fd.write("\t\t0};\n\n")
  868. fd.write("\t\tstatic const int _vertex_code_start=" + str(header_data.vertex_offset) + ";\n")
  869. fd.write("\t\tstatic const char _fragment_code[]={\n")
  870. for x in header_data.fragment_lines:
  871. for i in range(len(x)):
  872. fd.write(str(ord(x[i])) + ",")
  873. fd.write(str(ord('\n')) + ",")
  874. fd.write("\t\t0};\n\n")
  875. fd.write("\t\tstatic const int _fragment_code_start=" + str(header_data.fragment_offset) + ";\n")
  876. if output_attribs:
  877. 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")
  878. else:
  879. 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")
  880. fd.write("\t};\n\n")
  881. if (len(enum_constants)):
  882. fd.write("\tenum EnumConditionals {\n")
  883. for x in enum_constants:
  884. fd.write("\t\t" + x.upper() + ",\n")
  885. fd.write("\t};\n\n")
  886. fd.write("\tvoid set_enum_conditional(EnumConditionals p_cond) { _set_enum_conditional(p_cond); }\n")
  887. fd.write("};\n\n")
  888. fd.write("#endif\n\n")
  889. fd.close()
  890. def build_legacygl_headers(target, source, env):
  891. for x in source:
  892. build_legacygl_header(str(x), include="drivers/legacygl/shader_lgl.h", class_suffix="LGL", output_attribs=False)
  893. return 0
  894. def build_gles3_headers(target, source, env):
  895. for x in source:
  896. build_legacygl_header(str(x), include="drivers/gles3/shader_gles3.h", class_suffix="GLES3", output_attribs=True)
  897. def add_module_version_string(self,s):
  898. self.module_version_string += "." + s
  899. def update_version(module_version_string=""):
  900. build_name = "custom_build"
  901. if (os.getenv("BUILD_NAME") != None):
  902. build_name = os.getenv("BUILD_NAME")
  903. print("Using custom build name: " + build_name)
  904. import version
  905. f = open("core/version_generated.gen.h", "w")
  906. f.write("#define VERSION_SHORT_NAME \"" + str(version.short_name) + "\"\n")
  907. f.write("#define VERSION_NAME \"" + str(version.name) + "\"\n")
  908. f.write("#define VERSION_MAJOR " + str(version.major) + "\n")
  909. f.write("#define VERSION_MINOR " + str(version.minor) + "\n")
  910. if (hasattr(version, 'patch')):
  911. f.write("#define VERSION_PATCH " + str(version.patch) + "\n")
  912. f.write("#define VERSION_STATUS \"" + str(version.status) + "\"\n")
  913. f.write("#define VERSION_BUILD \"" + str(build_name) + "\"\n")
  914. f.write("#define VERSION_MODULE_CONFIG \"" + str(version.module_config) + module_version_string + "\"\n")
  915. import datetime
  916. f.write("#define VERSION_YEAR " + str(datetime.datetime.now().year) + "\n")
  917. f.close()
  918. fhash = open("core/version_hash.gen.h", "w")
  919. githash = ""
  920. if os.path.isfile(".git/HEAD"):
  921. head = open(".git/HEAD", "r").readline().strip()
  922. if head.startswith("ref: "):
  923. head = ".git/" + head[5:]
  924. if os.path.isfile(head):
  925. githash = open(head, "r").readline().strip()
  926. else:
  927. githash = head
  928. fhash.write("#define VERSION_HASH \"" + githash + "\"")
  929. fhash.close()
  930. def parse_cg_file(fname, uniforms, sizes, conditionals):
  931. import re
  932. fs = open(fname, "r")
  933. line = fs.readline()
  934. while line:
  935. if re.match(r"^\s*uniform", line):
  936. res = re.match(r"uniform ([\d\w]*) ([\d\w]*)")
  937. type = res.groups(1)
  938. name = res.groups(2)
  939. uniforms.append(name)
  940. if (type.find("texobj") != -1):
  941. sizes.append(1)
  942. else:
  943. t = re.match(r"float(\d)x(\d)", type)
  944. if t:
  945. sizes.append(int(t.groups(1)) * int(t.groups(2)))
  946. else:
  947. t = re.match(r"float(\d)", type)
  948. sizes.append(int(t.groups(1)))
  949. if line.find("[branch]") != -1:
  950. conditionals.append(name)
  951. line = fs.readline()
  952. def build_cg_shader(sname):
  953. vp_uniforms = []
  954. vp_uniform_sizes = []
  955. vp_conditionals = []
  956. parse_cg_file("vp_" + sname + ".cg", vp_uniforms, vp_uniform_sizes, vp_conditionals)
  957. fp_uniforms = []
  958. fp_uniform_sizes = []
  959. fp_conditionals = []
  960. parse_cg_file("fp_" + sname + ".cg", fp_uniforms, fp_uniform_sizes, fp_conditionals)
  961. fd = open("shader_" + sname + ".cg.gen.h", "w")
  962. fd.write('\n#include "shader_cell.h"\n')
  963. fd.write("\nclass Shader_" + sname + " : public ShaderCell {\n")
  964. fd.write("\n\tstatic struct VertexUniforms[] = {\n")
  965. offset = 0
  966. for i in range(0, len(vp_uniforms)):
  967. fd.write('\t\t{ "%s", %d, %d },\n' % (vp_uniforms[i], offset, vp_uniform_sizes[i]))
  968. offset = offset + vp_uniform_sizes[i]
  969. fd.write("\t};\n\n")
  970. fd.write("public:\n\n")
  971. fd.write("\tenum {\n")
  972. for i in range(0, len(vp_uniforms)):
  973. fd.write('\t\tVP_%s,\n' % vp_uniforms[i].upper())
  974. fd.write("\t};\n")
  975. import glob
  976. def detect_modules():
  977. module_list = []
  978. includes_cpp = ""
  979. register_cpp = ""
  980. unregister_cpp = ""
  981. files = glob.glob("modules/*")
  982. files.sort() # so register_module_types does not change that often, and also plugins are registered in alphabetic order
  983. for x in files:
  984. if (not os.path.isdir(x)):
  985. continue
  986. if (not os.path.exists(x + "/config.py")):
  987. continue
  988. x = x.replace("modules/", "") # rest of world
  989. x = x.replace("modules\\", "") # win32
  990. module_list.append(x)
  991. try:
  992. with open("modules/" + x + "/register_types.h"):
  993. includes_cpp += '#include "modules/' + x + '/register_types.h"\n'
  994. register_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  995. register_cpp += '\tregister_' + x + '_types();\n'
  996. register_cpp += '#endif\n'
  997. unregister_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  998. unregister_cpp += '\tunregister_' + x + '_types();\n'
  999. unregister_cpp += '#endif\n'
  1000. except IOError:
  1001. pass
  1002. modules_cpp = """
  1003. // modules.cpp - THIS FILE IS GENERATED, DO NOT EDIT!!!!!!!
  1004. #include "register_module_types.h"
  1005. """ + includes_cpp + """
  1006. void register_module_types() {
  1007. """ + register_cpp + """
  1008. }
  1009. void unregister_module_types() {
  1010. """ + unregister_cpp + """
  1011. }
  1012. """
  1013. f = open("modules/register_module_types.gen.cpp", "w")
  1014. f.write(modules_cpp)
  1015. return module_list
  1016. def win32_spawn(sh, escape, cmd, args, env):
  1017. import subprocess
  1018. newargs = ' '.join(args[1:])
  1019. cmdline = cmd + " " + newargs
  1020. startupinfo = subprocess.STARTUPINFO()
  1021. #startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  1022. for e in env:
  1023. if type(env[e]) != type(""):
  1024. env[e] = str(env[e])
  1025. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1026. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  1027. data, err = proc.communicate()
  1028. rv = proc.wait()
  1029. if rv:
  1030. print("=====")
  1031. print(err)
  1032. print("=====")
  1033. return rv
  1034. """
  1035. def win32_spawn(sh, escape, cmd, args, spawnenv):
  1036. import win32file
  1037. import win32event
  1038. import win32process
  1039. import win32security
  1040. for var in spawnenv:
  1041. spawnenv[var] = spawnenv[var].encode('ascii', 'replace')
  1042. sAttrs = win32security.SECURITY_ATTRIBUTES()
  1043. StartupInfo = win32process.STARTUPINFO()
  1044. newargs = ' '.join(map(escape, args[1:]))
  1045. cmdline = cmd + " " + newargs
  1046. # check for any special operating system commands
  1047. if cmd == 'del':
  1048. for arg in args[1:]:
  1049. win32file.DeleteFile(arg)
  1050. exit_code = 0
  1051. else:
  1052. # otherwise execute the command.
  1053. hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
  1054. win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
  1055. exit_code = win32process.GetExitCodeProcess(hProcess)
  1056. win32file.CloseHandle(hProcess);
  1057. win32file.CloseHandle(hThread);
  1058. return exit_code
  1059. """
  1060. def android_add_flat_dir(self, dir):
  1061. if (dir not in self.android_flat_dirs):
  1062. self.android_flat_dirs.append(dir)
  1063. def android_add_maven_repository(self, url):
  1064. if (url not in self.android_maven_repos):
  1065. self.android_maven_repos.append(url)
  1066. def android_add_dependency(self, depline):
  1067. if (depline not in self.android_dependencies):
  1068. self.android_dependencies.append(depline)
  1069. def android_add_java_dir(self, subpath):
  1070. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  1071. if (base_path not in self.android_java_dirs):
  1072. self.android_java_dirs.append(base_path)
  1073. def android_add_res_dir(self, subpath):
  1074. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  1075. if (base_path not in self.android_res_dirs):
  1076. self.android_res_dirs.append(base_path)
  1077. def android_add_asset_dir(self, subpath):
  1078. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  1079. if (base_path not in self.android_asset_dirs):
  1080. self.android_asset_dirs.append(base_path)
  1081. def android_add_aidl_dir(self, subpath):
  1082. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  1083. if (base_path not in self.android_aidl_dirs):
  1084. self.android_aidl_dirs.append(base_path)
  1085. def android_add_jni_dir(self, subpath):
  1086. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  1087. if (base_path not in self.android_jni_dirs):
  1088. self.android_jni_dirs.append(base_path)
  1089. def android_add_gradle_plugin(self, plugin):
  1090. if (plugin not in self.android_gradle_plugins):
  1091. self.android_gradle_plugins.append(plugin)
  1092. def android_add_gradle_classpath(self, classpath):
  1093. if (classpath not in self.android_gradle_classpath):
  1094. self.android_gradle_classpath.append(classpath)
  1095. def android_add_default_config(self, config):
  1096. if (config not in self.android_default_config):
  1097. self.android_default_config.append(config)
  1098. def android_add_to_manifest(self, file):
  1099. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  1100. f = open(base_path, "r")
  1101. self.android_manifest_chunk += f.read()
  1102. def android_add_to_permissions(self, file):
  1103. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  1104. f = open(base_path, "r")
  1105. self.android_permission_chunk += f.read()
  1106. def android_add_to_attributes(self, file):
  1107. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  1108. f = open(base_path, "r")
  1109. self.android_appattributes_chunk += f.read()
  1110. def disable_module(self):
  1111. self.disabled_modules.append(self.current_module)
  1112. def use_windows_spawn_fix(self, platform=None):
  1113. if (os.name != "nt"):
  1114. return # not needed, only for windows
  1115. # On Windows, due to the limited command line length, when creating a static library
  1116. # from a very high number of objects SCons will invoke "ar" once per object file;
  1117. # that makes object files with same names to be overwritten so the last wins and
  1118. # the library looses symbols defined by overwritten objects.
  1119. # By enabling quick append instead of the default mode (replacing), libraries will
  1120. # got built correctly regardless the invocation strategy.
  1121. # Furthermore, since SCons will rebuild the library from scratch when an object file
  1122. # changes, no multiple versions of the same object file will be present.
  1123. self.Replace(ARFLAGS='q')
  1124. import subprocess
  1125. def mySubProcess(cmdline, env):
  1126. prefix = ""
  1127. if(platform == 'javascript'):
  1128. prefix = "python.exe "
  1129. startupinfo = subprocess.STARTUPINFO()
  1130. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  1131. proc = subprocess.Popen(prefix + cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1132. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  1133. data, err = proc.communicate()
  1134. rv = proc.wait()
  1135. if rv:
  1136. print("=====")
  1137. print(err)
  1138. print("=====")
  1139. return rv
  1140. def mySpawn(sh, escape, cmd, args, env):
  1141. newargs = ' '.join(args[1:])
  1142. cmdline = cmd + " " + newargs
  1143. rv = 0
  1144. env = {str(key): str(value) for key, value in iteritems(env)}
  1145. if len(cmdline) > 32000 and cmd.endswith("ar"):
  1146. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  1147. for i in range(3, len(args)):
  1148. rv = mySubProcess(cmdline + args[i], env)
  1149. if rv:
  1150. break
  1151. else:
  1152. rv = mySubProcess(cmdline, env)
  1153. return rv
  1154. self['SPAWN'] = mySpawn
  1155. def split_lib(self, libname, src_list = None, env_lib = None):
  1156. import string
  1157. env = self
  1158. num = 0
  1159. cur_base = ""
  1160. max_src = 64
  1161. list = []
  1162. lib_list = []
  1163. if src_list == None:
  1164. src_list = getattr(env, libname + "_sources")
  1165. if type(env_lib) == type(None):
  1166. env_lib = env
  1167. for f in src_list:
  1168. fname = ""
  1169. if type(f) == type(""):
  1170. fname = env.File(f).path
  1171. else:
  1172. fname = env.File(f)[0].path
  1173. fname = fname.replace("\\", "/")
  1174. base = string.join(fname.split("/")[:2], "/")
  1175. if base != cur_base and len(list) > max_src:
  1176. if num > 0:
  1177. lib = env_lib.add_library(libname + str(num), list)
  1178. lib_list.append(lib)
  1179. list = []
  1180. num = num + 1
  1181. cur_base = base
  1182. list.append(f)
  1183. lib = env_lib.add_library(libname + str(num), list)
  1184. lib_list.append(lib)
  1185. if len(lib_list) > 0:
  1186. import os, sys
  1187. if os.name == 'posix' and sys.platform == 'msys':
  1188. env.Replace(ARFLAGS=['rcsT'])
  1189. lib = env_lib.add_library(libname + "_collated", lib_list)
  1190. lib_list = [lib]
  1191. lib_base = []
  1192. env_lib.add_source_files(lib_base, "*.cpp")
  1193. lib = env_lib.add_library(libname, lib_base)
  1194. lib_list.insert(0, lib)
  1195. env.Prepend(LIBS=lib_list)
  1196. def save_active_platforms(apnames, ap):
  1197. for x in ap:
  1198. names = ['logo']
  1199. if os.path.isfile(x + "/run_icon.png"):
  1200. names.append('run_icon')
  1201. for name in names:
  1202. pngf = open(x + "/" + name + ".png", "rb")
  1203. b = pngf.read(1)
  1204. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  1205. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  1206. while(len(b) == 1):
  1207. str += hex(ord(b))
  1208. b = pngf.read(1)
  1209. if (len(b) == 1):
  1210. str += ","
  1211. str += "};\n"
  1212. wf = x + "/" + name + ".gen.h"
  1213. pngw = open(wf, "w")
  1214. pngw.write(str)
  1215. def no_verbose(sys, env):
  1216. colors = {}
  1217. # Colors are disabled in non-TTY environments such as pipes. This means
  1218. # that if output is redirected to a file, it will not contain color codes
  1219. if sys.stdout.isatty():
  1220. colors['cyan'] = '\033[96m'
  1221. colors['purple'] = '\033[95m'
  1222. colors['blue'] = '\033[94m'
  1223. colors['green'] = '\033[92m'
  1224. colors['yellow'] = '\033[93m'
  1225. colors['red'] = '\033[91m'
  1226. colors['end'] = '\033[0m'
  1227. else:
  1228. colors['cyan'] = ''
  1229. colors['purple'] = ''
  1230. colors['blue'] = ''
  1231. colors['green'] = ''
  1232. colors['yellow'] = ''
  1233. colors['red'] = ''
  1234. colors['end'] = ''
  1235. compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  1236. java_compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  1237. compile_shared_source_message = '%sCompiling shared %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  1238. link_program_message = '%sLinking Program %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  1239. link_library_message = '%sLinking Static Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  1240. ranlib_library_message = '%sRanlib Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  1241. link_shared_library_message = '%sLinking Shared Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  1242. java_library_message = '%sCreating Java Archive %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  1243. env.Append(CXXCOMSTR=[compile_source_message])
  1244. env.Append(CCCOMSTR=[compile_source_message])
  1245. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  1246. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  1247. env.Append(ARCOMSTR=[link_library_message])
  1248. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  1249. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  1250. env.Append(LINKCOMSTR=[link_program_message])
  1251. env.Append(JARCOMSTR=[java_library_message])
  1252. env.Append(JAVACCOMSTR=[java_compile_source_message])
  1253. def detect_visual_c_compiler_version(tools_env):
  1254. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  1255. # (see the SCons documentation for more information on what it does)...
  1256. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  1257. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  1258. # the proper vc version that will be called
  1259. # There is no flag to give to visual c compilers to set the architecture, ie scons bits argument (32,64,ARM etc)
  1260. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  1261. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  1262. # is to check the PATH variable and figure out which one will be called first. Code below does that and returns:
  1263. # the following string values:
  1264. # "" Compiler not detected
  1265. # "amd64" Native 64 bit compiler
  1266. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  1267. # "x86" Native 32 bit compiler
  1268. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  1269. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  1270. # and similar architectures/compilers
  1271. # Set chosen compiler to "not detected"
  1272. vc_chosen_compiler_index = -1
  1273. vc_chosen_compiler_str = ""
  1274. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  1275. if 'VCINSTALLDIR' in tools_env:
  1276. # print("Checking VCINSTALLDIR")
  1277. # find() works with -1 so big ifs below are needed... the simplest solution, in fact
  1278. # First test if amd64 and amd64_x86 compilers are present in the path
  1279. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  1280. if(vc_amd64_compiler_detection_index > -1):
  1281. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  1282. vc_chosen_compiler_str = "amd64"
  1283. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  1284. if(vc_amd64_x86_compiler_detection_index > -1
  1285. and (vc_chosen_compiler_index == -1
  1286. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  1287. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  1288. vc_chosen_compiler_str = "amd64_x86"
  1289. # Now check the 32 bit compilers
  1290. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  1291. if(vc_x86_compiler_detection_index > -1
  1292. and (vc_chosen_compiler_index == -1
  1293. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  1294. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  1295. vc_chosen_compiler_str = "x86"
  1296. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env['VCINSTALLDIR'] + "BIN\\x86_amd64;")
  1297. if(vc_x86_amd64_compiler_detection_index > -1
  1298. and (vc_chosen_compiler_index == -1
  1299. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  1300. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  1301. vc_chosen_compiler_str = "x86_amd64"
  1302. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  1303. if 'VCTOOLSINSTALLDIR' in tools_env:
  1304. # print("Checking VCTOOLSINSTALLDIR")
  1305. # Newer versions have a different path available
  1306. vc_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X64;")
  1307. if(vc_amd64_compiler_detection_index > -1):
  1308. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  1309. vc_chosen_compiler_str = "amd64"
  1310. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X86;")
  1311. if(vc_amd64_x86_compiler_detection_index > -1
  1312. and (vc_chosen_compiler_index == -1
  1313. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  1314. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  1315. vc_chosen_compiler_str = "amd64_x86"
  1316. vc_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X86;")
  1317. if(vc_x86_compiler_detection_index > -1
  1318. and (vc_chosen_compiler_index == -1
  1319. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  1320. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  1321. vc_chosen_compiler_str = "x86"
  1322. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X64;")
  1323. if(vc_x86_amd64_compiler_detection_index > -1
  1324. and (vc_chosen_compiler_index == -1
  1325. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  1326. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  1327. vc_chosen_compiler_str = "x86_amd64"
  1328. # debug help
  1329. # print(vc_amd64_compiler_detection_index)
  1330. # print(vc_amd64_x86_compiler_detection_index)
  1331. # print(vc_x86_compiler_detection_index)
  1332. # print(vc_x86_amd64_compiler_detection_index)
  1333. # print("chosen "+str(vc_chosen_compiler_index)+ " | "+str(vc_chosen_compiler_str))
  1334. return vc_chosen_compiler_str
  1335. def find_visual_c_batch_file(env):
  1336. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file
  1337. version = get_default_version(env)
  1338. (host_platform, target_platform,req_target_platform) = get_host_target(env)
  1339. return find_batch_file(env, version, host_platform, target_platform)[0]
  1340. def generate_cpp_hint_file(filename):
  1341. import os.path
  1342. if os.path.isfile(filename):
  1343. # Don't overwrite an existing hint file since the user may have customized it.
  1344. pass
  1345. else:
  1346. try:
  1347. fd = open(filename, "w")
  1348. fd.write("#define GDCLASS(m_class, m_inherits)\n")
  1349. except IOError:
  1350. print("Could not write cpp.hint file.")
  1351. def generate_vs_project(env, num_jobs):
  1352. batch_file = find_visual_c_batch_file(env)
  1353. if batch_file:
  1354. def build_commandline(commands):
  1355. common_build_prefix = ['cmd /V /C set "plat=$(PlatformTarget)"',
  1356. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  1357. 'set "tools=yes"',
  1358. '(if "$(Configuration)"=="release" (set "tools=no"))',
  1359. 'call "' + batch_file + '" !plat!']
  1360. result = " ^& ".join(common_build_prefix + [commands])
  1361. # print("Building commandline: ", result)
  1362. return result
  1363. env.AddToVSProject(env.core_sources)
  1364. env.AddToVSProject(env.main_sources)
  1365. env.AddToVSProject(env.modules_sources)
  1366. env.AddToVSProject(env.scene_sources)
  1367. env.AddToVSProject(env.servers_sources)
  1368. env.AddToVSProject(env.editor_sources)
  1369. # windows allows us to have spaces in paths, so we need
  1370. # to double quote off the directory. However, the path ends
  1371. # in a backslash, so we need to remove this, lest it escape the
  1372. # last double quote off, confusing MSBuild
  1373. env['MSVSBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  1374. env['MSVSREBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows progress=no target=$(Configuration) tools=!tools! vsproj=yes -j' + str(num_jobs))
  1375. env['MSVSCLEANCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" --clean platform=windows progress=no target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  1376. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  1377. # required for Visual Studio to understand that it needs to generate an NMAKE
  1378. # project. Do not modify without knowing what you are doing.
  1379. debug_variants = ['debug|Win32'] + ['debug|x64']
  1380. release_variants = ['release|Win32'] + ['release|x64']
  1381. release_debug_variants = ['release_debug|Win32'] + ['release_debug|x64']
  1382. variants = debug_variants + release_variants + release_debug_variants
  1383. debug_targets = ['bin\\godot.windows.tools.32.exe'] + ['bin\\godot.windows.tools.64.exe']
  1384. release_targets = ['bin\\godot.windows.opt.32.exe'] + ['bin\\godot.windows.opt.64.exe']
  1385. release_debug_targets = ['bin\\godot.windows.opt.tools.32.exe'] + ['bin\\godot.windows.opt.tools.64.exe']
  1386. targets = debug_targets + release_targets + release_debug_targets
  1387. msvproj = env.MSVSProject(target=['#godot' + env['MSVSPROJECTSUFFIX']],
  1388. incs=env.vs_incs,
  1389. srcs=env.vs_srcs,
  1390. runfile=targets,
  1391. buildtarget=targets,
  1392. auto_build_solution=1,
  1393. variant=variants)
  1394. else:
  1395. print("Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project.")
  1396. def precious_program(env, program, sources, **args):
  1397. program = env.ProgramOriginal(program, sources, **args)
  1398. env.Precious(program)
  1399. return program
  1400. def add_shared_library(env, name, sources, **args):
  1401. library = env.SharedLibrary(name, sources, **args)
  1402. env.NoCache(library)
  1403. return library
  1404. def add_library(env, name, sources, **args):
  1405. library = env.Library(name, sources, **args)
  1406. env.NoCache(library)
  1407. return library
  1408. def add_program(env, name, sources, **args):
  1409. program = env.Program(name, sources, **args)
  1410. env.NoCache(program)
  1411. return program
  1412. def CommandNoCache(env, target, sources, command, **args):
  1413. result = env.Command(target, sources, command, **args)
  1414. env.NoCache(result)
  1415. return result