GenerateWebGLRenderingContext.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. auto cpp_type = idl_type_name_to_cpp_type(type, interface);
  37. return cpp_type.name;
  38. }
  39. static ByteString idl_to_gl_function_name(StringView function_name)
  40. {
  41. StringBuilder gl_function_name_builder;
  42. gl_function_name_builder.append("gl"sv);
  43. for (size_t i = 0; i < function_name.length(); ++i) {
  44. if (i == 0) {
  45. gl_function_name_builder.append(to_ascii_uppercase(function_name[i]));
  46. } else {
  47. gl_function_name_builder.append(function_name[i]);
  48. }
  49. }
  50. if (function_name == "clearDepth"sv || function_name == "depthRange"sv) {
  51. gl_function_name_builder.append("f"sv);
  52. }
  53. return gl_function_name_builder.to_byte_string();
  54. }
  55. ErrorOr<int> serenity_main(Main::Arguments arguments)
  56. {
  57. StringView generated_header_path;
  58. StringView generated_implementation_path;
  59. Vector<ByteString> base_paths;
  60. StringView webgl_context_idl_path;
  61. Core::ArgsParser args_parser;
  62. args_parser.add_option(webgl_context_idl_path, "Path to the WebGLRenderingContext.idl file", "webgl-idl-path", 'i', "webgl-idl-path");
  63. args_parser.add_option(Core::ArgsParser::Option {
  64. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  65. .help_string = "Path to root of IDL file tree(s)",
  66. .long_name = "base-path",
  67. .short_name = 'b',
  68. .value_name = "base-path",
  69. .accept_value = [&](StringView s) {
  70. base_paths.append(s);
  71. return true;
  72. },
  73. });
  74. args_parser.add_option(generated_header_path, "Path to the Enums header file to generate", "generated-header-path", 'h', "generated-header-path");
  75. args_parser.add_option(generated_implementation_path, "Path to the Enums implementation file to generate", "generated-implementation-path", 'c', "generated-implementation-path");
  76. args_parser.parse(arguments);
  77. auto generated_header_file = TRY(Core::File::open(generated_header_path, Core::File::OpenMode::Write));
  78. auto generated_implementation_file = TRY(Core::File::open(generated_implementation_path, Core::File::OpenMode::Write));
  79. auto idl_file = MUST(Core::File::open(webgl_context_idl_path, Core::File::OpenMode::Read));
  80. auto webgl_context_idl_file_content = MUST(idl_file->read_until_eof());
  81. Vector<ByteString> import_base_paths;
  82. for (auto const& base_path : base_paths) {
  83. VERIFY(!base_path.is_empty());
  84. import_base_paths.append(base_path);
  85. }
  86. IDL::Parser parser(webgl_context_idl_path, StringView(webgl_context_idl_file_content), import_base_paths);
  87. auto const& interface = parser.parse();
  88. StringBuilder header_file_string_builder;
  89. SourceGenerator header_file_generator { header_file_string_builder };
  90. StringBuilder implementation_file_string_builder;
  91. SourceGenerator implementation_file_generator { implementation_file_string_builder };
  92. implementation_file_generator.append(R"~~~(
  93. #include <LibJS/Runtime/ArrayBuffer.h>
  94. #include <LibJS/Runtime/TypedArray.h>
  95. #include <LibWeb/WebGL/OpenGLContext.h>
  96. #include <LibWeb/WebGL/WebGLActiveInfo.h>
  97. #include <LibWeb/WebGL/WebGLBuffer.h>
  98. #include <LibWeb/WebGL/WebGLFramebuffer.h>
  99. #include <LibWeb/WebGL/WebGLProgram.h>
  100. #include <LibWeb/WebGL/WebGLRenderbuffer.h>
  101. #include <LibWeb/WebGL/WebGLRenderingContextImpl.h>
  102. #include <LibWeb/WebGL/WebGLShader.h>
  103. #include <LibWeb/WebGL/WebGLTexture.h>
  104. #include <LibWeb/WebGL/WebGLUniformLocation.h>
  105. #include <LibWeb/WebIDL/Buffers.h>
  106. #include <GLES2/gl2.h>
  107. #include <GLES2/gl2ext.h>
  108. namespace Web::WebGL {
  109. static Vector<GLchar> null_terminated_string(StringView string)
  110. {
  111. Vector<GLchar> result;
  112. for (auto c : string.bytes())
  113. result.append(c);
  114. result.append('\\0');
  115. return result;
  116. }
  117. WebGLRenderingContextImpl::WebGLRenderingContextImpl(JS::Realm& realm, NonnullOwnPtr<OpenGLContext> context)
  118. : m_realm(realm)
  119. , m_context(move(context))
  120. {
  121. }
  122. )~~~");
  123. header_file_generator.append(R"~~~(
  124. #pragma once
  125. #include <AK/NonnullOwnPtr.h>
  126. #include <LibGC/Ptr.h>
  127. #include <LibGfx/Bitmap.h>
  128. #include <LibWeb/Bindings/PlatformObject.h>
  129. #include <LibWeb/Forward.h>
  130. #include <LibWeb/HTML/HTMLCanvasElement.h>
  131. #include <LibWeb/HTML/HTMLImageElement.h>
  132. #include <LibWeb/WebIDL/Types.h>
  133. namespace Web::WebGL {
  134. using namespace Web::HTML;
  135. class WebGLRenderingContextImpl {
  136. public:
  137. WebGLRenderingContextImpl(JS::Realm&, NonnullOwnPtr<OpenGLContext>);
  138. OpenGLContext& context() { return *m_context; }
  139. virtual void present() = 0;
  140. virtual void needs_to_present() = 0;
  141. )~~~");
  142. for (auto const& function : interface.functions) {
  143. if (function.extended_attributes.contains("FIXME")) {
  144. continue;
  145. }
  146. StringBuilder function_declaration;
  147. StringBuilder function_parameters;
  148. for (size_t i = 0; i < function.parameters.size(); ++i) {
  149. auto const& parameter = function.parameters[i];
  150. function_parameters.append(to_cpp_type(*parameter.type, interface));
  151. function_parameters.append(" "sv);
  152. function_parameters.append(parameter.name);
  153. if (i != function.parameters.size() - 1) {
  154. function_parameters.append(", "sv);
  155. }
  156. }
  157. auto function_name = function.name.to_snakecase();
  158. function_declaration.append(to_cpp_type(*function.return_type, interface));
  159. function_declaration.append(" "sv);
  160. function_declaration.append(function_name);
  161. function_declaration.append("("sv);
  162. function_declaration.append(function_parameters.string_view());
  163. function_declaration.append(");"sv);
  164. header_file_generator.append(" "sv);
  165. header_file_generator.append(function_declaration.string_view());
  166. header_file_generator.append("\n"sv);
  167. StringBuilder function_impl;
  168. SourceGenerator function_impl_generator { function_impl };
  169. ScopeGuard function_guard { [&] {
  170. function_impl_generator.append("}\n"sv);
  171. implementation_file_generator.append(function_impl_generator.as_string_view().bytes());
  172. } };
  173. function_impl_generator.set("function_name", function_name);
  174. function_impl_generator.set("function_parameters", function_parameters.string_view());
  175. function_impl_generator.set("function_return_type", to_cpp_type(*function.return_type, interface));
  176. function_impl_generator.append(R"~~~(
  177. @function_return_type@ WebGLRenderingContextImpl::@function_name@(@function_parameters@)
  178. {
  179. m_context->make_current();
  180. )~~~");
  181. if (gl_function_modifies_framebuffer(function.name)) {
  182. function_impl_generator.append(" m_context->notify_content_will_change();\n"sv);
  183. }
  184. if (function.name == "createBuffer"sv) {
  185. function_impl_generator.append(R"~~~(
  186. GLuint handle = 0;
  187. glGenBuffers(1, &handle);
  188. return WebGLBuffer::create(m_realm, handle);
  189. )~~~");
  190. continue;
  191. }
  192. if (function.name == "createTexture"sv) {
  193. function_impl_generator.append(R"~~~(
  194. GLuint handle = 0;
  195. glGenTextures(1, &handle);
  196. return WebGLTexture::create(m_realm, handle);
  197. )~~~");
  198. continue;
  199. }
  200. if (function.name == "shaderSource"sv) {
  201. function_impl_generator.append(R"~~~(
  202. Vector<GLchar*> strings;
  203. auto string = null_terminated_string(source);
  204. strings.append(string.data());
  205. Vector<GLint> length;
  206. length.append(source.bytes().size());
  207. glShaderSource(shader->handle(), 1, strings.data(), length.data());
  208. )~~~");
  209. continue;
  210. }
  211. if (function.name == "getAttribLocation"sv) {
  212. function_impl_generator.append(R"~~~(
  213. auto name_str = null_terminated_string(name);
  214. return glGetAttribLocation(program->handle(), name_str.data());
  215. )~~~");
  216. continue;
  217. }
  218. if (function.name == "vertexAttribPointer"sv) {
  219. function_impl_generator.append(R"~~~(
  220. glVertexAttribPointer(index, size, type, normalized, stride, reinterpret_cast<void*>(offset));
  221. )~~~");
  222. continue;
  223. }
  224. if (function.name == "getShaderParameter"sv) {
  225. function_impl_generator.append(R"~~~(
  226. GLint result = 0;
  227. glGetShaderiv(shader->handle(), pname, &result);
  228. return JS::Value(result);
  229. )~~~");
  230. continue;
  231. }
  232. if (function.name == "getProgramParameter"sv) {
  233. function_impl_generator.append(R"~~~(
  234. GLint result = 0;
  235. glGetProgramiv(program->handle(), pname, &result);
  236. return JS::Value(result);
  237. )~~~");
  238. continue;
  239. }
  240. if (function.name == "bufferData"sv && function.overload_index == 0) {
  241. function_impl_generator.append(R"~~~(
  242. glBufferData(target, size, 0, usage);
  243. )~~~");
  244. continue;
  245. }
  246. if (function.name == "getUniformLocation"sv) {
  247. function_impl_generator.append(R"~~~(
  248. auto name_str = null_terminated_string(name);
  249. return WebGLUniformLocation::create(m_realm, glGetUniformLocation(program->handle(), name_str.data()));
  250. )~~~");
  251. continue;
  252. }
  253. if (function.name == "drawElements"sv) {
  254. function_impl_generator.append(R"~~~(
  255. glDrawElements(mode, count, type, reinterpret_cast<void*>(offset));
  256. needs_to_present();
  257. )~~~");
  258. continue;
  259. }
  260. if (function.name.starts_with("uniformMatrix"sv)) {
  261. auto number_of_matrix_elements = function.name.substring_view(13, 1);
  262. function_impl_generator.set("number_of_matrix_elements", number_of_matrix_elements);
  263. function_impl_generator.append(R"~~~(
  264. auto matrix_size = @number_of_matrix_elements@ * @number_of_matrix_elements@;
  265. if (value.has<Vector<float>>()) {
  266. auto& data = value.get<Vector<float>>();
  267. glUniformMatrix@number_of_matrix_elements@fv(location->handle(), data.size() / matrix_size, transpose, data.data());
  268. return;
  269. }
  270. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*value.get<GC::Root<WebIDL::BufferSource>>()->raw_object());
  271. auto& float32_array = verify_cast<JS::Float32Array>(typed_array_base);
  272. float const* data = float32_array.data().data();
  273. auto count = float32_array.array_length().length() / matrix_size;
  274. glUniformMatrix@number_of_matrix_elements@fv(location->handle(), count, transpose, data);
  275. )~~~");
  276. continue;
  277. }
  278. if (function.name == "uniform1fv"sv || function.name == "uniform2fv"sv || function.name == "uniform3fv"sv || function.name == "uniform4fv"sv) {
  279. auto number_of_matrix_elements = function.name.substring_view(7, 1);
  280. function_impl_generator.set("number_of_matrix_elements", number_of_matrix_elements);
  281. function_impl_generator.append(R"~~~(
  282. if (v.has<Vector<float>>()) {
  283. auto& data = v.get<Vector<float>>();
  284. glUniform@number_of_matrix_elements@fv(location->handle(), data.size() / @number_of_matrix_elements@, data.data());
  285. return;
  286. }
  287. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*v.get<GC::Root<WebIDL::BufferSource>>()->raw_object());
  288. auto& float32_array = verify_cast<JS::Float32Array>(typed_array_base);
  289. float const* data = float32_array.data().data();
  290. auto count = float32_array.array_length().length() / @number_of_matrix_elements@;
  291. glUniform@number_of_matrix_elements@fv(location->handle(), count, data);
  292. )~~~");
  293. continue;
  294. }
  295. if (function.name == "getParameter"sv) {
  296. function_impl_generator.append(R"~~~(
  297. GLint result = 0;
  298. glGetIntegerv(pname, &result);
  299. return JS::Value(result);
  300. )~~~");
  301. continue;
  302. }
  303. if (function.name == "getActiveUniform"sv) {
  304. function_impl_generator.append(R"~~~(
  305. GLint size = 0;
  306. GLenum type = 0;
  307. GLsizei buf_size = 256;
  308. GLsizei length = 0;
  309. GLchar name[256];
  310. glGetActiveUniform(program->handle(), index, buf_size, &length, &size, &type, name);
  311. auto readonly_bytes = ReadonlyBytes { name, static_cast<size_t>(length) };
  312. return WebGLActiveInfo::create(m_realm, String::from_utf8_without_validation(readonly_bytes), type, size);
  313. )~~~");
  314. continue;
  315. }
  316. if (function.name == "getActiveAttrib"sv) {
  317. function_impl_generator.append(R"~~~(
  318. GLint size = 0;
  319. GLenum type = 0;
  320. GLsizei buf_size = 256;
  321. GLsizei length = 0;
  322. GLchar name[256];
  323. glGetActiveAttrib(program->handle(), index, buf_size, &length, &size, &type, name);
  324. auto readonly_bytes = ReadonlyBytes { name, static_cast<size_t>(length) };
  325. return WebGLActiveInfo::create(m_realm, String::from_utf8_without_validation(readonly_bytes), type, size);
  326. )~~~");
  327. continue;
  328. }
  329. Vector<ByteString> gl_call_arguments;
  330. for (size_t i = 0; i < function.parameters.size(); ++i) {
  331. auto const& parameter = function.parameters[i];
  332. if (parameter.type->is_numeric() || parameter.type->is_boolean()) {
  333. gl_call_arguments.append(parameter.name);
  334. continue;
  335. }
  336. if (parameter.type->is_string()) {
  337. gl_call_arguments.append(ByteString::formatted("{}", parameter.name));
  338. continue;
  339. }
  340. if (is_webgl_object_type(parameter.type->name())) {
  341. gl_call_arguments.append(ByteString::formatted("{} ? {}->handle() : 0", parameter.name, parameter.name));
  342. continue;
  343. }
  344. if (parameter.type->name() == "BufferSource"sv) {
  345. function_impl_generator.set("buffer_source_name", parameter.name);
  346. function_impl_generator.append(R"~~~(
  347. void const* ptr = nullptr;
  348. size_t byte_size = 0;
  349. if (@buffer_source_name@->is_typed_array_base()) {
  350. auto& typed_array_base = static_cast<JS::TypedArrayBase&>(*@buffer_source_name@->raw_object());
  351. ptr = typed_array_base.viewed_array_buffer()->buffer().data();
  352. byte_size = typed_array_base.viewed_array_buffer()->byte_length();
  353. } else if (@buffer_source_name@->is_data_view()) {
  354. VERIFY_NOT_REACHED();
  355. } else {
  356. VERIFY_NOT_REACHED();
  357. }
  358. )~~~");
  359. gl_call_arguments.append(ByteString::formatted("byte_size"));
  360. gl_call_arguments.append(ByteString::formatted("ptr"));
  361. continue;
  362. }
  363. VERIFY_NOT_REACHED();
  364. }
  365. StringBuilder gl_call_arguments_string_builder;
  366. gl_call_arguments_string_builder.join(", "sv, gl_call_arguments);
  367. auto gl_call_string = ByteString::formatted("{}({})", idl_to_gl_function_name(function.name), gl_call_arguments_string_builder.string_view());
  368. function_impl_generator.set("call_string", gl_call_string);
  369. if (gl_function_modifies_framebuffer(function.name)) {
  370. function_impl_generator.append(" needs_to_present();\n"sv);
  371. }
  372. if (function.return_type->name() == "undefined"sv) {
  373. function_impl_generator.append(" @call_string@;"sv);
  374. } else if (function.return_type->is_integer() || function.return_type->is_boolean()) {
  375. function_impl_generator.append(" return @call_string@;"sv);
  376. } else if (is_webgl_object_type(function.return_type->name())) {
  377. function_impl_generator.set("return_type_name", function.return_type->name());
  378. function_impl_generator.append(" return @return_type_name@::create(m_realm, @call_string@);"sv);
  379. } else {
  380. VERIFY_NOT_REACHED();
  381. }
  382. function_impl_generator.append("\n"sv);
  383. }
  384. header_file_generator.append(R"~~~(
  385. private:
  386. GC::Ref<JS::Realm> m_realm;
  387. NonnullOwnPtr<OpenGLContext> m_context;
  388. };
  389. }
  390. )~~~");
  391. implementation_file_generator.append(R"~~~(
  392. }
  393. )~~~");
  394. MUST(generated_header_file->write_until_depleted(header_file_generator.as_string_view().bytes()));
  395. MUST(generated_implementation_file->write_until_depleted(implementation_file_generator.as_string_view().bytes()));
  396. return 0;
  397. }