GenerateWebGLRenderingContext.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. /*
  2. * Copyright (c) 2024, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "BindingsGenerator/IDLGenerators.h"
  7. #include <AK/SourceGenerator.h>
  8. #include <AK/StringBuilder.h>
  9. #include <LibCore/ArgsParser.h>
  10. #include <LibCore/File.h>
  11. #include <LibIDL/IDLParser.h>
  12. #include <LibMain/Main.h>
  13. static bool is_webgl_object_type(StringView type_name)
  14. {
  15. return type_name == "WebGLShader"sv
  16. || type_name == "WebGLBuffer"sv
  17. || type_name == "WebGLFramebuffer"sv
  18. || type_name == "WebGLProgram"sv
  19. || type_name == "WebGLRenderbuffer"sv
  20. || type_name == "WebGLTexture"sv
  21. || type_name == "WebGLUniformLocation"sv;
  22. }
  23. static bool gl_function_modifies_framebuffer(StringView function_name)
  24. {
  25. return function_name == "clearColor"sv || function_name == "drawArrays"sv || function_name == "drawElements"sv;
  26. }
  27. static ByteString to_cpp_type(const IDL::Type& type, const IDL::Interface& interface)
  28. {
  29. if (type.name() == "undefined"sv)
  30. return "void"sv;
  31. if (type.name() == "object"sv) {
  32. if (type.is_nullable())
  33. return "JS::Object*"sv;
  34. return "JS::Object&"sv;
  35. }
  36. if (type.name() == "DOMString"sv) {
  37. if (type.is_nullable())
  38. return "Optional<String>"sv;
  39. return "String"sv;
  40. }
  41. auto cpp_type = idl_type_name_to_cpp_type(type, interface);
  42. return cpp_type.name;
  43. }
  44. static ByteString idl_to_gl_function_name(StringView function_name)
  45. {
  46. StringBuilder gl_function_name_builder;
  47. gl_function_name_builder.append("gl"sv);
  48. for (size_t i = 0; i < function_name.length(); ++i) {
  49. if (i == 0) {
  50. gl_function_name_builder.append(to_ascii_uppercase(function_name[i]));
  51. } else {
  52. gl_function_name_builder.append(function_name[i]);
  53. }
  54. }
  55. if (function_name == "clearDepth"sv || function_name == "depthRange"sv) {
  56. gl_function_name_builder.append("f"sv);
  57. }
  58. return gl_function_name_builder.to_byte_string();
  59. }
  60. static void generate_get_parameter(SourceGenerator& generator)
  61. {
  62. struct NameAndType {
  63. StringView name;
  64. struct {
  65. StringView type;
  66. int element_count { 0 };
  67. } return_type;
  68. };
  69. Vector<NameAndType> const name_to_type = {
  70. { "ACTIVE_TEXTURE"sv, { "GLenum"sv } },
  71. { "ALIASED_LINE_WIDTH_RANGE"sv, { "Float32Array"sv, 2 } },
  72. { "ALIASED_POINT_SIZE_RANGE"sv, { "Float32Array"sv, 2 } },
  73. { "ALPHA_BITS"sv, { "GLint"sv } },
  74. { "ARRAY_BUFFER_BINDING"sv, { "WebGLBuffer"sv } },
  75. { "BLEND"sv, { "GLboolean"sv } },
  76. { "BLEND_COLOR"sv, { "Float32Array"sv, 4 } },
  77. { "BLEND_DST_ALPHA"sv, { "GLenum"sv } },
  78. { "BLEND_DST_RGB"sv, { "GLenum"sv } },
  79. { "BLEND_EQUATION_ALPHA"sv, { "GLenum"sv } },
  80. { "BLEND_EQUATION_RGB"sv, { "GLenum"sv } },
  81. { "BLEND_SRC_ALPHA"sv, { "GLenum"sv } },
  82. { "BLEND_SRC_RGB"sv, { "GLenum"sv } },
  83. { "BLUE_BITS"sv, { "GLint"sv } },
  84. { "COLOR_CLEAR_VALUE"sv, { "Float32Array"sv, 4 } },
  85. // FIXME: { "COLOR_WRITEMASK"sv, { "sequence<GLboolean>"sv, 4 } },
  86. // FIXME: { "COMPRESSED_TEXTURE_FORMATS"sv, { "Uint32Array"sv } },
  87. { "CULL_FACE"sv, { "GLboolean"sv } },
  88. { "CULL_FACE_MODE"sv, { "GLenum"sv } },
  89. { "CURRENT_PROGRAM"sv, { "WebGLProgram"sv } },
  90. { "DEPTH_BITS"sv, { "GLint"sv } },
  91. { "DEPTH_CLEAR_VALUE"sv, { "GLfloat"sv } },
  92. { "DEPTH_FUNC"sv, { "GLenum"sv } },
  93. { "DEPTH_RANGE"sv, { "Float32Array"sv, 2 } },
  94. { "DEPTH_TEST"sv, { "GLboolean"sv } },
  95. { "DEPTH_WRITEMASK"sv, { "GLboolean"sv } },
  96. { "DITHER"sv, { "GLboolean"sv } },
  97. { "ELEMENT_ARRAY_BUFFER_BINDING"sv, { "WebGLBuffer"sv } },
  98. // FIXME: { "FRAMEBUFFER_BINDING"sv, { "WebGLFramebuffer"sv } },
  99. { "FRONT_FACE"sv, { "GLenum"sv } },
  100. { "GENERATE_MIPMAP_HINT"sv, { "GLenum"sv } },
  101. { "GREEN_BITS"sv, { "GLint"sv } },
  102. { "IMPLEMENTATION_COLOR_READ_FORMAT"sv, { "GLenum"sv } },
  103. { "IMPLEMENTATION_COLOR_READ_TYPE"sv, { "GLenum"sv } },
  104. { "LINE_WIDTH"sv, { "GLfloat"sv } },
  105. { "MAX_COMBINED_TEXTURE_IMAGE_UNITS"sv, { "GLint"sv } },
  106. { "MAX_CUBE_MAP_TEXTURE_SIZE"sv, { "GLint"sv } },
  107. { "MAX_FRAGMENT_UNIFORM_VECTORS"sv, { "GLint"sv } },
  108. { "MAX_RENDERBUFFER_SIZE"sv, { "GLint"sv } },
  109. { "MAX_TEXTURE_IMAGE_UNITS"sv, { "GLint"sv } },
  110. { "MAX_TEXTURE_SIZE"sv, { "GLint"sv } },
  111. { "MAX_VARYING_VECTORS"sv, { "GLint"sv } },
  112. { "MAX_VERTEX_ATTRIBS"sv, { "GLint"sv } },
  113. { "MAX_VERTEX_TEXTURE_IMAGE_UNITS"sv, { "GLint"sv } },
  114. { "MAX_VERTEX_UNIFORM_VECTORS"sv, { "GLint"sv } },
  115. { "MAX_VIEWPORT_DIMS"sv, { "Int32Array"sv, 2 } },
  116. { "PACK_ALIGNMENT"sv, { "GLint"sv } },
  117. { "POLYGON_OFFSET_FACTOR"sv, { "GLfloat"sv } },
  118. { "POLYGON_OFFSET_FILL"sv, { "GLboolean"sv } },
  119. { "POLYGON_OFFSET_UNITS"sv, { "GLfloat"sv } },
  120. { "RED_BITS"sv, { "GLint"sv } },
  121. // FIXME: { "RENDERBUFFER_BINDING"sv, { "WebGLRenderbuffer"sv } },
  122. { "RENDERER"sv, { "DOMString"sv } },
  123. { "SAMPLE_ALPHA_TO_COVERAGE"sv, { "GLboolean"sv } },
  124. { "SAMPLE_BUFFERS"sv, { "GLint"sv } },
  125. { "SAMPLE_COVERAGE"sv, { "GLboolean"sv } },
  126. { "SAMPLE_COVERAGE_INVERT"sv, { "GLboolean"sv } },
  127. { "SAMPLE_COVERAGE_VALUE"sv, { "GLfloat"sv } },
  128. { "SAMPLES"sv, { "GLint"sv } },
  129. { "SCISSOR_BOX"sv, { "Int32Array"sv, 4 } },
  130. { "SCISSOR_TEST"sv, { "GLboolean"sv } },
  131. { "SHADING_LANGUAGE_VERSION"sv, { "DOMString"sv } },
  132. { "STENCIL_BACK_FAIL"sv, { "GLenum"sv } },
  133. { "STENCIL_BACK_FUNC"sv, { "GLenum"sv } },
  134. { "STENCIL_BACK_PASS_DEPTH_FAIL"sv, { "GLenum"sv } },
  135. { "STENCIL_BACK_PASS_DEPTH_PASS"sv, { "GLenum"sv } },
  136. { "STENCIL_BACK_REF"sv, { "GLint"sv } },
  137. { "STENCIL_BACK_VALUE_MASK"sv, { "GLuint"sv } },
  138. { "STENCIL_BACK_WRITEMASK"sv, { "GLuint"sv } },
  139. { "STENCIL_BITS"sv, { "GLint"sv } },
  140. { "STENCIL_CLEAR_VALUE"sv, { "GLint"sv } },
  141. { "STENCIL_FAIL"sv, { "GLenum"sv } },
  142. { "STENCIL_FUNC"sv, { "GLenum"sv } },
  143. { "STENCIL_PASS_DEPTH_FAIL"sv, { "GLenum"sv } },
  144. { "STENCIL_PASS_DEPTH_PASS"sv, { "GLenum"sv } },
  145. { "STENCIL_REF"sv, { "GLint"sv } },
  146. { "STENCIL_TEST"sv, { "GLboolean"sv } },
  147. { "STENCIL_VALUE_MASK"sv, { "GLuint"sv } },
  148. { "STENCIL_WRITEMASK"sv, { "GLuint"sv } },
  149. { "SUBPIXEL_BITS"sv, { "GLint"sv } },
  150. { "TEXTURE_BINDING_2D"sv, { "WebGLTexture"sv } },
  151. { "TEXTURE_BINDING_CUBE_MAP"sv, { "WebGLTexture"sv } },
  152. { "UNPACK_ALIGNMENT"sv, { "GLint"sv } },
  153. // FIXME: { "UNPACK_COLORSPACE_CONVERSION_WEBGL"sv, { "GLenum"sv } },
  154. // FIXME: { "UNPACK_FLIP_Y_WEBGL"sv, { "GLboolean"sv } },
  155. // FIXME: { "UNPACK_PREMULTIPLY_ALPHA_WEBGL"sv, { "GLboolean"sv } },
  156. { "VENDOR"sv, { "DOMString"sv } },
  157. { "VERSION"sv, { "DOMString"sv } },
  158. { "VIEWPORT"sv, { "Int32Array"sv, 4 } },
  159. };
  160. auto is_primitive_type = [](StringView type) {
  161. return type == "GLboolean"sv || type == "GLint"sv || type == "GLfloat"sv || type == "GLenum"sv || type == "GLuint"sv;
  162. };
  163. generator.append(" switch (pname) {");
  164. for (auto const& name_and_type : name_to_type) {
  165. auto const& parameter_name = name_and_type.name;
  166. auto const& type_name = name_and_type.return_type.type;
  167. StringBuilder string_builder;
  168. SourceGenerator impl_generator { string_builder };
  169. impl_generator.set("parameter_name", parameter_name);
  170. impl_generator.set("type_name", type_name);
  171. impl_generator.append(R"~~~(
  172. case GL_@parameter_name@: {)~~~");
  173. if (is_primitive_type(type_name)) {
  174. impl_generator.append(R"~~~(
  175. GLint result;
  176. glGetIntegerv(GL_@parameter_name@, &result);
  177. return JS::Value(result);
  178. )~~~");
  179. } else if (type_name == "DOMString"sv) {
  180. impl_generator.append(R"~~~(
  181. auto result = reinterpret_cast<const char*>(glGetString(GL_@parameter_name@));
  182. return JS::PrimitiveString::create(m_realm->vm(), ByteString { result });)~~~");
  183. } else if (type_name == "Float32Array"sv || type_name == "Int32Array"sv) {
  184. auto element_count = name_and_type.return_type.element_count;
  185. impl_generator.set("element_count", MUST(String::formatted("{}", element_count)));
  186. if (type_name == "Int32Array"sv) {
  187. impl_generator.set("gl_function_name", "glGetIntegerv"sv);
  188. impl_generator.set("element_type", "GLint"sv);
  189. } else if (type_name == "Float32Array"sv) {
  190. impl_generator.set("gl_function_name", "glGetFloatv"sv);
  191. impl_generator.set("element_type", "GLfloat"sv);
  192. } else {
  193. VERIFY_NOT_REACHED();
  194. }
  195. impl_generator.append(R"~~~(
  196. Array<@element_type@, @element_count@> result;
  197. @gl_function_name@(GL_@parameter_name@, result.data());
  198. auto byte_buffer = MUST(ByteBuffer::copy(result.data(), @element_count@ * sizeof(@element_type@)));
  199. auto array_buffer = JS::ArrayBuffer::create(m_realm, move(byte_buffer));
  200. return JS::@type_name@::create(m_realm, @element_count@, array_buffer);
  201. )~~~");
  202. } else if (type_name == "WebGLProgram"sv || type_name == "WebGLBuffer"sv || type_name == "WebGLTexture"sv) {
  203. impl_generator.append(R"~~~(
  204. GLint result;
  205. glGetIntegerv(GL_@parameter_name@, &result);
  206. if (!result)
  207. return JS::js_null();
  208. return @type_name@::create(m_realm, result);
  209. )~~~");
  210. } else {
  211. VERIFY_NOT_REACHED();
  212. }
  213. impl_generator.append(" }");
  214. generator.append(string_builder.string_view());
  215. }
  216. generator.appendln(R"~~~(
  217. default:
  218. TODO();
  219. })~~~");
  220. }
  221. ErrorOr<int> serenity_main(Main::Arguments arguments)
  222. {
  223. StringView generated_header_path;
  224. StringView generated_implementation_path;
  225. Vector<ByteString> base_paths;
  226. StringView webgl_context_idl_path;
  227. Core::ArgsParser args_parser;
  228. args_parser.add_option(webgl_context_idl_path, "Path to the WebGLRenderingContext.idl file", "webgl-idl-path", 'i', "webgl-idl-path");
  229. args_parser.add_option(Core::ArgsParser::Option {
  230. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  231. .help_string = "Path to root of IDL file tree(s)",
  232. .long_name = "base-path",
  233. .short_name = 'b',
  234. .value_name = "base-path",
  235. .accept_value = [&](StringView s) {
  236. base_paths.append(s);
  237. return true;
  238. },
  239. });
  240. args_parser.add_option(generated_header_path, "Path to the Enums header file to generate", "generated-header-path", 'h', "generated-header-path");
  241. args_parser.add_option(generated_implementation_path, "Path to the Enums implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  242. args_parser.parse(arguments);
  243. auto generated_header_file = TRY(Core::File::open(generated_header_path, Core::File::OpenMode::Write));
  244. auto generated_implementation_file = TRY(Core::File::open(generated_implementation_path, Core::File::OpenMode::Write));
  245. auto idl_file = MUST(Core::File::open(webgl_context_idl_path, Core::File::OpenMode::Read));
  246. auto webgl_context_idl_file_content = MUST(idl_file->read_until_eof());
  247. Vector<ByteString> import_base_paths;
  248. for (auto const& base_path : base_paths) {
  249. VERIFY(!base_path.is_empty());
  250. import_base_paths.append(base_path);
  251. }
  252. IDL::Parser parser(webgl_context_idl_path, StringView(webgl_context_idl_file_content), import_base_paths);
  253. auto const& interface = parser.parse();
  254. StringBuilder header_file_string_builder;
  255. SourceGenerator header_file_generator { header_file_string_builder };
  256. StringBuilder implementation_file_string_builder;
  257. SourceGenerator implementation_file_generator { implementation_file_string_builder };
  258. implementation_file_generator.append(R"~~~(
  259. #include <LibJS/Runtime/ArrayBuffer.h>
  260. #include <LibJS/Runtime/TypedArray.h>
  261. #include <LibWeb/WebGL/OpenGLContext.h>
  262. #include <LibWeb/WebGL/WebGLActiveInfo.h>
  263. #include <LibWeb/WebGL/WebGLBuffer.h>
  264. #include <LibWeb/WebGL/WebGLFramebuffer.h>
  265. #include <LibWeb/WebGL/WebGLProgram.h>
  266. #include <LibWeb/WebGL/WebGLRenderbuffer.h>
  267. #include <LibWeb/WebGL/WebGLRenderingContextImpl.h>
  268. #include <LibWeb/WebGL/WebGLShader.h>
  269. #include <LibWeb/WebGL/WebGLTexture.h>
  270. #include <LibWeb/WebGL/WebGLUniformLocation.h>
  271. #include <LibWeb/WebIDL/Buffers.h>
  272. #include <GLES2/gl2.h>
  273. #include <GLES2/gl2ext.h>
  274. namespace Web::WebGL {
  275. static Vector<GLchar> null_terminated_string(StringView string)
  276. {
  277. Vector<GLchar> result;
  278. for (auto c : string.bytes())
  279. result.append(c);
  280. result.append('\\0');
  281. return result;
  282. }
  283. WebGLRenderingContextImpl::WebGLRenderingContextImpl(JS::Realm& realm, NonnullOwnPtr<OpenGLContext> context)
  284. : m_realm(realm)
  285. , m_context(move(context))
  286. {
  287. }
  288. )~~~");
  289. header_file_generator.append(R"~~~(
  290. #pragma once
  291. #include <AK/NonnullOwnPtr.h>
  292. #include <LibGC/Ptr.h>
  293. #include <LibGfx/Bitmap.h>
  294. #include <LibWeb/Bindings/PlatformObject.h>
  295. #include <LibWeb/Forward.h>
  296. #include <LibWeb/HTML/HTMLCanvasElement.h>
  297. #include <LibWeb/HTML/HTMLImageElement.h>
  298. #include <LibWeb/WebIDL/Types.h>
  299. namespace Web::WebGL {
  300. using namespace Web::HTML;
  301. class WebGLRenderingContextImpl {
  302. public:
  303. WebGLRenderingContextImpl(JS::Realm&, NonnullOwnPtr<OpenGLContext>);
  304. OpenGLContext& context() { return *m_context; }
  305. virtual void present() = 0;
  306. virtual void needs_to_present() = 0;
  307. )~~~");
  308. for (auto const& function : interface.functions) {
  309. if (function.extended_attributes.contains("FIXME")) {
  310. continue;
  311. }
  312. if (function.name == "getSupportedExtensions"sv || function.name == "getExtension"sv || function.name == "getContextAttributes"sv || function.name == "isContextLost"sv) {
  313. // Implemented in WebGLRenderingContext
  314. continue;
  315. }
  316. StringBuilder function_declaration;
  317. StringBuilder function_parameters;
  318. for (size_t i = 0; i < function.parameters.size(); ++i) {
  319. auto const& parameter = function.parameters[i];
  320. function_parameters.append(to_cpp_type(*parameter.type, interface));
  321. function_parameters.append(" "sv);
  322. function_parameters.append(parameter.name);
  323. if (i != function.parameters.size() - 1) {
  324. function_parameters.append(", "sv);
  325. }
  326. }
  327. auto function_name = function.name.to_snakecase();
  328. function_declaration.append(to_cpp_type(*function.return_type, interface));
  329. function_declaration.append(" "sv);
  330. function_declaration.append(function_name);
  331. function_declaration.append("("sv);
  332. function_declaration.append(function_parameters.string_view());
  333. function_declaration.append(");"sv);
  334. header_file_generator.append(" "sv);
  335. header_file_generator.append(function_declaration.string_view());
  336. header_file_generator.append("\n"sv);
  337. StringBuilder function_impl;
  338. SourceGenerator function_impl_generator { function_impl };
  339. ScopeGuard function_guard { [&] {
  340. function_impl_generator.append("}\n"sv);
  341. implementation_file_generator.append(function_impl_generator.as_string_view().bytes());
  342. } };
  343. function_impl_generator.set("function_name", function_name);
  344. function_impl_generator.set("function_parameters", function_parameters.string_view());
  345. function_impl_generator.set("function_return_type", to_cpp_type(*function.return_type, interface));
  346. function_impl_generator.append(R"~~~(
  347. @function_return_type@ WebGLRenderingContextImpl::@function_name@(@function_parameters@)
  348. {
  349. m_context->make_current();
  350. )~~~");
  351. if (gl_function_modifies_framebuffer(function.name)) {
  352. function_impl_generator.append(" m_context->notify_content_will_change();\n"sv);
  353. }
  354. if (function.name == "createBuffer"sv) {
  355. function_impl_generator.append(R"~~~(
  356. GLuint handle = 0;
  357. glGenBuffers(1, &handle);
  358. return WebGLBuffer::create(m_realm, handle);
  359. )~~~");
  360. continue;
  361. }
  362. if (function.name == "createTexture"sv) {
  363. function_impl_generator.append(R"~~~(
  364. GLuint handle = 0;
  365. glGenTextures(1, &handle);
  366. return WebGLTexture::create(m_realm, handle);
  367. )~~~");
  368. continue;
  369. }
  370. if (function.name == "shaderSource"sv) {
  371. function_impl_generator.append(R"~~~(
  372. Vector<GLchar*> strings;
  373. auto string = null_terminated_string(source);
  374. strings.append(string.data());
  375. Vector<GLint> length;
  376. length.append(source.bytes().size());
  377. glShaderSource(shader->handle(), 1, strings.data(), length.data());
  378. )~~~");
  379. continue;
  380. }
  381. if (function.name == "getAttribLocation"sv) {
  382. function_impl_generator.append(R"~~~(
  383. auto name_str = null_terminated_string(name);
  384. return glGetAttribLocation(program->handle(), name_str.data());
  385. )~~~");
  386. continue;
  387. }
  388. if (function.name == "vertexAttribPointer"sv) {
  389. function_impl_generator.append(R"~~~(
  390. glVertexAttribPointer(index, size, type, normalized, stride, reinterpret_cast<void*>(offset));
  391. )~~~");
  392. continue;
  393. }
  394. if (function.name == "texImage2D"sv && function.overload_index == 0) {
  395. function_impl_generator.append(R"~~~(
  396. void const* pixels_ptr = nullptr;
  397. if (pixels) {
  398. auto const& viewed_array_buffer = pixels->viewed_array_buffer();
  399. auto const& byte_buffer = viewed_array_buffer->buffer();
  400. pixels_ptr = byte_buffer.data();
  401. }
  402. glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels_ptr);
  403. )~~~");
  404. continue;
  405. }
  406. if (function.name == "getShaderParameter"sv) {
  407. function_impl_generator.append(R"~~~(
  408. GLint result = 0;
  409. glGetShaderiv(shader->handle(), pname, &result);
  410. return JS::Value(result);
  411. )~~~");
  412. continue;
  413. }
  414. if (function.name == "getProgramParameter"sv) {
  415. function_impl_generator.append(R"~~~(
  416. GLint result = 0;
  417. glGetProgramiv(program->handle(), pname, &result);
  418. return JS::Value(result);
  419. )~~~");
  420. continue;
  421. }
  422. if (function.name == "bufferData"sv && function.overload_index == 0) {
  423. function_impl_generator.append(R"~~~(
  424. glBufferData(target, size, 0, usage);
  425. )~~~");
  426. continue;
  427. }
  428. if (function.name == "getUniformLocation"sv) {
  429. function_impl_generator.append(R"~~~(
  430. auto name_str = null_terminated_string(name);
  431. return WebGLUniformLocation::create(m_realm, glGetUniformLocation(program->handle(), name_str.data()));
  432. )~~~");
  433. continue;
  434. }
  435. if (function.name == "drawElements"sv) {
  436. function_impl_generator.append(R"~~~(
  437. glDrawElements(mode, count, type, reinterpret_cast<void*>(offset));
  438. needs_to_present();
  439. )~~~");
  440. continue;
  441. }
  442. if (function.name.starts_with("uniformMatrix"sv)) {
  443. auto number_of_matrix_elements = function.name.substring_view(13, 1);
  444. function_impl_generator.set("number_of_matrix_elements", number_of_matrix_elements);
  445. function_impl_generator.append(R"~~~(
  446. auto matrix_size = @number_of_matrix_elements@ * @number_of_matrix_elements@;
  447. if (value.has<Vector<float>>()) {
  448. auto& data = value.get<Vector<float>>();
  449. glUniformMatrix@number_of_matrix_elements@fv(location->handle(), data.size() / matrix_size, transpose, data.data());
  450. return;
  451. }
  452. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*value.get<GC::Root<WebIDL::BufferSource>>()->raw_object());
  453. auto& float32_array = verify_cast<JS::Float32Array>(typed_array_base);
  454. float const* data = float32_array.data().data();
  455. auto count = float32_array.array_length().length() / matrix_size;
  456. glUniformMatrix@number_of_matrix_elements@fv(location->handle(), count, transpose, data);
  457. )~~~");
  458. continue;
  459. }
  460. if (function.name == "uniform1fv"sv || function.name == "uniform2fv"sv || function.name == "uniform3fv"sv || function.name == "uniform4fv"sv) {
  461. auto number_of_matrix_elements = function.name.substring_view(7, 1);
  462. function_impl_generator.set("number_of_matrix_elements", number_of_matrix_elements);
  463. function_impl_generator.append(R"~~~(
  464. if (v.has<Vector<float>>()) {
  465. auto& data = v.get<Vector<float>>();
  466. glUniform@number_of_matrix_elements@fv(location->handle(), data.size() / @number_of_matrix_elements@, data.data());
  467. return;
  468. }
  469. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*v.get<GC::Root<WebIDL::BufferSource>>()->raw_object());
  470. auto& float32_array = verify_cast<JS::Float32Array>(typed_array_base);
  471. float const* data = float32_array.data().data();
  472. auto count = float32_array.array_length().length() / @number_of_matrix_elements@;
  473. glUniform@number_of_matrix_elements@fv(location->handle(), count, data);
  474. )~~~");
  475. continue;
  476. }
  477. if (function.name == "getParameter"sv) {
  478. generate_get_parameter(function_impl_generator);
  479. continue;
  480. }
  481. if (function.name == "getActiveUniform"sv) {
  482. function_impl_generator.append(R"~~~(
  483. GLint size = 0;
  484. GLenum type = 0;
  485. GLsizei buf_size = 256;
  486. GLsizei length = 0;
  487. GLchar name[256];
  488. glGetActiveUniform(program->handle(), index, buf_size, &length, &size, &type, name);
  489. auto readonly_bytes = ReadonlyBytes { name, static_cast<size_t>(length) };
  490. return WebGLActiveInfo::create(m_realm, String::from_utf8_without_validation(readonly_bytes), type, size);
  491. )~~~");
  492. continue;
  493. }
  494. if (function.name == "getActiveAttrib"sv) {
  495. function_impl_generator.append(R"~~~(
  496. GLint size = 0;
  497. GLenum type = 0;
  498. GLsizei buf_size = 256;
  499. GLsizei length = 0;
  500. GLchar name[256];
  501. glGetActiveAttrib(program->handle(), index, buf_size, &length, &size, &type, name);
  502. auto readonly_bytes = ReadonlyBytes { name, static_cast<size_t>(length) };
  503. return WebGLActiveInfo::create(m_realm, String::from_utf8_without_validation(readonly_bytes), type, size);
  504. )~~~");
  505. continue;
  506. }
  507. if (function.name == "getShaderInfoLog"sv) {
  508. function_impl_generator.append(R"~~~(
  509. GLint info_log_length = 0;
  510. glGetShaderiv(shader->handle(), GL_INFO_LOG_LENGTH, &info_log_length);
  511. Vector<GLchar> info_log;
  512. info_log.resize(info_log_length);
  513. if (!info_log_length)
  514. return String {};
  515. glGetShaderInfoLog(shader->handle(), info_log_length, nullptr, info_log.data());
  516. return String::from_utf8_without_validation(ReadonlyBytes { info_log.data(), static_cast<size_t>(info_log_length - 1) });
  517. )~~~");
  518. continue;
  519. }
  520. if (function.name == "getProgramInfoLog"sv) {
  521. function_impl_generator.append(R"~~~(
  522. GLint info_log_length = 0;
  523. glGetProgramiv(program->handle(), GL_INFO_LOG_LENGTH, &info_log_length);
  524. Vector<GLchar> info_log;
  525. info_log.resize(info_log_length);
  526. if (!info_log_length)
  527. return String {};
  528. glGetProgramInfoLog(program->handle(), info_log_length, nullptr, info_log.data());
  529. return String::from_utf8_without_validation(ReadonlyBytes { info_log.data(), static_cast<size_t>(info_log_length - 1) });
  530. )~~~");
  531. continue;
  532. }
  533. Vector<ByteString> gl_call_arguments;
  534. for (size_t i = 0; i < function.parameters.size(); ++i) {
  535. auto const& parameter = function.parameters[i];
  536. if (parameter.type->is_numeric() || parameter.type->is_boolean()) {
  537. gl_call_arguments.append(parameter.name);
  538. continue;
  539. }
  540. if (parameter.type->is_string()) {
  541. function_impl_generator.set("parameter_name", parameter.name);
  542. function_impl_generator.append(R"~~~(
  543. auto @parameter_name@_null_terminated = null_terminated_string(@parameter_name@);
  544. )~~~");
  545. gl_call_arguments.append(ByteString::formatted("{}_null_terminated.data()", parameter.name));
  546. continue;
  547. }
  548. if (is_webgl_object_type(parameter.type->name())) {
  549. gl_call_arguments.append(ByteString::formatted("{} ? {}->handle() : 0", parameter.name, parameter.name));
  550. continue;
  551. }
  552. if (parameter.type->name() == "BufferSource"sv) {
  553. function_impl_generator.set("buffer_source_name", parameter.name);
  554. function_impl_generator.append(R"~~~(
  555. void const* ptr = nullptr;
  556. size_t byte_size = 0;
  557. if (@buffer_source_name@->is_typed_array_base()) {
  558. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*@buffer_source_name@->raw_object());
  559. ptr = typed_array_base.viewed_array_buffer()->buffer().data();
  560. byte_size = typed_array_base.viewed_array_buffer()->byte_length();
  561. } else if (@buffer_source_name@->is_data_view()) {
  562. VERIFY_NOT_REACHED();
  563. } else {
  564. VERIFY_NOT_REACHED();
  565. }
  566. )~~~");
  567. gl_call_arguments.append(ByteString::formatted("byte_size"));
  568. gl_call_arguments.append(ByteString::formatted("ptr"));
  569. continue;
  570. }
  571. VERIFY_NOT_REACHED();
  572. }
  573. StringBuilder gl_call_arguments_string_builder;
  574. gl_call_arguments_string_builder.join(", "sv, gl_call_arguments);
  575. auto gl_call_string = ByteString::formatted("{}({})", idl_to_gl_function_name(function.name), gl_call_arguments_string_builder.string_view());
  576. function_impl_generator.set("call_string", gl_call_string);
  577. if (gl_function_modifies_framebuffer(function.name)) {
  578. function_impl_generator.append(" needs_to_present();\n"sv);
  579. }
  580. if (function.return_type->name() == "undefined"sv) {
  581. function_impl_generator.append(" @call_string@;"sv);
  582. } else if (function.return_type->is_integer() || function.return_type->is_boolean()) {
  583. function_impl_generator.append(" return @call_string@;"sv);
  584. } else if (is_webgl_object_type(function.return_type->name())) {
  585. function_impl_generator.set("return_type_name", function.return_type->name());
  586. function_impl_generator.append(" return @return_type_name@::create(m_realm, @call_string@);"sv);
  587. } else {
  588. VERIFY_NOT_REACHED();
  589. }
  590. function_impl_generator.append("\n"sv);
  591. }
  592. header_file_generator.append(R"~~~(
  593. private:
  594. GC::Ref<JS::Realm> m_realm;
  595. NonnullOwnPtr<OpenGLContext> m_context;
  596. };
  597. }
  598. )~~~");
  599. implementation_file_generator.append(R"~~~(
  600. }
  601. )~~~");
  602. MUST(generated_header_file->write_until_depleted(header_file_generator.as_string_view().bytes()));
  603. MUST(generated_implementation_file->write_until_depleted(implementation_file_generator.as_string_view().bytes()));
  604. return 0;
  605. }