GenerateWebGLRenderingContext.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  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. struct NameAndType {
  61. StringView name;
  62. struct {
  63. StringView type;
  64. int element_count { 0 };
  65. } return_type;
  66. };
  67. static void generate_get_parameter(SourceGenerator& generator)
  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. { "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. { "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 || type_name == "WebGLFramebuffer"sv || type_name == "WebGLRenderbuffer"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. static void generate_get_buffer_parameter(SourceGenerator& generator)
  222. {
  223. Vector<NameAndType> const name_to_type = {
  224. { "BUFFER_SIZE"sv, { "GLint"sv } },
  225. { "BUFFER_USAGE"sv, { "GLenum"sv } },
  226. };
  227. generator.append(" switch (pname) {");
  228. for (auto const& name_and_type : name_to_type) {
  229. auto const& parameter_name = name_and_type.name;
  230. auto const& type_name = name_and_type.return_type.type;
  231. StringBuilder string_builder;
  232. SourceGenerator impl_generator { string_builder };
  233. impl_generator.set("parameter_name", parameter_name);
  234. impl_generator.set("type_name", type_name);
  235. impl_generator.append(R"~~~(
  236. case GL_@parameter_name@: {
  237. GLint result;
  238. glGetBufferParameteriv(target, GL_@parameter_name@, &result);
  239. return JS::Value(result);
  240. }
  241. )~~~");
  242. generator.append(string_builder.string_view());
  243. }
  244. generator.appendln(R"~~~(
  245. default:
  246. TODO();
  247. })~~~");
  248. }
  249. ErrorOr<int> serenity_main(Main::Arguments arguments)
  250. {
  251. StringView generated_header_path;
  252. StringView generated_implementation_path;
  253. Vector<ByteString> base_paths;
  254. StringView webgl_context_idl_path;
  255. Core::ArgsParser args_parser;
  256. args_parser.add_option(webgl_context_idl_path, "Path to the WebGLRenderingContext.idl file", "webgl-idl-path", 'i', "webgl-idl-path");
  257. args_parser.add_option(Core::ArgsParser::Option {
  258. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  259. .help_string = "Path to root of IDL file tree(s)",
  260. .long_name = "base-path",
  261. .short_name = 'b',
  262. .value_name = "base-path",
  263. .accept_value = [&](StringView s) {
  264. base_paths.append(s);
  265. return true;
  266. },
  267. });
  268. args_parser.add_option(generated_header_path, "Path to the Enums header file to generate", "generated-header-path", 'h', "generated-header-path");
  269. args_parser.add_option(generated_implementation_path, "Path to the Enums implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  270. args_parser.parse(arguments);
  271. auto generated_header_file = TRY(Core::File::open(generated_header_path, Core::File::OpenMode::Write));
  272. auto generated_implementation_file = TRY(Core::File::open(generated_implementation_path, Core::File::OpenMode::Write));
  273. auto idl_file = MUST(Core::File::open(webgl_context_idl_path, Core::File::OpenMode::Read));
  274. auto webgl_context_idl_file_content = MUST(idl_file->read_until_eof());
  275. Vector<ByteString> import_base_paths;
  276. for (auto const& base_path : base_paths) {
  277. VERIFY(!base_path.is_empty());
  278. import_base_paths.append(base_path);
  279. }
  280. IDL::Parser parser(webgl_context_idl_path, StringView(webgl_context_idl_file_content), import_base_paths);
  281. auto const& interface = parser.parse();
  282. StringBuilder header_file_string_builder;
  283. SourceGenerator header_file_generator { header_file_string_builder };
  284. StringBuilder implementation_file_string_builder;
  285. SourceGenerator implementation_file_generator { implementation_file_string_builder };
  286. implementation_file_generator.append(R"~~~(
  287. #include <LibJS/Runtime/ArrayBuffer.h>
  288. #include <LibJS/Runtime/TypedArray.h>
  289. #include <LibWeb/HTML/HTMLCanvasElement.h>
  290. #include <LibWeb/HTML/HTMLImageElement.h>
  291. #include <LibWeb/HTML/HTMLVideoElement.h>
  292. #include <LibWeb/HTML/ImageBitmap.h>
  293. #include <LibWeb/HTML/ImageData.h>
  294. #include <LibWeb/WebGL/OpenGLContext.h>
  295. #include <LibWeb/WebGL/WebGLActiveInfo.h>
  296. #include <LibWeb/WebGL/WebGLBuffer.h>
  297. #include <LibWeb/WebGL/WebGLFramebuffer.h>
  298. #include <LibWeb/WebGL/WebGLProgram.h>
  299. #include <LibWeb/WebGL/WebGLRenderbuffer.h>
  300. #include <LibWeb/WebGL/WebGLRenderingContextImpl.h>
  301. #include <LibWeb/WebGL/WebGLShader.h>
  302. #include <LibWeb/WebGL/WebGLTexture.h>
  303. #include <LibWeb/WebGL/WebGLUniformLocation.h>
  304. #include <LibWeb/WebIDL/Buffers.h>
  305. #include <GLES2/gl2.h>
  306. #include <GLES2/gl2ext.h>
  307. namespace Web::WebGL {
  308. static Vector<GLchar> null_terminated_string(StringView string)
  309. {
  310. Vector<GLchar> result;
  311. for (auto c : string.bytes())
  312. result.append(c);
  313. result.append('\\0');
  314. return result;
  315. }
  316. WebGLRenderingContextImpl::WebGLRenderingContextImpl(JS::Realm& realm, NonnullOwnPtr<OpenGLContext> context)
  317. : m_realm(realm)
  318. , m_context(move(context))
  319. {
  320. }
  321. )~~~");
  322. header_file_generator.append(R"~~~(
  323. #pragma once
  324. #include <AK/NonnullOwnPtr.h>
  325. #include <LibGC/Ptr.h>
  326. #include <LibGfx/Bitmap.h>
  327. #include <LibWeb/Bindings/PlatformObject.h>
  328. #include <LibWeb/Forward.h>
  329. #include <LibWeb/WebIDL/Types.h>
  330. namespace Web::WebGL {
  331. using namespace Web::HTML;
  332. class WebGLRenderingContextImpl {
  333. public:
  334. WebGLRenderingContextImpl(JS::Realm&, NonnullOwnPtr<OpenGLContext>);
  335. OpenGLContext& context() { return *m_context; }
  336. virtual void present() = 0;
  337. virtual void needs_to_present() = 0;
  338. )~~~");
  339. for (auto const& function : interface.functions) {
  340. if (function.extended_attributes.contains("FIXME")) {
  341. continue;
  342. }
  343. if (function.name == "getSupportedExtensions"sv || function.name == "getExtension"sv || function.name == "getContextAttributes"sv || function.name == "isContextLost"sv) {
  344. // Implemented in WebGLRenderingContext
  345. continue;
  346. }
  347. StringBuilder function_declaration;
  348. StringBuilder function_parameters;
  349. for (size_t i = 0; i < function.parameters.size(); ++i) {
  350. auto const& parameter = function.parameters[i];
  351. function_parameters.append(to_cpp_type(*parameter.type, interface));
  352. function_parameters.append(" "sv);
  353. function_parameters.append(parameter.name);
  354. if (i != function.parameters.size() - 1) {
  355. function_parameters.append(", "sv);
  356. }
  357. }
  358. auto function_name = function.name.to_snakecase();
  359. function_declaration.append(to_cpp_type(*function.return_type, interface));
  360. function_declaration.append(" "sv);
  361. function_declaration.append(function_name);
  362. function_declaration.append("("sv);
  363. function_declaration.append(function_parameters.string_view());
  364. function_declaration.append(");"sv);
  365. header_file_generator.append(" "sv);
  366. header_file_generator.append(function_declaration.string_view());
  367. header_file_generator.append("\n"sv);
  368. StringBuilder function_impl;
  369. SourceGenerator function_impl_generator { function_impl };
  370. ScopeGuard function_guard { [&] {
  371. function_impl_generator.append("}\n"sv);
  372. implementation_file_generator.append(function_impl_generator.as_string_view().bytes());
  373. } };
  374. function_impl_generator.set("function_name", function_name);
  375. function_impl_generator.set("function_parameters", function_parameters.string_view());
  376. function_impl_generator.set("function_return_type", to_cpp_type(*function.return_type, interface));
  377. function_impl_generator.append(R"~~~(
  378. @function_return_type@ WebGLRenderingContextImpl::@function_name@(@function_parameters@)
  379. {
  380. m_context->make_current();
  381. )~~~");
  382. if (gl_function_modifies_framebuffer(function.name)) {
  383. function_impl_generator.append(" m_context->notify_content_will_change();\n"sv);
  384. }
  385. if (function.name == "createBuffer"sv) {
  386. function_impl_generator.append(R"~~~(
  387. GLuint handle = 0;
  388. glGenBuffers(1, &handle);
  389. return WebGLBuffer::create(m_realm, handle);
  390. )~~~");
  391. continue;
  392. }
  393. if (function.name == "createTexture"sv) {
  394. function_impl_generator.append(R"~~~(
  395. GLuint handle = 0;
  396. glGenTextures(1, &handle);
  397. return WebGLTexture::create(m_realm, handle);
  398. )~~~");
  399. continue;
  400. }
  401. if (function.name == "createFramebuffer"sv) {
  402. function_impl_generator.append(R"~~~(
  403. GLuint handle = 0;
  404. glGenFramebuffers(1, &handle);
  405. return WebGLFramebuffer::create(m_realm, handle);
  406. )~~~");
  407. continue;
  408. }
  409. if (function.name == "createRenderbuffer"sv) {
  410. function_impl_generator.append(R"~~~(
  411. GLuint handle = 0;
  412. glGenRenderbuffers(1, &handle);
  413. return WebGLRenderbuffer::create(m_realm, handle);
  414. )~~~");
  415. continue;
  416. }
  417. if (function.name == "shaderSource"sv) {
  418. function_impl_generator.append(R"~~~(
  419. Vector<GLchar*> strings;
  420. auto string = null_terminated_string(source);
  421. strings.append(string.data());
  422. Vector<GLint> length;
  423. length.append(source.bytes().size());
  424. glShaderSource(shader->handle(), 1, strings.data(), length.data());
  425. )~~~");
  426. continue;
  427. }
  428. if (function.name == "getAttribLocation"sv) {
  429. function_impl_generator.append(R"~~~(
  430. auto name_str = null_terminated_string(name);
  431. return glGetAttribLocation(program->handle(), name_str.data());
  432. )~~~");
  433. continue;
  434. }
  435. if (function.name == "vertexAttribPointer"sv) {
  436. function_impl_generator.append(R"~~~(
  437. glVertexAttribPointer(index, size, type, normalized, stride, reinterpret_cast<void*>(offset));
  438. )~~~");
  439. continue;
  440. }
  441. if (function.name == "texImage2D"sv && function.overload_index == 0) {
  442. function_impl_generator.append(R"~~~(
  443. void const* pixels_ptr = nullptr;
  444. if (pixels) {
  445. auto const& viewed_array_buffer = pixels->viewed_array_buffer();
  446. auto const& byte_buffer = viewed_array_buffer->buffer();
  447. pixels_ptr = byte_buffer.data();
  448. }
  449. glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels_ptr);
  450. )~~~");
  451. continue;
  452. }
  453. if (function.name == "texImage2D"sv && function.overload_index == 1) {
  454. // FIXME: If this function is called with an ImageData whose data attribute has been neutered,
  455. // an INVALID_VALUE error is generated.
  456. // FIXME: If this function is called with an ImageBitmap that has been neutered, an INVALID_VALUE
  457. // error is generated.
  458. // FIXME: If this function is called with an HTMLImageElement or HTMLVideoElement whose origin
  459. // differs from the origin of the containing Document, or with an HTMLCanvasElement,
  460. // ImageBitmap or OffscreenCanvas whose bitmap's origin-clean flag is set to false,
  461. // a SECURITY_ERR exception must be thrown. See Origin Restrictions.
  462. // FIXME: If source is null then an INVALID_VALUE error is generated.
  463. function_impl_generator.append(R"~~~(
  464. auto bitmap = source.visit(
  465. [](GC::Root<HTMLImageElement> const& source) -> RefPtr<Gfx::ImmutableBitmap> {
  466. return source->immutable_bitmap();
  467. },
  468. [](GC::Root<HTMLCanvasElement> const& source) -> RefPtr<Gfx::ImmutableBitmap> {
  469. auto surface = source->surface();
  470. if (!surface)
  471. return {};
  472. auto bitmap = MUST(Gfx::Bitmap::create(Gfx::BitmapFormat::RGBA8888, Gfx::AlphaType::Premultiplied, surface->size()));
  473. surface->read_into_bitmap(*bitmap);
  474. return Gfx::ImmutableBitmap::create(*bitmap);
  475. },
  476. [](GC::Root<HTMLVideoElement> const& source) -> RefPtr<Gfx::ImmutableBitmap> {
  477. return Gfx::ImmutableBitmap::create(*source->bitmap());
  478. },
  479. [](GC::Root<ImageBitmap> const& source) -> RefPtr<Gfx::ImmutableBitmap> {
  480. return Gfx::ImmutableBitmap::create(*source->bitmap());
  481. },
  482. [](GC::Root<ImageData> const& source) -> RefPtr<Gfx::ImmutableBitmap> {
  483. return Gfx::ImmutableBitmap::create(source->bitmap());
  484. });
  485. if (!bitmap)
  486. return;
  487. void const* pixels_ptr = bitmap->bitmap()->begin();
  488. int width = bitmap->width();
  489. int height = bitmap->height();
  490. glTexImage2D(target, level, internalformat, width, height, 0, format, type, pixels_ptr);
  491. )~~~");
  492. continue;
  493. }
  494. if (function.name == "getShaderParameter"sv) {
  495. function_impl_generator.append(R"~~~(
  496. GLint result = 0;
  497. glGetShaderiv(shader->handle(), pname, &result);
  498. return JS::Value(result);
  499. )~~~");
  500. continue;
  501. }
  502. if (function.name == "getProgramParameter"sv) {
  503. function_impl_generator.append(R"~~~(
  504. GLint result = 0;
  505. glGetProgramiv(program->handle(), pname, &result);
  506. return JS::Value(result);
  507. )~~~");
  508. continue;
  509. }
  510. if (function.name == "bufferData"sv && function.overload_index == 0) {
  511. function_impl_generator.append(R"~~~(
  512. glBufferData(target, size, 0, usage);
  513. )~~~");
  514. continue;
  515. }
  516. if (function.name == "getUniformLocation"sv) {
  517. function_impl_generator.append(R"~~~(
  518. auto name_str = null_terminated_string(name);
  519. return WebGLUniformLocation::create(m_realm, glGetUniformLocation(program->handle(), name_str.data()));
  520. )~~~");
  521. continue;
  522. }
  523. if (function.name == "drawElements"sv) {
  524. function_impl_generator.append(R"~~~(
  525. glDrawElements(mode, count, type, reinterpret_cast<void*>(offset));
  526. needs_to_present();
  527. )~~~");
  528. continue;
  529. }
  530. if (function.name.starts_with("uniformMatrix"sv)) {
  531. auto number_of_matrix_elements = function.name.substring_view(13, 1);
  532. function_impl_generator.set("number_of_matrix_elements", number_of_matrix_elements);
  533. function_impl_generator.append(R"~~~(
  534. auto matrix_size = @number_of_matrix_elements@ * @number_of_matrix_elements@;
  535. if (value.has<Vector<float>>()) {
  536. auto& data = value.get<Vector<float>>();
  537. glUniformMatrix@number_of_matrix_elements@fv(location->handle(), data.size() / matrix_size, transpose, data.data());
  538. return;
  539. }
  540. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*value.get<GC::Root<WebIDL::BufferSource>>()->raw_object());
  541. auto& float32_array = verify_cast<JS::Float32Array>(typed_array_base);
  542. float const* data = float32_array.data().data();
  543. auto count = float32_array.array_length().length() / matrix_size;
  544. glUniformMatrix@number_of_matrix_elements@fv(location->handle(), count, transpose, data);
  545. )~~~");
  546. continue;
  547. }
  548. if (function.name == "uniform1fv"sv || function.name == "uniform2fv"sv || function.name == "uniform3fv"sv || function.name == "uniform4fv"sv) {
  549. auto number_of_matrix_elements = function.name.substring_view(7, 1);
  550. function_impl_generator.set("number_of_matrix_elements", number_of_matrix_elements);
  551. function_impl_generator.append(R"~~~(
  552. if (v.has<Vector<float>>()) {
  553. auto& data = v.get<Vector<float>>();
  554. glUniform@number_of_matrix_elements@fv(location->handle(), data.size() / @number_of_matrix_elements@, data.data());
  555. return;
  556. }
  557. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*v.get<GC::Root<WebIDL::BufferSource>>()->raw_object());
  558. auto& float32_array = verify_cast<JS::Float32Array>(typed_array_base);
  559. float const* data = float32_array.data().data();
  560. auto count = float32_array.array_length().length() / @number_of_matrix_elements@;
  561. glUniform@number_of_matrix_elements@fv(location->handle(), count, data);
  562. )~~~");
  563. continue;
  564. }
  565. if (function.name == "uniform1iv"sv || function.name == "uniform2iv"sv || function.name == "uniform3iv"sv || function.name == "uniform4iv"sv) {
  566. auto number_of_matrix_elements = function.name.substring_view(7, 1);
  567. function_impl_generator.set("number_of_matrix_elements", number_of_matrix_elements);
  568. function_impl_generator.append(R"~~~(
  569. if (v.has<Vector<int>>()) {
  570. auto& data = v.get<Vector<int>>();
  571. glUniform@number_of_matrix_elements@iv(location->handle(), data.size() / @number_of_matrix_elements@, data.data());
  572. return;
  573. }
  574. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*v.get<GC::Root<WebIDL::BufferSource>>()->raw_object());
  575. auto& int32_array = verify_cast<JS::Int32Array>(typed_array_base);
  576. int const* data = int32_array.data().data();
  577. auto count = int32_array.array_length().length() / @number_of_matrix_elements@;
  578. glUniform@number_of_matrix_elements@iv(location->handle(), count, data);
  579. )~~~");
  580. continue;
  581. }
  582. if (function.name == "getParameter"sv) {
  583. generate_get_parameter(function_impl_generator);
  584. continue;
  585. }
  586. if (function.name == "getBufferParameter"sv) {
  587. generate_get_buffer_parameter(function_impl_generator);
  588. continue;
  589. }
  590. if (function.name == "getActiveUniform"sv) {
  591. function_impl_generator.append(R"~~~(
  592. GLint size = 0;
  593. GLenum type = 0;
  594. GLsizei buf_size = 256;
  595. GLsizei length = 0;
  596. GLchar name[256];
  597. glGetActiveUniform(program->handle(), index, buf_size, &length, &size, &type, name);
  598. auto readonly_bytes = ReadonlyBytes { name, static_cast<size_t>(length) };
  599. return WebGLActiveInfo::create(m_realm, String::from_utf8_without_validation(readonly_bytes), type, size);
  600. )~~~");
  601. continue;
  602. }
  603. if (function.name == "getActiveAttrib"sv) {
  604. function_impl_generator.append(R"~~~(
  605. GLint size = 0;
  606. GLenum type = 0;
  607. GLsizei buf_size = 256;
  608. GLsizei length = 0;
  609. GLchar name[256];
  610. glGetActiveAttrib(program->handle(), index, buf_size, &length, &size, &type, name);
  611. auto readonly_bytes = ReadonlyBytes { name, static_cast<size_t>(length) };
  612. return WebGLActiveInfo::create(m_realm, String::from_utf8_without_validation(readonly_bytes), type, size);
  613. )~~~");
  614. continue;
  615. }
  616. if (function.name == "getShaderInfoLog"sv) {
  617. function_impl_generator.append(R"~~~(
  618. GLint info_log_length = 0;
  619. glGetShaderiv(shader->handle(), GL_INFO_LOG_LENGTH, &info_log_length);
  620. Vector<GLchar> info_log;
  621. info_log.resize(info_log_length);
  622. if (!info_log_length)
  623. return String {};
  624. glGetShaderInfoLog(shader->handle(), info_log_length, nullptr, info_log.data());
  625. return String::from_utf8_without_validation(ReadonlyBytes { info_log.data(), static_cast<size_t>(info_log_length - 1) });
  626. )~~~");
  627. continue;
  628. }
  629. if (function.name == "getProgramInfoLog"sv) {
  630. function_impl_generator.append(R"~~~(
  631. GLint info_log_length = 0;
  632. glGetProgramiv(program->handle(), GL_INFO_LOG_LENGTH, &info_log_length);
  633. Vector<GLchar> info_log;
  634. info_log.resize(info_log_length);
  635. if (!info_log_length)
  636. return String {};
  637. glGetProgramInfoLog(program->handle(), info_log_length, nullptr, info_log.data());
  638. return String::from_utf8_without_validation(ReadonlyBytes { info_log.data(), static_cast<size_t>(info_log_length - 1) });
  639. )~~~");
  640. continue;
  641. }
  642. if (function.name == "deleteBuffer"sv) {
  643. function_impl_generator.append(R"~~~(
  644. auto handle = buffer ? buffer->handle() : 0;
  645. glDeleteBuffers(1, &handle);
  646. )~~~");
  647. continue;
  648. }
  649. if (function.name == "deleteFramebuffer"sv) {
  650. function_impl_generator.append(R"~~~(
  651. auto handle = framebuffer ? framebuffer->handle() : 0;
  652. glDeleteFramebuffers(1, &handle);
  653. )~~~");
  654. continue;
  655. }
  656. if (function.name == "deleteTexture"sv) {
  657. function_impl_generator.append(R"~~~(
  658. auto handle = texture ? texture->handle() : 0;
  659. glDeleteTextures(1, &handle);
  660. )~~~");
  661. continue;
  662. }
  663. Vector<ByteString> gl_call_arguments;
  664. for (size_t i = 0; i < function.parameters.size(); ++i) {
  665. auto const& parameter = function.parameters[i];
  666. if (parameter.type->is_numeric() || parameter.type->is_boolean()) {
  667. gl_call_arguments.append(parameter.name);
  668. continue;
  669. }
  670. if (parameter.type->is_string()) {
  671. function_impl_generator.set("parameter_name", parameter.name);
  672. function_impl_generator.append(R"~~~(
  673. auto @parameter_name@_null_terminated = null_terminated_string(@parameter_name@);
  674. )~~~");
  675. gl_call_arguments.append(ByteString::formatted("{}_null_terminated.data()", parameter.name));
  676. continue;
  677. }
  678. if (is_webgl_object_type(parameter.type->name())) {
  679. gl_call_arguments.append(ByteString::formatted("{} ? {}->handle() : 0", parameter.name, parameter.name));
  680. continue;
  681. }
  682. if (parameter.type->name() == "BufferSource"sv) {
  683. function_impl_generator.set("buffer_source_name", parameter.name);
  684. function_impl_generator.append(R"~~~(
  685. void const* ptr = nullptr;
  686. size_t byte_size = 0;
  687. if (@buffer_source_name@->is_typed_array_base()) {
  688. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*@buffer_source_name@->raw_object());
  689. ptr = typed_array_base.viewed_array_buffer()->buffer().data();
  690. byte_size = typed_array_base.viewed_array_buffer()->byte_length();
  691. } else if (@buffer_source_name@->is_data_view()) {
  692. VERIFY_NOT_REACHED();
  693. } else {
  694. VERIFY_NOT_REACHED();
  695. }
  696. )~~~");
  697. gl_call_arguments.append(ByteString::formatted("byte_size"));
  698. gl_call_arguments.append(ByteString::formatted("ptr"));
  699. continue;
  700. }
  701. VERIFY_NOT_REACHED();
  702. }
  703. StringBuilder gl_call_arguments_string_builder;
  704. gl_call_arguments_string_builder.join(", "sv, gl_call_arguments);
  705. auto gl_call_string = ByteString::formatted("{}({})", idl_to_gl_function_name(function.name), gl_call_arguments_string_builder.string_view());
  706. function_impl_generator.set("call_string", gl_call_string);
  707. if (gl_function_modifies_framebuffer(function.name)) {
  708. function_impl_generator.append(" needs_to_present();\n"sv);
  709. }
  710. if (function.return_type->name() == "undefined"sv) {
  711. function_impl_generator.append(" @call_string@;"sv);
  712. } else if (function.return_type->is_integer() || function.return_type->is_boolean()) {
  713. function_impl_generator.append(" return @call_string@;"sv);
  714. } else if (is_webgl_object_type(function.return_type->name())) {
  715. function_impl_generator.set("return_type_name", function.return_type->name());
  716. function_impl_generator.append(" return @return_type_name@::create(m_realm, @call_string@);"sv);
  717. } else {
  718. VERIFY_NOT_REACHED();
  719. }
  720. function_impl_generator.append("\n"sv);
  721. }
  722. header_file_generator.append(R"~~~(
  723. private:
  724. GC::Ref<JS::Realm> m_realm;
  725. NonnullOwnPtr<OpenGLContext> m_context;
  726. };
  727. }
  728. )~~~");
  729. implementation_file_generator.append(R"~~~(
  730. }
  731. )~~~");
  732. MUST(generated_header_file->write_until_depleted(header_file_generator.as_string_view().bytes()));
  733. MUST(generated_implementation_file->write_until_depleted(implementation_file_generator.as_string_view().bytes()));
  734. return 0;
  735. }