methods.py 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750
  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. rev = "custom_build"
  901. if (os.getenv("BUILD_REVISION") != None):
  902. rev = os.getenv("BUILD_REVISION")
  903. print("Using custom revision: " + rev)
  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_REVISION " + str(rev) + "\n")
  913. f.write("#define VERSION_STATUS " + str(version.status) + "\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. x = x.replace("modules/", "") # rest of world
  987. x = x.replace("modules\\", "") # win32
  988. module_list.append(x)
  989. try:
  990. with open("modules/" + x + "/register_types.h"):
  991. includes_cpp += '#include "modules/' + x + '/register_types.h"\n'
  992. register_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  993. register_cpp += '\tregister_' + x + '_types();\n'
  994. register_cpp += '#endif\n'
  995. unregister_cpp += '#ifdef MODULE_' + x.upper() + '_ENABLED\n'
  996. unregister_cpp += '\tunregister_' + x + '_types();\n'
  997. unregister_cpp += '#endif\n'
  998. except IOError:
  999. pass
  1000. modules_cpp = """
  1001. // modules.cpp - THIS FILE IS GENERATED, DO NOT EDIT!!!!!!!
  1002. #include "register_module_types.h"
  1003. """ + includes_cpp + """
  1004. void register_module_types() {
  1005. """ + register_cpp + """
  1006. }
  1007. void unregister_module_types() {
  1008. """ + unregister_cpp + """
  1009. }
  1010. """
  1011. f = open("modules/register_module_types.gen.cpp", "w")
  1012. f.write(modules_cpp)
  1013. return module_list
  1014. def win32_spawn(sh, escape, cmd, args, env):
  1015. import subprocess
  1016. newargs = ' '.join(args[1:])
  1017. cmdline = cmd + " " + newargs
  1018. startupinfo = subprocess.STARTUPINFO()
  1019. #startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  1020. for e in env:
  1021. if type(env[e]) != type(""):
  1022. env[e] = str(env[e])
  1023. proc = subprocess.Popen(cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1024. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  1025. data, err = proc.communicate()
  1026. rv = proc.wait()
  1027. if rv:
  1028. print("=====")
  1029. print(err)
  1030. print("=====")
  1031. return rv
  1032. """
  1033. def win32_spawn(sh, escape, cmd, args, spawnenv):
  1034. import win32file
  1035. import win32event
  1036. import win32process
  1037. import win32security
  1038. for var in spawnenv:
  1039. spawnenv[var] = spawnenv[var].encode('ascii', 'replace')
  1040. sAttrs = win32security.SECURITY_ATTRIBUTES()
  1041. StartupInfo = win32process.STARTUPINFO()
  1042. newargs = ' '.join(map(escape, args[1:]))
  1043. cmdline = cmd + " " + newargs
  1044. # check for any special operating system commands
  1045. if cmd == 'del':
  1046. for arg in args[1:]:
  1047. win32file.DeleteFile(arg)
  1048. exit_code = 0
  1049. else:
  1050. # otherwise execute the command.
  1051. hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
  1052. win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
  1053. exit_code = win32process.GetExitCodeProcess(hProcess)
  1054. win32file.CloseHandle(hProcess);
  1055. win32file.CloseHandle(hThread);
  1056. return exit_code
  1057. """
  1058. def android_add_flat_dir(self, dir):
  1059. if (dir not in self.android_flat_dirs):
  1060. self.android_flat_dirs.append(dir)
  1061. def android_add_maven_repository(self, url):
  1062. if (url not in self.android_maven_repos):
  1063. self.android_maven_repos.append(url)
  1064. def android_add_dependency(self, depline):
  1065. if (depline not in self.android_dependencies):
  1066. self.android_dependencies.append(depline)
  1067. def android_add_java_dir(self, subpath):
  1068. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  1069. if (base_path not in self.android_java_dirs):
  1070. self.android_java_dirs.append(base_path)
  1071. def android_add_res_dir(self, subpath):
  1072. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  1073. if (base_path not in self.android_res_dirs):
  1074. self.android_res_dirs.append(base_path)
  1075. def android_add_aidl_dir(self, subpath):
  1076. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  1077. if (base_path not in self.android_aidl_dirs):
  1078. self.android_aidl_dirs.append(base_path)
  1079. def android_add_jni_dir(self, subpath):
  1080. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + subpath
  1081. if (base_path not in self.android_jni_dirs):
  1082. self.android_jni_dirs.append(base_path)
  1083. def android_add_gradle_plugin(self, plugin):
  1084. if (plugin not in self.android_gradle_plugins):
  1085. self.android_gradle_plugins.append(plugin)
  1086. def android_add_gradle_classpath(self, classpath):
  1087. if (classpath not in self.android_gradle_classpath):
  1088. self.android_gradle_classpath.append(classpath)
  1089. def android_add_default_config(self, config):
  1090. if (config not in self.android_default_config):
  1091. self.android_default_config.append(config)
  1092. def android_add_to_manifest(self, file):
  1093. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  1094. f = open(base_path, "r")
  1095. self.android_manifest_chunk += f.read()
  1096. def android_add_to_permissions(self, file):
  1097. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  1098. f = open(base_path, "r")
  1099. self.android_permission_chunk += f.read()
  1100. def android_add_to_attributes(self, file):
  1101. base_path = self.Dir(".").abspath + "/modules/" + self.current_module + "/" + file
  1102. f = open(base_path, "r")
  1103. self.android_appattributes_chunk += f.read()
  1104. def disable_module(self):
  1105. self.disabled_modules.append(self.current_module)
  1106. def use_windows_spawn_fix(self, platform=None):
  1107. if (os.name != "nt"):
  1108. return # not needed, only for windows
  1109. # On Windows, due to the limited command line length, when creating a static library
  1110. # from a very high number of objects SCons will invoke "ar" once per object file;
  1111. # that makes object files with same names to be overwritten so the last wins and
  1112. # the library looses symbols defined by overwritten objects.
  1113. # By enabling quick append instead of the default mode (replacing), libraries will
  1114. # got built correctly regardless the invokation strategy.
  1115. # Furthermore, since SCons will rebuild the library from scratch when an object file
  1116. # changes, no multiple versions of the same object file will be present.
  1117. self.Replace(ARFLAGS='q')
  1118. import subprocess
  1119. def mySubProcess(cmdline, env):
  1120. prefix = ""
  1121. if(platform == 'javascript'):
  1122. prefix = "python.exe "
  1123. startupinfo = subprocess.STARTUPINFO()
  1124. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  1125. proc = subprocess.Popen(prefix + cmdline, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1126. stderr=subprocess.PIPE, startupinfo=startupinfo, shell=False, env=env)
  1127. data, err = proc.communicate()
  1128. rv = proc.wait()
  1129. if rv:
  1130. print("=====")
  1131. print(err)
  1132. print("=====")
  1133. return rv
  1134. def mySpawn(sh, escape, cmd, args, env):
  1135. newargs = ' '.join(args[1:])
  1136. cmdline = cmd + " " + newargs
  1137. rv = 0
  1138. env = {str(key): str(value) for key, value in iteritems(env)}
  1139. if len(cmdline) > 32000 and cmd.endswith("ar"):
  1140. cmdline = cmd + " " + args[1] + " " + args[2] + " "
  1141. for i in range(3, len(args)):
  1142. rv = mySubProcess(cmdline + args[i], env)
  1143. if rv:
  1144. break
  1145. else:
  1146. rv = mySubProcess(cmdline, env)
  1147. return rv
  1148. self['SPAWN'] = mySpawn
  1149. def split_lib(self, libname):
  1150. import string
  1151. env = self
  1152. num = 0
  1153. cur_base = ""
  1154. max_src = 64
  1155. list = []
  1156. lib_list = []
  1157. for f in getattr(env, libname + "_sources"):
  1158. fname = ""
  1159. if type(f) == type(""):
  1160. fname = env.File(f).path
  1161. else:
  1162. fname = env.File(f)[0].path
  1163. fname = fname.replace("\\", "/")
  1164. base = string.join(fname.split("/")[:2], "/")
  1165. if base != cur_base and len(list) > max_src:
  1166. if num > 0:
  1167. lib = env.Library(libname + str(num), list)
  1168. lib_list.append(lib)
  1169. list = []
  1170. num = num + 1
  1171. cur_base = base
  1172. list.append(f)
  1173. lib = env.Library(libname + str(num), list)
  1174. lib_list.append(lib)
  1175. if len(lib_list) > 0:
  1176. import os, sys
  1177. if os.name == 'posix' and sys.platform == 'msys':
  1178. env.Replace(ARFLAGS=['rcsT'])
  1179. lib = env.Library(libname + "_collated", lib_list)
  1180. lib_list = [lib]
  1181. lib_base = []
  1182. env.add_source_files(lib_base, "*.cpp")
  1183. lib_list.insert(0, env.Library(libname, lib_base))
  1184. env.Prepend(LIBS=lib_list)
  1185. def save_active_platforms(apnames, ap):
  1186. for x in ap:
  1187. names = ['logo']
  1188. if os.path.isfile(x + "/run_icon.png"):
  1189. names.append('run_icon')
  1190. for name in names:
  1191. pngf = open(x + "/" + name + ".png", "rb")
  1192. b = pngf.read(1)
  1193. str = " /* AUTOGENERATED FILE, DO NOT EDIT */ \n"
  1194. str += " static const unsigned char _" + x[9:] + "_" + name + "[]={"
  1195. while(len(b) == 1):
  1196. str += hex(ord(b))
  1197. b = pngf.read(1)
  1198. if (len(b) == 1):
  1199. str += ","
  1200. str += "};\n"
  1201. wf = x + "/" + name + ".gen.h"
  1202. pngw = open(wf, "w")
  1203. pngw.write(str)
  1204. def no_verbose(sys, env):
  1205. # If the output is not a terminal, do nothing
  1206. if not sys.stdout.isatty():
  1207. return
  1208. colors = {}
  1209. colors['cyan'] = '\033[96m'
  1210. colors['purple'] = '\033[95m'
  1211. colors['blue'] = '\033[94m'
  1212. colors['green'] = '\033[92m'
  1213. colors['yellow'] = '\033[93m'
  1214. colors['red'] = '\033[91m'
  1215. colors['end'] = '\033[0m'
  1216. compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  1217. java_compile_source_message = '%sCompiling %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  1218. compile_shared_source_message = '%sCompiling shared %s==> %s$SOURCE%s' % (colors['blue'], colors['purple'], colors['yellow'], colors['end'])
  1219. link_program_message = '%sLinking Program %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  1220. link_library_message = '%sLinking Static Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  1221. ranlib_library_message = '%sRanlib Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  1222. link_shared_library_message = '%sLinking Shared Library %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  1223. java_library_message = '%sCreating Java Archive %s==> %s$TARGET%s' % (colors['red'], colors['purple'], colors['yellow'], colors['end'])
  1224. env.Append(CXXCOMSTR=[compile_source_message])
  1225. env.Append(CCCOMSTR=[compile_source_message])
  1226. env.Append(SHCCCOMSTR=[compile_shared_source_message])
  1227. env.Append(SHCXXCOMSTR=[compile_shared_source_message])
  1228. env.Append(ARCOMSTR=[link_library_message])
  1229. env.Append(RANLIBCOMSTR=[ranlib_library_message])
  1230. env.Append(SHLINKCOMSTR=[link_shared_library_message])
  1231. env.Append(LINKCOMSTR=[link_program_message])
  1232. env.Append(JARCOMSTR=[java_library_message])
  1233. env.Append(JAVACCOMSTR=[java_compile_source_message])
  1234. def detect_visual_c_compiler_version(tools_env):
  1235. # tools_env is the variable scons uses to call tools that execute tasks, SCons's env['ENV'] that executes tasks...
  1236. # (see the SCons documentation for more information on what it does)...
  1237. # in order for this function to be well encapsulated i choose to force it to receive SCons's TOOLS env (env['ENV']
  1238. # and not scons setup environment (env)... so make sure you call the right environment on it or it will fail to detect
  1239. # the proper vc version that will be called
  1240. # These is no flag to give to visual c compilers to set the architecture, ie scons bits argument (32,64,ARM etc)
  1241. # There are many different cl.exe files that are run, and each one compiles & links to a different architecture
  1242. # As far as I know, the only way to figure out what compiler will be run when Scons calls cl.exe via Program()
  1243. # is to check the PATH varaible and figure out which one will be called first. Code bellow does that and returns:
  1244. # the following string values:
  1245. # "" Compiler not detected
  1246. # "amd64" Native 64 bit compiler
  1247. # "amd64_x86" 64 bit Cross Compiler for 32 bit
  1248. # "x86" Native 32 bit compiler
  1249. # "x86_amd64" 32 bit Cross Compiler for 64 bit
  1250. # There are other architectures, but Godot does not support them currently, so this function does not detect arm/amd64_arm
  1251. # and similar architectures/compilers
  1252. # Set chosen compiler to "not detected"
  1253. vc_chosen_compiler_index = -1
  1254. vc_chosen_compiler_str = ""
  1255. # Start with Pre VS 2017 checks which uses VCINSTALLDIR:
  1256. if 'VCINSTALLDIR' in tools_env:
  1257. # print("Checking VCINSTALLDIR")
  1258. # find() works with -1 so big ifs bellow are needed... the simplest solution, in fact
  1259. # First test if amd64 and amd64_x86 compilers are present in the path
  1260. vc_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64;")
  1261. if(vc_amd64_compiler_detection_index > -1):
  1262. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  1263. vc_chosen_compiler_str = "amd64"
  1264. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN\\amd64_x86;")
  1265. if(vc_amd64_x86_compiler_detection_index > -1
  1266. and (vc_chosen_compiler_index == -1
  1267. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  1268. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  1269. vc_chosen_compiler_str = "amd64_x86"
  1270. # Now check the 32 bit compilers
  1271. vc_x86_compiler_detection_index = tools_env["PATH"].find(tools_env["VCINSTALLDIR"] + "BIN;")
  1272. if(vc_x86_compiler_detection_index > -1
  1273. and (vc_chosen_compiler_index == -1
  1274. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  1275. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  1276. vc_chosen_compiler_str = "x86"
  1277. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].find(tools_env['VCINSTALLDIR'] + "BIN\\x86_amd64;")
  1278. if(vc_x86_amd64_compiler_detection_index > -1
  1279. and (vc_chosen_compiler_index == -1
  1280. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  1281. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  1282. vc_chosen_compiler_str = "x86_amd64"
  1283. # and for VS 2017 and newer we check VCTOOLSINSTALLDIR:
  1284. if 'VCTOOLSINSTALLDIR' in tools_env:
  1285. # print("Checking VCTOOLSINSTALLDIR")
  1286. # Newer versions have a different path available
  1287. vc_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X64;")
  1288. if(vc_amd64_compiler_detection_index > -1):
  1289. vc_chosen_compiler_index = vc_amd64_compiler_detection_index
  1290. vc_chosen_compiler_str = "amd64"
  1291. vc_amd64_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX64\\X86;")
  1292. if(vc_amd64_x86_compiler_detection_index > -1
  1293. and (vc_chosen_compiler_index == -1
  1294. or vc_chosen_compiler_index > vc_amd64_x86_compiler_detection_index)):
  1295. vc_chosen_compiler_index = vc_amd64_x86_compiler_detection_index
  1296. vc_chosen_compiler_str = "amd64_x86"
  1297. vc_x86_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X86;")
  1298. if(vc_x86_compiler_detection_index > -1
  1299. and (vc_chosen_compiler_index == -1
  1300. or vc_chosen_compiler_index > vc_x86_compiler_detection_index)):
  1301. vc_chosen_compiler_index = vc_x86_compiler_detection_index
  1302. vc_chosen_compiler_str = "x86"
  1303. vc_x86_amd64_compiler_detection_index = tools_env["PATH"].upper().find(tools_env['VCTOOLSINSTALLDIR'].upper() + "BIN\\HOSTX86\\X64;")
  1304. if(vc_x86_amd64_compiler_detection_index > -1
  1305. and (vc_chosen_compiler_index == -1
  1306. or vc_chosen_compiler_index > vc_x86_amd64_compiler_detection_index)):
  1307. vc_chosen_compiler_index = vc_x86_amd64_compiler_detection_index
  1308. vc_chosen_compiler_str = "x86_amd64"
  1309. # debug help
  1310. # print(vc_amd64_compiler_detection_index)
  1311. # print(vc_amd64_x86_compiler_detection_index)
  1312. # print(vc_x86_compiler_detection_index)
  1313. # print(vc_x86_amd64_compiler_detection_index)
  1314. # print("chosen "+str(vc_chosen_compiler_index)+ " | "+str(vc_chosen_compiler_str))
  1315. return vc_chosen_compiler_str
  1316. def find_visual_c_batch_file(env):
  1317. from SCons.Tool.MSCommon.vc import get_default_version, get_host_target, find_batch_file
  1318. version = get_default_version(env)
  1319. (host_platform, target_platform,req_target_platform) = get_host_target(env)
  1320. return find_batch_file(env, version, host_platform, target_platform)[0]
  1321. def generate_vs_project(env, num_jobs):
  1322. batch_file = find_visual_c_batch_file(env)
  1323. if batch_file:
  1324. def build_commandline(commands):
  1325. common_build_prefix = ['cmd /V /C set "plat=$(PlatformTarget)"',
  1326. '(if "$(PlatformTarget)"=="x64" (set "plat=x86_amd64"))',
  1327. 'set "tools=yes"',
  1328. '(if "$(Configuration)"=="release" (set "tools=no"))',
  1329. 'call "' + batch_file + '" !plat!']
  1330. result = " ^& ".join(common_build_prefix + [commands])
  1331. # print("Building commandline: ", result)
  1332. return result
  1333. env.AddToVSProject(env.core_sources)
  1334. env.AddToVSProject(env.main_sources)
  1335. env.AddToVSProject(env.modules_sources)
  1336. env.AddToVSProject(env.scene_sources)
  1337. env.AddToVSProject(env.servers_sources)
  1338. env.AddToVSProject(env.editor_sources)
  1339. # windows allows us to have spaces in paths, so we need
  1340. # to double quote off the directory. However, the path ends
  1341. # in a backslash, so we need to remove this, lest it escape the
  1342. # last double quote off, confusing MSBuild
  1343. env['MSVSBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  1344. env['MSVSREBUILDCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" platform=windows target=$(Configuration) tools=!tools! vsproj=yes -j' + str(num_jobs))
  1345. env['MSVSCLEANCOM'] = build_commandline('scons --directory="$(ProjectDir.TrimEnd(\'\\\'))" --clean platform=windows target=$(Configuration) tools=!tools! -j' + str(num_jobs))
  1346. # This version information (Win32, x64, Debug, Release, Release_Debug seems to be
  1347. # required for Visual Studio to understand that it needs to generate an NMAKE
  1348. # project. Do not modify without knowing what you are doing.
  1349. debug_variants = ['debug|Win32'] + ['debug|x64']
  1350. release_variants = ['release|Win32'] + ['release|x64']
  1351. release_debug_variants = ['release_debug|Win32'] + ['release_debug|x64']
  1352. variants = debug_variants + release_variants + release_debug_variants
  1353. debug_targets = ['bin\\godot.windows.tools.32.exe'] + ['bin\\godot.windows.tools.64.exe']
  1354. release_targets = ['bin\\godot.windows.opt.32.exe'] + ['bin\\godot.windows.opt.64.exe']
  1355. release_debug_targets = ['bin\\godot.windows.opt.tools.32.exe'] + ['bin\\godot.windows.opt.tools.64.exe']
  1356. targets = debug_targets + release_targets + release_debug_targets
  1357. msvproj = env.MSVSProject(target=['#godot' + env['MSVSPROJECTSUFFIX']],
  1358. incs=env.vs_incs,
  1359. srcs=env.vs_srcs,
  1360. runfile=targets,
  1361. buildtarget=targets,
  1362. auto_build_solution=1,
  1363. variant=variants)
  1364. else:
  1365. print("Could not locate Visual Studio batch file for setting up the build environment. Not generating VS project.")
  1366. def precious_program(env, program, sources, **args):
  1367. program = env.ProgramOriginal(program, sources, **args)
  1368. env.Precious(program)
  1369. return program