methods.py 65 KB

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