renderer_canvas_render_rd.cpp 124 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266
  1. /**************************************************************************/
  2. /* renderer_canvas_render_rd.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "renderer_canvas_render_rd.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/math/geometry_2d.h"
  33. #include "core/math/math_defs.h"
  34. #include "core/math/math_funcs.h"
  35. #include "core/math/transform_interpolator.h"
  36. #include "renderer_compositor_rd.h"
  37. #include "servers/rendering/renderer_rd/storage_rd/material_storage.h"
  38. #include "servers/rendering/renderer_rd/storage_rd/particles_storage.h"
  39. #include "servers/rendering/renderer_rd/storage_rd/texture_storage.h"
  40. #include "servers/rendering/rendering_server_default.h"
  41. void RendererCanvasRenderRD::_update_transform_2d_to_mat4(const Transform2D &p_transform, float *p_mat4) {
  42. p_mat4[0] = p_transform.columns[0][0];
  43. p_mat4[1] = p_transform.columns[0][1];
  44. p_mat4[2] = 0;
  45. p_mat4[3] = 0;
  46. p_mat4[4] = p_transform.columns[1][0];
  47. p_mat4[5] = p_transform.columns[1][1];
  48. p_mat4[6] = 0;
  49. p_mat4[7] = 0;
  50. p_mat4[8] = 0;
  51. p_mat4[9] = 0;
  52. p_mat4[10] = 1;
  53. p_mat4[11] = 0;
  54. p_mat4[12] = p_transform.columns[2][0];
  55. p_mat4[13] = p_transform.columns[2][1];
  56. p_mat4[14] = 0;
  57. p_mat4[15] = 1;
  58. }
  59. void RendererCanvasRenderRD::_update_transform_2d_to_mat2x4(const Transform2D &p_transform, float *p_mat2x4) {
  60. p_mat2x4[0] = p_transform.columns[0][0];
  61. p_mat2x4[1] = p_transform.columns[1][0];
  62. p_mat2x4[2] = 0;
  63. p_mat2x4[3] = p_transform.columns[2][0];
  64. p_mat2x4[4] = p_transform.columns[0][1];
  65. p_mat2x4[5] = p_transform.columns[1][1];
  66. p_mat2x4[6] = 0;
  67. p_mat2x4[7] = p_transform.columns[2][1];
  68. }
  69. void RendererCanvasRenderRD::_update_transform_2d_to_mat2x3(const Transform2D &p_transform, float *p_mat2x3) {
  70. p_mat2x3[0] = p_transform.columns[0][0];
  71. p_mat2x3[1] = p_transform.columns[0][1];
  72. p_mat2x3[2] = p_transform.columns[1][0];
  73. p_mat2x3[3] = p_transform.columns[1][1];
  74. p_mat2x3[4] = p_transform.columns[2][0];
  75. p_mat2x3[5] = p_transform.columns[2][1];
  76. }
  77. void RendererCanvasRenderRD::_update_transform_to_mat4(const Transform3D &p_transform, float *p_mat4) {
  78. p_mat4[0] = p_transform.basis.rows[0][0];
  79. p_mat4[1] = p_transform.basis.rows[1][0];
  80. p_mat4[2] = p_transform.basis.rows[2][0];
  81. p_mat4[3] = 0;
  82. p_mat4[4] = p_transform.basis.rows[0][1];
  83. p_mat4[5] = p_transform.basis.rows[1][1];
  84. p_mat4[6] = p_transform.basis.rows[2][1];
  85. p_mat4[7] = 0;
  86. p_mat4[8] = p_transform.basis.rows[0][2];
  87. p_mat4[9] = p_transform.basis.rows[1][2];
  88. p_mat4[10] = p_transform.basis.rows[2][2];
  89. p_mat4[11] = 0;
  90. p_mat4[12] = p_transform.origin.x;
  91. p_mat4[13] = p_transform.origin.y;
  92. p_mat4[14] = p_transform.origin.z;
  93. p_mat4[15] = 1;
  94. }
  95. RendererCanvasRender::PolygonID RendererCanvasRenderRD::request_polygon(const Vector<int> &p_indices, const Vector<Point2> &p_points, const Vector<Color> &p_colors, const Vector<Point2> &p_uvs, const Vector<int> &p_bones, const Vector<float> &p_weights) {
  96. // Care must be taken to generate array formats
  97. // in ways where they could be reused, so we will
  98. // put single-occuring elements first, and repeated
  99. // elements later. This way the generated formats are
  100. // the same no matter the length of the arrays.
  101. // This dramatically reduces the amount of pipeline objects
  102. // that need to be created for these formats.
  103. RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton();
  104. uint32_t vertex_count = p_points.size();
  105. uint32_t stride = 2; //vertices always repeat
  106. if ((uint32_t)p_colors.size() == vertex_count || p_colors.size() == 1) {
  107. stride += 4;
  108. }
  109. if ((uint32_t)p_uvs.size() == vertex_count) {
  110. stride += 2;
  111. }
  112. if ((uint32_t)p_bones.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {
  113. stride += 4;
  114. }
  115. uint32_t buffer_size = stride * p_points.size();
  116. Vector<uint8_t> polygon_buffer;
  117. polygon_buffer.resize(buffer_size * sizeof(float));
  118. Vector<RD::VertexAttribute> descriptions;
  119. descriptions.resize(5);
  120. Vector<RID> buffers;
  121. buffers.resize(5);
  122. {
  123. uint8_t *r = polygon_buffer.ptrw();
  124. float *fptr = reinterpret_cast<float *>(r);
  125. uint32_t *uptr = reinterpret_cast<uint32_t *>(r);
  126. uint32_t base_offset = 0;
  127. { //vertices
  128. RD::VertexAttribute vd;
  129. vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;
  130. vd.offset = base_offset * sizeof(float);
  131. vd.location = RS::ARRAY_VERTEX;
  132. vd.stride = stride * sizeof(float);
  133. descriptions.write[0] = vd;
  134. const Vector2 *points_ptr = p_points.ptr();
  135. for (uint32_t i = 0; i < vertex_count; i++) {
  136. fptr[base_offset + i * stride + 0] = points_ptr[i].x;
  137. fptr[base_offset + i * stride + 1] = points_ptr[i].y;
  138. }
  139. base_offset += 2;
  140. }
  141. //colors
  142. if ((uint32_t)p_colors.size() == vertex_count || p_colors.size() == 1) {
  143. RD::VertexAttribute vd;
  144. vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  145. vd.offset = base_offset * sizeof(float);
  146. vd.location = RS::ARRAY_COLOR;
  147. vd.stride = stride * sizeof(float);
  148. descriptions.write[1] = vd;
  149. if (p_colors.size() == 1) {
  150. Color color = p_colors[0];
  151. for (uint32_t i = 0; i < vertex_count; i++) {
  152. fptr[base_offset + i * stride + 0] = color.r;
  153. fptr[base_offset + i * stride + 1] = color.g;
  154. fptr[base_offset + i * stride + 2] = color.b;
  155. fptr[base_offset + i * stride + 3] = color.a;
  156. }
  157. } else {
  158. const Color *color_ptr = p_colors.ptr();
  159. for (uint32_t i = 0; i < vertex_count; i++) {
  160. fptr[base_offset + i * stride + 0] = color_ptr[i].r;
  161. fptr[base_offset + i * stride + 1] = color_ptr[i].g;
  162. fptr[base_offset + i * stride + 2] = color_ptr[i].b;
  163. fptr[base_offset + i * stride + 3] = color_ptr[i].a;
  164. }
  165. }
  166. base_offset += 4;
  167. } else {
  168. RD::VertexAttribute vd;
  169. vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  170. vd.offset = 0;
  171. vd.location = RS::ARRAY_COLOR;
  172. vd.stride = 0;
  173. descriptions.write[1] = vd;
  174. buffers.write[1] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::MeshStorage::DEFAULT_RD_BUFFER_COLOR);
  175. }
  176. //uvs
  177. if ((uint32_t)p_uvs.size() == vertex_count) {
  178. RD::VertexAttribute vd;
  179. vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;
  180. vd.offset = base_offset * sizeof(float);
  181. vd.location = RS::ARRAY_TEX_UV;
  182. vd.stride = stride * sizeof(float);
  183. descriptions.write[2] = vd;
  184. const Vector2 *uv_ptr = p_uvs.ptr();
  185. for (uint32_t i = 0; i < vertex_count; i++) {
  186. fptr[base_offset + i * stride + 0] = uv_ptr[i].x;
  187. fptr[base_offset + i * stride + 1] = uv_ptr[i].y;
  188. }
  189. base_offset += 2;
  190. } else {
  191. RD::VertexAttribute vd;
  192. vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;
  193. vd.offset = 0;
  194. vd.location = RS::ARRAY_TEX_UV;
  195. vd.stride = 0;
  196. descriptions.write[2] = vd;
  197. buffers.write[2] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::MeshStorage::DEFAULT_RD_BUFFER_TEX_UV);
  198. }
  199. //bones
  200. if ((uint32_t)p_indices.size() == vertex_count * 4 && (uint32_t)p_weights.size() == vertex_count * 4) {
  201. RD::VertexAttribute vd;
  202. vd.format = RD::DATA_FORMAT_R16G16B16A16_UINT;
  203. vd.offset = base_offset * sizeof(float);
  204. vd.location = RS::ARRAY_BONES;
  205. vd.stride = stride * sizeof(float);
  206. descriptions.write[3] = vd;
  207. const int *bone_ptr = p_bones.ptr();
  208. for (uint32_t i = 0; i < vertex_count; i++) {
  209. uint16_t *bone16w = (uint16_t *)&uptr[base_offset + i * stride];
  210. bone16w[0] = bone_ptr[i * 4 + 0];
  211. bone16w[1] = bone_ptr[i * 4 + 1];
  212. bone16w[2] = bone_ptr[i * 4 + 2];
  213. bone16w[3] = bone_ptr[i * 4 + 3];
  214. }
  215. base_offset += 2;
  216. } else {
  217. RD::VertexAttribute vd;
  218. vd.format = RD::DATA_FORMAT_R32G32B32A32_UINT;
  219. vd.offset = 0;
  220. vd.location = RS::ARRAY_BONES;
  221. vd.stride = 0;
  222. descriptions.write[3] = vd;
  223. buffers.write[3] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::MeshStorage::DEFAULT_RD_BUFFER_BONES);
  224. }
  225. //weights
  226. if ((uint32_t)p_weights.size() == vertex_count * 4) {
  227. RD::VertexAttribute vd;
  228. vd.format = RD::DATA_FORMAT_R16G16B16A16_UNORM;
  229. vd.offset = base_offset * sizeof(float);
  230. vd.location = RS::ARRAY_WEIGHTS;
  231. vd.stride = stride * sizeof(float);
  232. descriptions.write[4] = vd;
  233. const float *weight_ptr = p_weights.ptr();
  234. for (uint32_t i = 0; i < vertex_count; i++) {
  235. uint16_t *weight16w = (uint16_t *)&uptr[base_offset + i * stride];
  236. weight16w[0] = CLAMP(weight_ptr[i * 4 + 0] * 65535, 0, 65535);
  237. weight16w[1] = CLAMP(weight_ptr[i * 4 + 1] * 65535, 0, 65535);
  238. weight16w[2] = CLAMP(weight_ptr[i * 4 + 2] * 65535, 0, 65535);
  239. weight16w[3] = CLAMP(weight_ptr[i * 4 + 3] * 65535, 0, 65535);
  240. }
  241. base_offset += 2;
  242. } else {
  243. RD::VertexAttribute vd;
  244. vd.format = RD::DATA_FORMAT_R32G32B32A32_SFLOAT;
  245. vd.offset = 0;
  246. vd.location = RS::ARRAY_WEIGHTS;
  247. vd.stride = 0;
  248. descriptions.write[4] = vd;
  249. buffers.write[4] = mesh_storage->mesh_get_default_rd_buffer(RendererRD::MeshStorage::DEFAULT_RD_BUFFER_WEIGHTS);
  250. }
  251. //check that everything is as it should be
  252. ERR_FAIL_COND_V(base_offset != stride, 0); //bug
  253. }
  254. RD::VertexFormatID vertex_id = RD::get_singleton()->vertex_format_create(descriptions);
  255. ERR_FAIL_COND_V(vertex_id == RD::INVALID_ID, 0);
  256. PolygonBuffers pb;
  257. pb.vertex_buffer = RD::get_singleton()->vertex_buffer_create(polygon_buffer.size(), polygon_buffer);
  258. for (int i = 0; i < descriptions.size(); i++) {
  259. if (buffers[i] == RID()) { //if put in vertex, use as vertex
  260. buffers.write[i] = pb.vertex_buffer;
  261. }
  262. }
  263. pb.vertex_array = RD::get_singleton()->vertex_array_create(p_points.size(), vertex_id, buffers);
  264. pb.primitive_count = vertex_count;
  265. if (p_indices.size()) {
  266. //create indices, as indices were requested
  267. Vector<uint8_t> index_buffer;
  268. index_buffer.resize(p_indices.size() * sizeof(int32_t));
  269. {
  270. uint8_t *w = index_buffer.ptrw();
  271. memcpy(w, p_indices.ptr(), sizeof(int32_t) * p_indices.size());
  272. }
  273. pb.index_buffer = RD::get_singleton()->index_buffer_create(p_indices.size(), RD::INDEX_BUFFER_FORMAT_UINT32, index_buffer);
  274. pb.indices = RD::get_singleton()->index_array_create(pb.index_buffer, 0, p_indices.size());
  275. pb.primitive_count = p_indices.size();
  276. }
  277. pb.vertex_format_id = vertex_id;
  278. PolygonID id = polygon_buffers.last_id++;
  279. polygon_buffers.polygons[id] = pb;
  280. return id;
  281. }
  282. void RendererCanvasRenderRD::free_polygon(PolygonID p_polygon) {
  283. PolygonBuffers *pb_ptr = polygon_buffers.polygons.getptr(p_polygon);
  284. ERR_FAIL_NULL(pb_ptr);
  285. PolygonBuffers &pb = *pb_ptr;
  286. if (pb.indices.is_valid()) {
  287. RD::get_singleton()->free(pb.indices);
  288. }
  289. if (pb.index_buffer.is_valid()) {
  290. RD::get_singleton()->free(pb.index_buffer);
  291. }
  292. RD::get_singleton()->free(pb.vertex_array);
  293. RD::get_singleton()->free(pb.vertex_buffer);
  294. polygon_buffers.polygons.erase(p_polygon);
  295. }
  296. ////////////////////
  297. static RD::RenderPrimitive _primitive_type_to_render_primitive(RS::PrimitiveType p_primitive) {
  298. switch (p_primitive) {
  299. case RS::PRIMITIVE_POINTS:
  300. return RD::RENDER_PRIMITIVE_POINTS;
  301. case RS::PRIMITIVE_LINES:
  302. return RD::RENDER_PRIMITIVE_LINES;
  303. case RS::PRIMITIVE_LINE_STRIP:
  304. return RD::RENDER_PRIMITIVE_LINESTRIPS;
  305. case RS::PRIMITIVE_TRIANGLES:
  306. return RD::RENDER_PRIMITIVE_TRIANGLES;
  307. case RS::PRIMITIVE_TRIANGLE_STRIP:
  308. return RD::RENDER_PRIMITIVE_TRIANGLE_STRIPS;
  309. default:
  310. return RD::RENDER_PRIMITIVE_MAX;
  311. }
  312. }
  313. _FORCE_INLINE_ static uint32_t _indices_to_primitives(RS::PrimitiveType p_primitive, uint32_t p_indices) {
  314. static const uint32_t divisor[RS::PRIMITIVE_MAX] = { 1, 2, 1, 3, 1 };
  315. static const uint32_t subtractor[RS::PRIMITIVE_MAX] = { 0, 0, 1, 0, 1 };
  316. return (p_indices - subtractor[p_primitive]) / divisor[p_primitive];
  317. }
  318. RID RendererCanvasRenderRD::_create_base_uniform_set(RID p_to_render_target, bool p_backbuffer) {
  319. RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();
  320. RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
  321. //re create canvas state
  322. Vector<RD::Uniform> uniforms;
  323. {
  324. RD::Uniform u;
  325. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  326. u.binding = 1;
  327. u.append_id(state.canvas_state_buffer);
  328. uniforms.push_back(u);
  329. }
  330. {
  331. RD::Uniform u;
  332. u.uniform_type = RD::UNIFORM_TYPE_UNIFORM_BUFFER;
  333. u.binding = 2;
  334. u.append_id(state.lights_uniform_buffer);
  335. uniforms.push_back(u);
  336. }
  337. {
  338. RD::Uniform u;
  339. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  340. u.binding = 3;
  341. u.append_id(RendererRD::TextureStorage::get_singleton()->decal_atlas_get_texture());
  342. uniforms.push_back(u);
  343. }
  344. {
  345. RD::Uniform u;
  346. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  347. u.binding = 4;
  348. u.append_id(state.shadow_texture);
  349. uniforms.push_back(u);
  350. }
  351. {
  352. RD::Uniform u;
  353. u.uniform_type = RD::UNIFORM_TYPE_SAMPLER;
  354. u.binding = 5;
  355. u.append_id(state.shadow_sampler);
  356. uniforms.push_back(u);
  357. }
  358. {
  359. RD::Uniform u;
  360. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  361. u.binding = 6;
  362. RID screen;
  363. if (p_backbuffer) {
  364. screen = texture_storage->render_target_get_rd_texture(p_to_render_target);
  365. } else {
  366. screen = texture_storage->render_target_get_rd_backbuffer(p_to_render_target);
  367. if (screen.is_null()) { //unallocated backbuffer
  368. screen = RendererRD::TextureStorage::get_singleton()->texture_rd_get_default(RendererRD::TextureStorage::DEFAULT_RD_TEXTURE_WHITE);
  369. }
  370. }
  371. u.append_id(screen);
  372. uniforms.push_back(u);
  373. }
  374. {
  375. RD::Uniform u;
  376. u.uniform_type = RD::UNIFORM_TYPE_TEXTURE;
  377. u.binding = 7;
  378. RID sdf = texture_storage->render_target_get_sdf_texture(p_to_render_target);
  379. u.append_id(sdf);
  380. uniforms.push_back(u);
  381. }
  382. {
  383. RD::Uniform u;
  384. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  385. u.binding = 9;
  386. u.append_id(RendererRD::MaterialStorage::get_singleton()->global_shader_uniforms_get_storage_buffer());
  387. uniforms.push_back(u);
  388. }
  389. material_storage->samplers_rd_get_default().append_uniforms(uniforms, SAMPLERS_BINDING_FIRST_INDEX);
  390. RID uniform_set = RD::get_singleton()->uniform_set_create(uniforms, shader.default_version_rd_shader, BASE_UNIFORM_SET);
  391. if (p_backbuffer) {
  392. texture_storage->render_target_set_backbuffer_uniform_set(p_to_render_target, uniform_set);
  393. } else {
  394. texture_storage->render_target_set_framebuffer_uniform_set(p_to_render_target, uniform_set);
  395. }
  396. return uniform_set;
  397. }
  398. RID RendererCanvasRenderRD::_get_pipeline_specialization_or_ubershader(CanvasShaderData *p_shader_data, PipelineKey &r_pipeline_key, PushConstant &r_push_constant, RID p_mesh_instance, void *p_surface, uint32_t p_surface_index, RID *r_vertex_array) {
  399. r_pipeline_key.ubershader = 0;
  400. const uint32_t ubershader_iterations = 1;
  401. while (r_pipeline_key.ubershader < ubershader_iterations) {
  402. if (r_vertex_array != nullptr) {
  403. RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton();
  404. uint64_t input_mask = p_shader_data->get_vertex_input_mask(r_pipeline_key.variant, r_pipeline_key.ubershader);
  405. if (p_mesh_instance.is_valid()) {
  406. mesh_storage->mesh_instance_surface_get_vertex_arrays_and_format(p_mesh_instance, p_surface_index, input_mask, false, *r_vertex_array, r_pipeline_key.vertex_format_id);
  407. } else {
  408. mesh_storage->mesh_surface_get_vertex_arrays_and_format(p_surface, input_mask, false, *r_vertex_array, r_pipeline_key.vertex_format_id);
  409. }
  410. }
  411. if (r_pipeline_key.ubershader) {
  412. r_push_constant.shader_specialization = r_pipeline_key.shader_specialization;
  413. r_pipeline_key.shader_specialization = {};
  414. } else {
  415. r_push_constant.shader_specialization = {};
  416. }
  417. bool wait_for_compilation = r_pipeline_key.ubershader || ubershader_iterations == 1;
  418. RS::PipelineSource source = RS::PIPELINE_SOURCE_CANVAS;
  419. RID pipeline = p_shader_data->pipeline_hash_map.get_pipeline(r_pipeline_key, r_pipeline_key.hash(), wait_for_compilation, source);
  420. if (pipeline.is_valid()) {
  421. return pipeline;
  422. }
  423. r_pipeline_key.ubershader++;
  424. }
  425. // This case should never be reached unless the shader wasn't available.
  426. return RID();
  427. }
  428. void RendererCanvasRenderRD::canvas_render_items(RID p_to_render_target, Item *p_item_list, const Color &p_modulate, Light *p_light_list, Light *p_directional_light_list, const Transform2D &p_canvas_transform, RenderingServer::CanvasItemTextureFilter p_default_filter, RenderingServer::CanvasItemTextureRepeat p_default_repeat, bool p_snap_2d_vertices_to_pixel, bool &r_sdf_used, RenderingMethod::RenderInfo *r_render_info) {
  429. RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();
  430. RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
  431. RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton();
  432. r_sdf_used = false;
  433. int item_count = 0;
  434. //setup canvas state uniforms if needed
  435. Transform2D canvas_transform_inverse = p_canvas_transform.affine_inverse();
  436. //setup directional lights if exist
  437. uint32_t light_count = 0;
  438. uint32_t directional_light_count = 0;
  439. {
  440. Light *l = p_directional_light_list;
  441. uint32_t index = 0;
  442. while (l) {
  443. if (index == state.max_lights_per_render) {
  444. l->render_index_cache = -1;
  445. l = l->next_ptr;
  446. continue;
  447. }
  448. CanvasLight *clight = canvas_light_owner.get_or_null(l->light_internal);
  449. if (!clight) { //unused or invalid texture
  450. l->render_index_cache = -1;
  451. l = l->next_ptr;
  452. ERR_CONTINUE(!clight);
  453. }
  454. Vector2 canvas_light_dir = l->xform_cache.columns[1].normalized();
  455. state.light_uniforms[index].position[0] = -canvas_light_dir.x;
  456. state.light_uniforms[index].position[1] = -canvas_light_dir.y;
  457. _update_transform_2d_to_mat2x4(clight->shadow.directional_xform, state.light_uniforms[index].shadow_matrix);
  458. state.light_uniforms[index].height = l->height; //0..1 here
  459. for (int i = 0; i < 4; i++) {
  460. state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));
  461. state.light_uniforms[index].color[i] = l->color[i];
  462. }
  463. state.light_uniforms[index].color[3] *= l->energy; //use alpha for energy, so base color can go separate
  464. if (state.shadow_fb.is_valid()) {
  465. state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);
  466. state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;
  467. state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;
  468. } else {
  469. state.light_uniforms[index].shadow_pixel_size = 1.0;
  470. state.light_uniforms[index].shadow_z_far_inv = 1.0;
  471. state.light_uniforms[index].shadow_y_ofs = 0;
  472. }
  473. state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;
  474. state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
  475. if (clight->shadow.enabled) {
  476. state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
  477. }
  478. l->render_index_cache = index;
  479. index++;
  480. l = l->next_ptr;
  481. }
  482. light_count = index;
  483. directional_light_count = light_count;
  484. using_directional_lights = directional_light_count > 0;
  485. }
  486. //setup lights if exist
  487. {
  488. Light *l = p_light_list;
  489. uint32_t index = light_count;
  490. while (l) {
  491. if (index == state.max_lights_per_render) {
  492. l->render_index_cache = -1;
  493. l = l->next_ptr;
  494. continue;
  495. }
  496. CanvasLight *clight = canvas_light_owner.get_or_null(l->light_internal);
  497. if (!clight) { //unused or invalid texture
  498. l->render_index_cache = -1;
  499. l = l->next_ptr;
  500. ERR_CONTINUE(!clight);
  501. }
  502. Transform2D final_xform;
  503. if (!RSG::canvas->_interpolation_data.interpolation_enabled || !l->interpolated) {
  504. final_xform = l->xform_curr;
  505. } else {
  506. real_t f = Engine::get_singleton()->get_physics_interpolation_fraction();
  507. TransformInterpolator::interpolate_transform_2d(l->xform_prev, l->xform_curr, final_xform, f);
  508. }
  509. // Convert light position to canvas coordinates, as all computation is done in canvas coordinates to avoid precision loss.
  510. Vector2 canvas_light_pos = p_canvas_transform.xform(final_xform.get_origin());
  511. state.light_uniforms[index].position[0] = canvas_light_pos.x;
  512. state.light_uniforms[index].position[1] = canvas_light_pos.y;
  513. _update_transform_2d_to_mat2x4(l->light_shader_xform.affine_inverse(), state.light_uniforms[index].matrix);
  514. _update_transform_2d_to_mat2x4(l->xform_cache.affine_inverse(), state.light_uniforms[index].shadow_matrix);
  515. state.light_uniforms[index].height = l->height * (p_canvas_transform.columns[0].length() + p_canvas_transform.columns[1].length()) * 0.5; //approximate height conversion to the canvas size, since all calculations are done in canvas coords to avoid precision loss
  516. for (int i = 0; i < 4; i++) {
  517. state.light_uniforms[index].shadow_color[i] = uint8_t(CLAMP(int32_t(l->shadow_color[i] * 255.0), 0, 255));
  518. state.light_uniforms[index].color[i] = l->color[i];
  519. }
  520. state.light_uniforms[index].color[3] *= l->energy; //use alpha for energy, so base color can go separate
  521. if (state.shadow_fb.is_valid()) {
  522. state.light_uniforms[index].shadow_pixel_size = (1.0 / state.shadow_texture_size) * (1.0 + l->shadow_smooth);
  523. state.light_uniforms[index].shadow_z_far_inv = 1.0 / clight->shadow.z_far;
  524. state.light_uniforms[index].shadow_y_ofs = clight->shadow.y_offset;
  525. } else {
  526. state.light_uniforms[index].shadow_pixel_size = 1.0;
  527. state.light_uniforms[index].shadow_z_far_inv = 1.0;
  528. state.light_uniforms[index].shadow_y_ofs = 0;
  529. }
  530. state.light_uniforms[index].flags = l->blend_mode << LIGHT_FLAGS_BLEND_SHIFT;
  531. state.light_uniforms[index].flags |= l->shadow_filter << LIGHT_FLAGS_FILTER_SHIFT;
  532. if (clight->shadow.enabled) {
  533. state.light_uniforms[index].flags |= LIGHT_FLAGS_HAS_SHADOW;
  534. }
  535. if (clight->texture.is_valid()) {
  536. Rect2 atlas_rect = RendererRD::TextureStorage::get_singleton()->decal_atlas_get_texture_rect(clight->texture);
  537. state.light_uniforms[index].atlas_rect[0] = atlas_rect.position.x;
  538. state.light_uniforms[index].atlas_rect[1] = atlas_rect.position.y;
  539. state.light_uniforms[index].atlas_rect[2] = atlas_rect.size.width;
  540. state.light_uniforms[index].atlas_rect[3] = atlas_rect.size.height;
  541. } else {
  542. state.light_uniforms[index].atlas_rect[0] = 0;
  543. state.light_uniforms[index].atlas_rect[1] = 0;
  544. state.light_uniforms[index].atlas_rect[2] = 0;
  545. state.light_uniforms[index].atlas_rect[3] = 0;
  546. }
  547. l->render_index_cache = index;
  548. index++;
  549. l = l->next_ptr;
  550. }
  551. light_count = index;
  552. }
  553. if (light_count > 0) {
  554. RD::get_singleton()->buffer_update(state.lights_uniform_buffer, 0, sizeof(LightUniform) * light_count, &state.light_uniforms[0]);
  555. }
  556. bool use_linear_colors = texture_storage->render_target_is_using_hdr(p_to_render_target);
  557. {
  558. //update canvas state uniform buffer
  559. State::Buffer state_buffer;
  560. Size2i ssize = texture_storage->render_target_get_size(p_to_render_target);
  561. Transform3D screen_transform;
  562. screen_transform.translate_local(-(ssize.width / 2.0f), -(ssize.height / 2.0f), 0.0f);
  563. screen_transform.scale(Vector3(2.0f / ssize.width, 2.0f / ssize.height, 1.0f));
  564. _update_transform_to_mat4(screen_transform, state_buffer.screen_transform);
  565. _update_transform_2d_to_mat4(p_canvas_transform, state_buffer.canvas_transform);
  566. Transform2D normal_transform = p_canvas_transform;
  567. normal_transform.columns[0].normalize();
  568. normal_transform.columns[1].normalize();
  569. normal_transform.columns[2] = Vector2();
  570. _update_transform_2d_to_mat4(normal_transform, state_buffer.canvas_normal_transform);
  571. Color modulate = p_modulate;
  572. if (use_linear_colors) {
  573. modulate = p_modulate.srgb_to_linear();
  574. }
  575. state_buffer.canvas_modulate[0] = modulate.r;
  576. state_buffer.canvas_modulate[1] = modulate.g;
  577. state_buffer.canvas_modulate[2] = modulate.b;
  578. state_buffer.canvas_modulate[3] = modulate.a;
  579. Size2 render_target_size = texture_storage->render_target_get_size(p_to_render_target);
  580. state_buffer.screen_pixel_size[0] = 1.0 / render_target_size.x;
  581. state_buffer.screen_pixel_size[1] = 1.0 / render_target_size.y;
  582. state_buffer.time = state.time;
  583. state_buffer.use_pixel_snap = p_snap_2d_vertices_to_pixel;
  584. state_buffer.directional_light_count = directional_light_count;
  585. Vector2 canvas_scale = p_canvas_transform.get_scale();
  586. state_buffer.sdf_to_screen[0] = render_target_size.width / canvas_scale.x;
  587. state_buffer.sdf_to_screen[1] = render_target_size.height / canvas_scale.y;
  588. state_buffer.screen_to_sdf[0] = 1.0 / state_buffer.sdf_to_screen[0];
  589. state_buffer.screen_to_sdf[1] = 1.0 / state_buffer.sdf_to_screen[1];
  590. Rect2 sdf_rect = texture_storage->render_target_get_sdf_rect(p_to_render_target);
  591. Rect2 sdf_tex_rect(sdf_rect.position / canvas_scale, sdf_rect.size / canvas_scale);
  592. state_buffer.sdf_to_tex[0] = 1.0 / sdf_tex_rect.size.width;
  593. state_buffer.sdf_to_tex[1] = 1.0 / sdf_tex_rect.size.height;
  594. state_buffer.sdf_to_tex[2] = -sdf_tex_rect.position.x / sdf_tex_rect.size.width;
  595. state_buffer.sdf_to_tex[3] = -sdf_tex_rect.position.y / sdf_tex_rect.size.height;
  596. //print_line("w: " + itos(ssize.width) + " s: " + rtos(canvas_scale));
  597. state_buffer.tex_to_sdf = 1.0 / ((canvas_scale.x + canvas_scale.y) * 0.5);
  598. state_buffer.flags = use_linear_colors ? CANVAS_FLAGS_CONVERT_ATTRIBUTES_TO_LINEAR : 0;
  599. RD::get_singleton()->buffer_update(state.canvas_state_buffer, 0, sizeof(State::Buffer), &state_buffer);
  600. }
  601. { //default filter/repeat
  602. default_filter = p_default_filter;
  603. default_repeat = p_default_repeat;
  604. }
  605. Item *ci = p_item_list;
  606. //fill the list until rendering is possible.
  607. bool material_screen_texture_cached = false;
  608. bool material_screen_texture_mipmaps_cached = false;
  609. Rect2 back_buffer_rect;
  610. bool backbuffer_copy = false;
  611. bool backbuffer_gen_mipmaps = false;
  612. Item *canvas_group_owner = nullptr;
  613. bool skip_item = false;
  614. state.last_instance_index = 0;
  615. bool update_skeletons = false;
  616. bool time_used = false;
  617. bool backbuffer_cleared = false;
  618. RenderTarget to_render_target;
  619. to_render_target.render_target = p_to_render_target;
  620. to_render_target.use_linear_colors = use_linear_colors;
  621. while (ci) {
  622. if (ci->copy_back_buffer && canvas_group_owner == nullptr) {
  623. backbuffer_copy = true;
  624. if (ci->copy_back_buffer->full) {
  625. back_buffer_rect = Rect2();
  626. } else {
  627. back_buffer_rect = ci->copy_back_buffer->rect;
  628. }
  629. }
  630. RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;
  631. if (material.is_valid()) {
  632. CanvasMaterialData *md = static_cast<CanvasMaterialData *>(material_storage->material_get_data(material, RendererRD::MaterialStorage::SHADER_TYPE_2D));
  633. if (md && md->shader_data->is_valid()) {
  634. if (md->shader_data->uses_screen_texture && canvas_group_owner == nullptr) {
  635. if (!material_screen_texture_cached) {
  636. backbuffer_copy = true;
  637. back_buffer_rect = Rect2();
  638. backbuffer_gen_mipmaps = md->shader_data->uses_screen_texture_mipmaps;
  639. } else if (!material_screen_texture_mipmaps_cached) {
  640. backbuffer_gen_mipmaps = md->shader_data->uses_screen_texture_mipmaps;
  641. }
  642. }
  643. if (md->shader_data->uses_sdf) {
  644. r_sdf_used = true;
  645. }
  646. if (md->shader_data->uses_time) {
  647. time_used = true;
  648. }
  649. }
  650. }
  651. if (ci->skeleton.is_valid()) {
  652. const Item::Command *c = ci->commands;
  653. while (c) {
  654. if (c->type == Item::Command::TYPE_MESH) {
  655. const Item::CommandMesh *cm = static_cast<const Item::CommandMesh *>(c);
  656. if (cm->mesh_instance.is_valid()) {
  657. mesh_storage->mesh_instance_check_for_update(cm->mesh_instance);
  658. mesh_storage->mesh_instance_set_canvas_item_transform(cm->mesh_instance, canvas_transform_inverse * ci->final_transform);
  659. update_skeletons = true;
  660. }
  661. }
  662. c = c->next;
  663. }
  664. }
  665. if (ci->canvas_group_owner != nullptr) {
  666. if (canvas_group_owner == nullptr) {
  667. // Canvas group begins here, render until before this item
  668. if (update_skeletons) {
  669. mesh_storage->update_mesh_instances();
  670. update_skeletons = false;
  671. }
  672. _render_batch_items(to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, false, r_render_info);
  673. item_count = 0;
  674. if (ci->canvas_group_owner->canvas_group->mode != RS::CANVAS_GROUP_MODE_TRANSPARENT) {
  675. Rect2i group_rect = ci->canvas_group_owner->global_rect_cache;
  676. texture_storage->render_target_copy_to_back_buffer(p_to_render_target, group_rect, false);
  677. if (ci->canvas_group_owner->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
  678. ci->canvas_group_owner->use_canvas_group = false;
  679. items[item_count++] = ci->canvas_group_owner;
  680. }
  681. } else if (!backbuffer_cleared) {
  682. texture_storage->render_target_clear_back_buffer(p_to_render_target, Rect2i(), Color(0, 0, 0, 0));
  683. backbuffer_cleared = true;
  684. }
  685. backbuffer_copy = false;
  686. canvas_group_owner = ci->canvas_group_owner; //continue until owner found
  687. }
  688. ci->canvas_group_owner = nullptr; //must be cleared
  689. }
  690. if (canvas_group_owner == nullptr && ci->canvas_group != nullptr && ci->canvas_group->mode != RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
  691. skip_item = true;
  692. }
  693. if (ci == canvas_group_owner) {
  694. if (update_skeletons) {
  695. mesh_storage->update_mesh_instances();
  696. update_skeletons = false;
  697. }
  698. _render_batch_items(to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, true, r_render_info);
  699. item_count = 0;
  700. if (ci->canvas_group->blur_mipmaps) {
  701. texture_storage->render_target_gen_back_buffer_mipmaps(p_to_render_target, ci->global_rect_cache);
  702. }
  703. canvas_group_owner = nullptr;
  704. // Backbuffer is dirty now and needs to be re-cleared if another CanvasGroup needs it.
  705. backbuffer_cleared = false;
  706. // Tell the renderer to paint this as a canvas group
  707. ci->use_canvas_group = true;
  708. } else {
  709. ci->use_canvas_group = false;
  710. }
  711. if (backbuffer_copy) {
  712. //render anything pending, including clearing if no items
  713. if (update_skeletons) {
  714. mesh_storage->update_mesh_instances();
  715. update_skeletons = false;
  716. }
  717. _render_batch_items(to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, false, r_render_info);
  718. item_count = 0;
  719. texture_storage->render_target_copy_to_back_buffer(p_to_render_target, back_buffer_rect, backbuffer_gen_mipmaps);
  720. backbuffer_copy = false;
  721. material_screen_texture_cached = true; // After a backbuffer copy, screen texture makes no further copies.
  722. material_screen_texture_mipmaps_cached = backbuffer_gen_mipmaps;
  723. backbuffer_gen_mipmaps = false;
  724. }
  725. if (backbuffer_gen_mipmaps) {
  726. texture_storage->render_target_gen_back_buffer_mipmaps(p_to_render_target, back_buffer_rect);
  727. backbuffer_gen_mipmaps = false;
  728. material_screen_texture_mipmaps_cached = true;
  729. }
  730. if (skip_item) {
  731. skip_item = false;
  732. } else {
  733. items[item_count++] = ci;
  734. }
  735. if (!ci->next || item_count == MAX_RENDER_ITEMS - 1) {
  736. if (update_skeletons) {
  737. mesh_storage->update_mesh_instances();
  738. update_skeletons = false;
  739. }
  740. _render_batch_items(to_render_target, item_count, canvas_transform_inverse, p_light_list, r_sdf_used, canvas_group_owner != nullptr, r_render_info);
  741. //then reset
  742. item_count = 0;
  743. }
  744. ci = ci->next;
  745. }
  746. if (time_used) {
  747. RenderingServerDefault::redraw_request();
  748. }
  749. state.current_data_buffer_index = (state.current_data_buffer_index + 1) % BATCH_DATA_BUFFER_COUNT;
  750. state.current_instance_buffer_index = 0;
  751. }
  752. RID RendererCanvasRenderRD::light_create() {
  753. CanvasLight canvas_light;
  754. return canvas_light_owner.make_rid(canvas_light);
  755. }
  756. void RendererCanvasRenderRD::light_set_texture(RID p_rid, RID p_texture) {
  757. RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();
  758. CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
  759. ERR_FAIL_NULL(cl);
  760. if (cl->texture == p_texture) {
  761. return;
  762. }
  763. ERR_FAIL_COND(p_texture.is_valid() && !texture_storage->owns_texture(p_texture));
  764. if (cl->texture.is_valid()) {
  765. texture_storage->texture_remove_from_decal_atlas(cl->texture);
  766. }
  767. cl->texture = p_texture;
  768. if (cl->texture.is_valid()) {
  769. texture_storage->texture_add_to_decal_atlas(cl->texture);
  770. }
  771. }
  772. void RendererCanvasRenderRD::light_set_use_shadow(RID p_rid, bool p_enable) {
  773. CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
  774. ERR_FAIL_NULL(cl);
  775. cl->shadow.enabled = p_enable;
  776. }
  777. void RendererCanvasRenderRD::_update_shadow_atlas() {
  778. if (state.shadow_fb == RID()) {
  779. //ah, we lack the shadow texture..
  780. RD::get_singleton()->free(state.shadow_texture); //erase placeholder
  781. Vector<RID> fb_textures;
  782. { //texture
  783. RD::TextureFormat tf;
  784. tf.texture_type = RD::TEXTURE_TYPE_2D;
  785. tf.width = state.shadow_texture_size;
  786. tf.height = state.max_lights_per_render * 2;
  787. tf.usage_bits = RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT | RD::TEXTURE_USAGE_SAMPLING_BIT;
  788. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  789. state.shadow_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  790. fb_textures.push_back(state.shadow_texture);
  791. }
  792. {
  793. RD::TextureFormat tf;
  794. tf.texture_type = RD::TEXTURE_TYPE_2D;
  795. tf.width = state.shadow_texture_size;
  796. tf.height = state.max_lights_per_render * 2;
  797. tf.usage_bits = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  798. tf.format = RD::DATA_FORMAT_D32_SFLOAT;
  799. tf.is_discardable = true;
  800. //chunks to write
  801. state.shadow_depth_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  802. fb_textures.push_back(state.shadow_depth_texture);
  803. }
  804. state.shadow_fb = RD::get_singleton()->framebuffer_create(fb_textures);
  805. }
  806. }
  807. void RendererCanvasRenderRD::light_update_shadow(RID p_rid, int p_shadow_index, const Transform2D &p_light_xform, int p_light_mask, float p_near, float p_far, LightOccluderInstance *p_occluders) {
  808. CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
  809. ERR_FAIL_COND(!cl->shadow.enabled);
  810. _update_shadow_atlas();
  811. cl->shadow.z_far = p_far;
  812. cl->shadow.y_offset = float(p_shadow_index * 2 + 1) / float(state.max_lights_per_render * 2);
  813. Vector<Color> cc;
  814. cc.push_back(Color(p_far, p_far, p_far, 1.0));
  815. Projection projection;
  816. {
  817. real_t fov = 90;
  818. real_t nearp = p_near;
  819. real_t farp = p_far;
  820. real_t aspect = 1.0;
  821. real_t ymax = nearp * Math::tan(Math::deg_to_rad(fov * 0.5));
  822. real_t ymin = -ymax;
  823. real_t xmin = ymin * aspect;
  824. real_t xmax = ymax * aspect;
  825. projection.set_frustum(xmin, xmax, ymin, ymax, nearp, farp);
  826. }
  827. // Precomputed:
  828. // Vector3 cam_target = Basis::from_euler(Vector3(0, 0, Math_TAU * ((i + 3) / 4.0))).xform(Vector3(0, 1, 0));
  829. // projection = projection * Projection(Transform3D().looking_at(cam_targets[i], Vector3(0, 0, -1)).affine_inverse());
  830. const Projection projections[4] = {
  831. projection * Projection(Vector4(0, 0, -1, 0), Vector4(1, 0, 0, 0), Vector4(0, -1, 0, 0), Vector4(0, 0, 0, 1)),
  832. projection * Projection(Vector4(-1, 0, 0, 0), Vector4(0, 0, -1, 0), Vector4(0, -1, 0, 0), Vector4(0, 0, 0, 1)),
  833. projection * Projection(Vector4(0, 0, 1, 0), Vector4(-1, 0, 0, 0), Vector4(0, -1, 0, 0), Vector4(0, 0, 0, 1)),
  834. projection * Projection(Vector4(1, 0, 0, 0), Vector4(0, 0, 1, 0), Vector4(0, -1, 0, 0), Vector4(0, 0, 0, 1))
  835. };
  836. for (int i = 0; i < 4; i++) {
  837. Rect2i rect((state.shadow_texture_size / 4) * i, p_shadow_index * 2, (state.shadow_texture_size / 4), 2);
  838. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(state.shadow_fb, RD::DRAW_CLEAR_ALL, cc, 1.0f, 0, rect);
  839. ShadowRenderPushConstant push_constant;
  840. for (int y = 0; y < 4; y++) {
  841. for (int x = 0; x < 4; x++) {
  842. push_constant.projection[y * 4 + x] = projections[i].columns[y][x];
  843. }
  844. }
  845. static const Vector2 directions[4] = { Vector2(1, 0), Vector2(0, 1), Vector2(-1, 0), Vector2(0, -1) };
  846. push_constant.direction[0] = directions[i].x;
  847. push_constant.direction[1] = directions[i].y;
  848. push_constant.z_far = p_far;
  849. push_constant.pad = 0;
  850. LightOccluderInstance *instance = p_occluders;
  851. while (instance) {
  852. OccluderPolygon *co = occluder_polygon_owner.get_or_null(instance->occluder);
  853. if (!co || co->index_array.is_null() || !(p_light_mask & instance->light_mask)) {
  854. instance = instance->next;
  855. continue;
  856. }
  857. _update_transform_2d_to_mat2x4(p_light_xform * instance->xform_cache, push_constant.modelview);
  858. RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, shadow_render.render_pipelines[co->cull_mode]);
  859. RD::get_singleton()->draw_list_bind_vertex_array(draw_list, co->vertex_array);
  860. RD::get_singleton()->draw_list_bind_index_array(draw_list, co->index_array);
  861. RD::get_singleton()->draw_list_set_push_constant(draw_list, &push_constant, sizeof(ShadowRenderPushConstant));
  862. RD::get_singleton()->draw_list_draw(draw_list, true);
  863. instance = instance->next;
  864. }
  865. RD::get_singleton()->draw_list_end();
  866. }
  867. }
  868. void RendererCanvasRenderRD::light_update_directional_shadow(RID p_rid, int p_shadow_index, const Transform2D &p_light_xform, int p_light_mask, float p_cull_distance, const Rect2 &p_clip_rect, LightOccluderInstance *p_occluders) {
  869. CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
  870. ERR_FAIL_COND(!cl->shadow.enabled);
  871. _update_shadow_atlas();
  872. Vector2 light_dir = p_light_xform.columns[1].normalized();
  873. Vector2 center = p_clip_rect.get_center();
  874. float to_edge_distance = ABS(light_dir.dot(p_clip_rect.get_support(-light_dir)) - light_dir.dot(center));
  875. Vector2 from_pos = center - light_dir * (to_edge_distance + p_cull_distance);
  876. float distance = to_edge_distance * 2.0 + p_cull_distance;
  877. float half_size = p_clip_rect.size.length() * 0.5; //shadow length, must keep this no matter the angle
  878. cl->shadow.z_far = distance;
  879. cl->shadow.y_offset = float(p_shadow_index * 2 + 1) / float(state.max_lights_per_render * 2);
  880. Transform2D to_light_xform;
  881. to_light_xform[2] = from_pos;
  882. to_light_xform[1] = light_dir;
  883. to_light_xform[0] = -light_dir.orthogonal();
  884. to_light_xform.invert();
  885. Vector<Color> cc;
  886. cc.push_back(Color(1, 1, 1, 1));
  887. Rect2i rect(0, p_shadow_index * 2, state.shadow_texture_size, 2);
  888. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(state.shadow_fb, RD::DRAW_CLEAR_ALL, cc, 1.0f, 0, rect);
  889. Projection projection;
  890. projection.set_orthogonal(-half_size, half_size, -0.5, 0.5, 0.0, distance);
  891. projection = projection * Projection(Transform3D().looking_at(Vector3(0, 1, 0), Vector3(0, 0, -1)).affine_inverse());
  892. ShadowRenderPushConstant push_constant;
  893. for (int y = 0; y < 4; y++) {
  894. for (int x = 0; x < 4; x++) {
  895. push_constant.projection[y * 4 + x] = projection.columns[y][x];
  896. }
  897. }
  898. push_constant.direction[0] = 0.0;
  899. push_constant.direction[1] = 1.0;
  900. push_constant.z_far = distance;
  901. push_constant.pad = 0;
  902. LightOccluderInstance *instance = p_occluders;
  903. while (instance) {
  904. OccluderPolygon *co = occluder_polygon_owner.get_or_null(instance->occluder);
  905. if (!co || co->index_array.is_null() || !(p_light_mask & instance->light_mask)) {
  906. instance = instance->next;
  907. continue;
  908. }
  909. _update_transform_2d_to_mat2x4(to_light_xform * instance->xform_cache, push_constant.modelview);
  910. RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, shadow_render.render_pipelines[co->cull_mode]);
  911. RD::get_singleton()->draw_list_bind_vertex_array(draw_list, co->vertex_array);
  912. RD::get_singleton()->draw_list_bind_index_array(draw_list, co->index_array);
  913. RD::get_singleton()->draw_list_set_push_constant(draw_list, &push_constant, sizeof(ShadowRenderPushConstant));
  914. RD::get_singleton()->draw_list_draw(draw_list, true);
  915. instance = instance->next;
  916. }
  917. RD::get_singleton()->draw_list_end();
  918. Transform2D to_shadow;
  919. to_shadow.columns[0].x = 1.0 / -(half_size * 2.0);
  920. to_shadow.columns[2].x = 0.5;
  921. cl->shadow.directional_xform = to_shadow * to_light_xform;
  922. }
  923. void RendererCanvasRenderRD::render_sdf(RID p_render_target, LightOccluderInstance *p_occluders) {
  924. RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();
  925. RID fb = texture_storage->render_target_get_sdf_framebuffer(p_render_target);
  926. Rect2i rect = texture_storage->render_target_get_sdf_rect(p_render_target);
  927. Transform2D to_sdf;
  928. to_sdf.columns[0] *= rect.size.width;
  929. to_sdf.columns[1] *= rect.size.height;
  930. to_sdf.columns[2] = rect.position;
  931. Transform2D to_clip;
  932. to_clip.columns[0] *= 2.0;
  933. to_clip.columns[1] *= 2.0;
  934. to_clip.columns[2] = -Vector2(1.0, 1.0);
  935. to_clip = to_clip * to_sdf.affine_inverse();
  936. Vector<Color> cc;
  937. cc.push_back(Color(0, 0, 0, 0));
  938. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(fb, RD::DRAW_CLEAR_ALL, cc);
  939. Projection projection;
  940. ShadowRenderPushConstant push_constant;
  941. for (int y = 0; y < 4; y++) {
  942. for (int x = 0; x < 4; x++) {
  943. push_constant.projection[y * 4 + x] = projection.columns[y][x];
  944. }
  945. }
  946. push_constant.direction[0] = 0.0;
  947. push_constant.direction[1] = 0.0;
  948. push_constant.z_far = 0;
  949. push_constant.pad = 0;
  950. LightOccluderInstance *instance = p_occluders;
  951. while (instance) {
  952. OccluderPolygon *co = occluder_polygon_owner.get_or_null(instance->occluder);
  953. if (!co || co->sdf_index_array.is_null() || !instance->sdf_collision) {
  954. instance = instance->next;
  955. continue;
  956. }
  957. _update_transform_2d_to_mat2x4(to_clip * instance->xform_cache, push_constant.modelview);
  958. RD::get_singleton()->draw_list_bind_render_pipeline(draw_list, shadow_render.sdf_render_pipelines[co->sdf_is_lines ? SHADOW_RENDER_SDF_LINES : SHADOW_RENDER_SDF_TRIANGLES]);
  959. RD::get_singleton()->draw_list_bind_vertex_array(draw_list, co->sdf_vertex_array);
  960. RD::get_singleton()->draw_list_bind_index_array(draw_list, co->sdf_index_array);
  961. RD::get_singleton()->draw_list_set_push_constant(draw_list, &push_constant, sizeof(ShadowRenderPushConstant));
  962. RD::get_singleton()->draw_list_draw(draw_list, true);
  963. instance = instance->next;
  964. }
  965. RD::get_singleton()->draw_list_end();
  966. texture_storage->render_target_sdf_process(p_render_target); //done rendering, process it
  967. }
  968. RID RendererCanvasRenderRD::occluder_polygon_create() {
  969. OccluderPolygon occluder;
  970. occluder.line_point_count = 0;
  971. occluder.sdf_point_count = 0;
  972. occluder.sdf_index_count = 0;
  973. occluder.cull_mode = RS::CANVAS_OCCLUDER_POLYGON_CULL_DISABLED;
  974. return occluder_polygon_owner.make_rid(occluder);
  975. }
  976. void RendererCanvasRenderRD::occluder_polygon_set_shape(RID p_occluder, const Vector<Vector2> &p_points, bool p_closed) {
  977. OccluderPolygon *oc = occluder_polygon_owner.get_or_null(p_occluder);
  978. ERR_FAIL_NULL(oc);
  979. Vector<Vector2> lines;
  980. if (p_points.size()) {
  981. int lc = p_points.size() * 2;
  982. lines.resize(lc - (p_closed ? 0 : 2));
  983. {
  984. Vector2 *w = lines.ptrw();
  985. const Vector2 *r = p_points.ptr();
  986. int max = lc / 2;
  987. if (!p_closed) {
  988. max--;
  989. }
  990. for (int i = 0; i < max; i++) {
  991. Vector2 a = r[i];
  992. Vector2 b = r[(i + 1) % (lc / 2)];
  993. w[i * 2 + 0] = a;
  994. w[i * 2 + 1] = b;
  995. }
  996. }
  997. }
  998. if ((oc->line_point_count != lines.size() || lines.size() == 0) && oc->vertex_array.is_valid()) {
  999. RD::get_singleton()->free(oc->vertex_array);
  1000. RD::get_singleton()->free(oc->vertex_buffer);
  1001. RD::get_singleton()->free(oc->index_array);
  1002. RD::get_singleton()->free(oc->index_buffer);
  1003. oc->vertex_array = RID();
  1004. oc->vertex_buffer = RID();
  1005. oc->index_array = RID();
  1006. oc->index_buffer = RID();
  1007. oc->line_point_count = lines.size();
  1008. }
  1009. if (lines.size()) {
  1010. oc->line_point_count = lines.size();
  1011. Vector<uint8_t> geometry;
  1012. Vector<uint8_t> indices;
  1013. int lc = lines.size();
  1014. geometry.resize(lc * 6 * sizeof(float));
  1015. indices.resize(lc * 3 * sizeof(uint16_t));
  1016. {
  1017. uint8_t *vw = geometry.ptrw();
  1018. float *vwptr = reinterpret_cast<float *>(vw);
  1019. uint8_t *iw = indices.ptrw();
  1020. uint16_t *iwptr = (uint16_t *)iw;
  1021. const Vector2 *lr = lines.ptr();
  1022. const int POLY_HEIGHT = 16384;
  1023. for (int i = 0; i < lc / 2; i++) {
  1024. vwptr[i * 12 + 0] = lr[i * 2 + 0].x;
  1025. vwptr[i * 12 + 1] = lr[i * 2 + 0].y;
  1026. vwptr[i * 12 + 2] = POLY_HEIGHT;
  1027. vwptr[i * 12 + 3] = lr[i * 2 + 1].x;
  1028. vwptr[i * 12 + 4] = lr[i * 2 + 1].y;
  1029. vwptr[i * 12 + 5] = POLY_HEIGHT;
  1030. vwptr[i * 12 + 6] = lr[i * 2 + 1].x;
  1031. vwptr[i * 12 + 7] = lr[i * 2 + 1].y;
  1032. vwptr[i * 12 + 8] = -POLY_HEIGHT;
  1033. vwptr[i * 12 + 9] = lr[i * 2 + 0].x;
  1034. vwptr[i * 12 + 10] = lr[i * 2 + 0].y;
  1035. vwptr[i * 12 + 11] = -POLY_HEIGHT;
  1036. iwptr[i * 6 + 0] = i * 4 + 0;
  1037. iwptr[i * 6 + 1] = i * 4 + 1;
  1038. iwptr[i * 6 + 2] = i * 4 + 2;
  1039. iwptr[i * 6 + 3] = i * 4 + 2;
  1040. iwptr[i * 6 + 4] = i * 4 + 3;
  1041. iwptr[i * 6 + 5] = i * 4 + 0;
  1042. }
  1043. }
  1044. //if same buffer len is being set, just use buffer_update to avoid a pipeline flush
  1045. if (oc->vertex_array.is_null()) {
  1046. //create from scratch
  1047. //vertices
  1048. oc->vertex_buffer = RD::get_singleton()->vertex_buffer_create(lc * 6 * sizeof(float), geometry);
  1049. Vector<RID> buffer;
  1050. buffer.push_back(oc->vertex_buffer);
  1051. oc->vertex_array = RD::get_singleton()->vertex_array_create(4 * lc / 2, shadow_render.vertex_format, buffer);
  1052. //indices
  1053. oc->index_buffer = RD::get_singleton()->index_buffer_create(3 * lc, RD::INDEX_BUFFER_FORMAT_UINT16, indices);
  1054. oc->index_array = RD::get_singleton()->index_array_create(oc->index_buffer, 0, 3 * lc);
  1055. } else {
  1056. //update existing
  1057. const uint8_t *vr = geometry.ptr();
  1058. RD::get_singleton()->buffer_update(oc->vertex_buffer, 0, geometry.size(), vr);
  1059. const uint8_t *ir = indices.ptr();
  1060. RD::get_singleton()->buffer_update(oc->index_buffer, 0, indices.size(), ir);
  1061. }
  1062. }
  1063. // sdf
  1064. Vector<int> sdf_indices;
  1065. if (p_points.size()) {
  1066. if (p_closed) {
  1067. sdf_indices = Geometry2D::triangulate_polygon(p_points);
  1068. oc->sdf_is_lines = false;
  1069. } else {
  1070. int max = p_points.size();
  1071. sdf_indices.resize(max * 2);
  1072. int *iw = sdf_indices.ptrw();
  1073. for (int i = 0; i < max; i++) {
  1074. iw[i * 2 + 0] = i;
  1075. iw[i * 2 + 1] = (i + 1) % max;
  1076. }
  1077. oc->sdf_is_lines = true;
  1078. }
  1079. }
  1080. if (((oc->sdf_index_count != sdf_indices.size() && oc->sdf_point_count != p_points.size()) || p_points.size() == 0) && oc->sdf_vertex_array.is_valid()) {
  1081. RD::get_singleton()->free(oc->sdf_vertex_array);
  1082. RD::get_singleton()->free(oc->sdf_vertex_buffer);
  1083. RD::get_singleton()->free(oc->sdf_index_array);
  1084. RD::get_singleton()->free(oc->sdf_index_buffer);
  1085. oc->sdf_vertex_array = RID();
  1086. oc->sdf_vertex_buffer = RID();
  1087. oc->sdf_index_array = RID();
  1088. oc->sdf_index_buffer = RID();
  1089. oc->sdf_index_count = sdf_indices.size();
  1090. oc->sdf_point_count = p_points.size();
  1091. oc->sdf_is_lines = false;
  1092. }
  1093. if (sdf_indices.size()) {
  1094. if (oc->sdf_vertex_array.is_null()) {
  1095. //create from scratch
  1096. //vertices
  1097. #ifdef REAL_T_IS_DOUBLE
  1098. PackedFloat32Array float_points;
  1099. float_points.resize(p_points.size() * 2);
  1100. float *float_points_ptr = (float *)float_points.ptrw();
  1101. for (int i = 0; i < p_points.size(); i++) {
  1102. float_points_ptr[i * 2] = p_points[i].x;
  1103. float_points_ptr[i * 2 + 1] = p_points[i].y;
  1104. }
  1105. oc->sdf_vertex_buffer = RD::get_singleton()->vertex_buffer_create(p_points.size() * 2 * sizeof(float), float_points.to_byte_array());
  1106. #else
  1107. oc->sdf_vertex_buffer = RD::get_singleton()->vertex_buffer_create(p_points.size() * 2 * sizeof(float), p_points.to_byte_array());
  1108. #endif
  1109. oc->sdf_index_buffer = RD::get_singleton()->index_buffer_create(sdf_indices.size(), RD::INDEX_BUFFER_FORMAT_UINT32, sdf_indices.to_byte_array());
  1110. oc->sdf_index_array = RD::get_singleton()->index_array_create(oc->sdf_index_buffer, 0, sdf_indices.size());
  1111. Vector<RID> buffer;
  1112. buffer.push_back(oc->sdf_vertex_buffer);
  1113. oc->sdf_vertex_array = RD::get_singleton()->vertex_array_create(p_points.size(), shadow_render.sdf_vertex_format, buffer);
  1114. //indices
  1115. } else {
  1116. //update existing
  1117. #ifdef REAL_T_IS_DOUBLE
  1118. PackedFloat32Array float_points;
  1119. float_points.resize(p_points.size() * 2);
  1120. float *float_points_ptr = (float *)float_points.ptrw();
  1121. for (int i = 0; i < p_points.size(); i++) {
  1122. float_points_ptr[i * 2] = p_points[i].x;
  1123. float_points_ptr[i * 2 + 1] = p_points[i].y;
  1124. }
  1125. RD::get_singleton()->buffer_update(oc->sdf_vertex_buffer, 0, sizeof(float) * 2 * p_points.size(), float_points.ptr());
  1126. #else
  1127. RD::get_singleton()->buffer_update(oc->sdf_vertex_buffer, 0, sizeof(float) * 2 * p_points.size(), p_points.ptr());
  1128. #endif
  1129. RD::get_singleton()->buffer_update(oc->sdf_index_buffer, 0, sdf_indices.size() * sizeof(int32_t), sdf_indices.ptr());
  1130. }
  1131. }
  1132. }
  1133. void RendererCanvasRenderRD::occluder_polygon_set_cull_mode(RID p_occluder, RS::CanvasOccluderPolygonCullMode p_mode) {
  1134. OccluderPolygon *oc = occluder_polygon_owner.get_or_null(p_occluder);
  1135. ERR_FAIL_NULL(oc);
  1136. oc->cull_mode = p_mode;
  1137. }
  1138. void RendererCanvasRenderRD::CanvasShaderData::_clear_vertex_input_mask_cache() {
  1139. for (uint32_t i = 0; i < VERTEX_INPUT_MASKS_SIZE; i++) {
  1140. vertex_input_masks[i].store(0);
  1141. }
  1142. }
  1143. void RendererCanvasRenderRD::CanvasShaderData::_create_pipeline(PipelineKey p_pipeline_key) {
  1144. #if PRINT_PIPELINE_COMPILATION_KEYS
  1145. print_line(
  1146. "HASH:", p_pipeline_key.hash(),
  1147. "VERSION:", version,
  1148. "VARIANT:", p_pipeline_key.variant,
  1149. "FRAMEBUFFER:", p_pipeline_key.framebuffer_format_id,
  1150. "VERTEX:", p_pipeline_key.vertex_format_id,
  1151. "PRIMITIVE:", p_pipeline_key.render_primitive,
  1152. "SPEC PACKED #0:", p_pipeline_key.shader_specialization.packed_0,
  1153. "LCD:", p_pipeline_key.lcd_blend);
  1154. #endif
  1155. RendererRD::MaterialStorage::ShaderData::BlendMode blend_mode_rd = RendererRD::MaterialStorage::ShaderData::BlendMode(blend_mode);
  1156. RD::PipelineColorBlendState blend_state;
  1157. RD::PipelineColorBlendState::Attachment attachment;
  1158. uint32_t dynamic_state_flags = 0;
  1159. if (p_pipeline_key.lcd_blend) {
  1160. attachment.enable_blend = true;
  1161. attachment.alpha_blend_op = RD::BLEND_OP_ADD;
  1162. attachment.color_blend_op = RD::BLEND_OP_ADD;
  1163. attachment.src_color_blend_factor = RD::BLEND_FACTOR_CONSTANT_COLOR;
  1164. attachment.dst_color_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_COLOR;
  1165. attachment.src_alpha_blend_factor = RD::BLEND_FACTOR_ONE;
  1166. attachment.dst_alpha_blend_factor = RD::BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
  1167. dynamic_state_flags = RD::DYNAMIC_STATE_BLEND_CONSTANTS;
  1168. } else {
  1169. attachment = RendererRD::MaterialStorage::ShaderData::blend_mode_to_blend_attachment(blend_mode_rd);
  1170. }
  1171. blend_state.attachments.push_back(attachment);
  1172. RD::PipelineMultisampleState multisample_state;
  1173. multisample_state.sample_count = RD::get_singleton()->framebuffer_format_get_texture_samples(p_pipeline_key.framebuffer_format_id, 0);
  1174. // Convert the specialization from the key to pipeline specialization constants.
  1175. Vector<RD::PipelineSpecializationConstant> specialization_constants;
  1176. RD::PipelineSpecializationConstant sc;
  1177. sc.constant_id = 0;
  1178. sc.int_value = p_pipeline_key.shader_specialization.packed_0;
  1179. sc.type = RD::PIPELINE_SPECIALIZATION_CONSTANT_TYPE_INT;
  1180. specialization_constants.push_back(sc);
  1181. RID shader_rid = get_shader(p_pipeline_key.variant, p_pipeline_key.ubershader);
  1182. ERR_FAIL_COND(shader_rid.is_null());
  1183. RID pipeline = RD::get_singleton()->render_pipeline_create(shader_rid, p_pipeline_key.framebuffer_format_id, p_pipeline_key.vertex_format_id, p_pipeline_key.render_primitive, RD::PipelineRasterizationState(), multisample_state, RD::PipelineDepthStencilState(), blend_state, dynamic_state_flags, 0, specialization_constants);
  1184. ERR_FAIL_COND(pipeline.is_null());
  1185. pipeline_hash_map.add_compiled_pipeline(p_pipeline_key.hash(), pipeline);
  1186. }
  1187. void RendererCanvasRenderRD::CanvasShaderData::set_code(const String &p_code) {
  1188. //compile
  1189. code = p_code;
  1190. ubo_size = 0;
  1191. uniforms.clear();
  1192. uses_screen_texture = false;
  1193. uses_screen_texture_mipmaps = false;
  1194. uses_sdf = false;
  1195. uses_time = false;
  1196. _clear_vertex_input_mask_cache();
  1197. if (code.is_empty()) {
  1198. return; //just invalid, but no error
  1199. }
  1200. ShaderCompiler::GeneratedCode gen_code;
  1201. blend_mode = BLEND_MODE_MIX;
  1202. ShaderCompiler::IdentifierActions actions;
  1203. actions.entry_point_stages["vertex"] = ShaderCompiler::STAGE_VERTEX;
  1204. actions.entry_point_stages["fragment"] = ShaderCompiler::STAGE_FRAGMENT;
  1205. actions.entry_point_stages["light"] = ShaderCompiler::STAGE_FRAGMENT;
  1206. actions.render_mode_values["blend_add"] = Pair<int *, int>(&blend_mode, BLEND_MODE_ADD);
  1207. actions.render_mode_values["blend_mix"] = Pair<int *, int>(&blend_mode, BLEND_MODE_MIX);
  1208. actions.render_mode_values["blend_sub"] = Pair<int *, int>(&blend_mode, BLEND_MODE_SUB);
  1209. actions.render_mode_values["blend_mul"] = Pair<int *, int>(&blend_mode, BLEND_MODE_MUL);
  1210. actions.render_mode_values["blend_premul_alpha"] = Pair<int *, int>(&blend_mode, BLEND_MODE_PREMULTIPLIED_ALPHA);
  1211. actions.render_mode_values["blend_disabled"] = Pair<int *, int>(&blend_mode, BLEND_MODE_DISABLED);
  1212. actions.usage_flag_pointers["texture_sdf"] = &uses_sdf;
  1213. actions.usage_flag_pointers["TIME"] = &uses_time;
  1214. actions.uniforms = &uniforms;
  1215. RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);
  1216. MutexLock lock(canvas_singleton->shader.mutex);
  1217. Error err = canvas_singleton->shader.compiler.compile(RS::SHADER_CANVAS_ITEM, code, &actions, path, gen_code);
  1218. if (err != OK) {
  1219. if (version.is_valid()) {
  1220. canvas_singleton->shader.canvas_shader.version_free(version);
  1221. version = RID();
  1222. }
  1223. ERR_FAIL_MSG("Shader compilation failed.");
  1224. }
  1225. uses_screen_texture_mipmaps = gen_code.uses_screen_texture_mipmaps;
  1226. uses_screen_texture = gen_code.uses_screen_texture;
  1227. pipeline_hash_map.clear_pipelines();
  1228. if (version.is_null()) {
  1229. version = canvas_singleton->shader.canvas_shader.version_create();
  1230. }
  1231. #if 0
  1232. print_line("**compiling shader:");
  1233. print_line("**defines:\n");
  1234. for (int i = 0; i < gen_code.defines.size(); i++) {
  1235. print_line(gen_code.defines[i]);
  1236. }
  1237. HashMap<String, String>::Iterator el = gen_code.code.begin();
  1238. while (el) {
  1239. print_line("\n**code " + el->key + ":\n" + el->value);
  1240. ++el;
  1241. }
  1242. print_line("\n**uniforms:\n" + gen_code.uniforms);
  1243. print_line("\n**vertex_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX]);
  1244. print_line("\n**fragment_globals:\n" + gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT]);
  1245. #endif
  1246. canvas_singleton->shader.canvas_shader.version_set_code(version, gen_code.code, gen_code.uniforms, gen_code.stage_globals[ShaderCompiler::STAGE_VERTEX], gen_code.stage_globals[ShaderCompiler::STAGE_FRAGMENT], gen_code.defines);
  1247. ubo_size = gen_code.uniform_total_size;
  1248. ubo_offsets = gen_code.uniform_offsets;
  1249. texture_uniforms = gen_code.texture_uniforms;
  1250. }
  1251. bool RendererCanvasRenderRD::CanvasShaderData::is_animated() const {
  1252. return false;
  1253. }
  1254. bool RendererCanvasRenderRD::CanvasShaderData::casts_shadows() const {
  1255. return false;
  1256. }
  1257. RS::ShaderNativeSourceCode RendererCanvasRenderRD::CanvasShaderData::get_native_source_code() const {
  1258. RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);
  1259. MutexLock lock(canvas_singleton->shader.mutex);
  1260. return canvas_singleton->shader.canvas_shader.version_get_native_source_code(version);
  1261. }
  1262. RID RendererCanvasRenderRD::CanvasShaderData::get_shader(ShaderVariant p_shader_variant, bool p_ubershader) const {
  1263. if (version.is_valid()) {
  1264. uint32_t variant_index = p_shader_variant + (p_ubershader ? SHADER_VARIANT_MAX : 0);
  1265. RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);
  1266. MutexLock lock(canvas_singleton->shader.mutex);
  1267. return canvas_singleton->shader.canvas_shader.version_get_shader(version, variant_index);
  1268. } else {
  1269. return RID();
  1270. }
  1271. }
  1272. uint64_t RendererCanvasRenderRD::CanvasShaderData::get_vertex_input_mask(ShaderVariant p_shader_variant, bool p_ubershader) {
  1273. // Vertex input masks require knowledge of the shader. Since querying the shader can be expensive due to high contention and the necessary mutex, we cache the result instead.
  1274. uint32_t input_mask_index = p_shader_variant + (p_ubershader ? SHADER_VARIANT_MAX : 0);
  1275. uint64_t input_mask = vertex_input_masks[input_mask_index].load(std::memory_order_relaxed);
  1276. if (input_mask == 0) {
  1277. RID shader_rid = get_shader(p_shader_variant, p_ubershader);
  1278. ERR_FAIL_COND_V(shader_rid.is_null(), 0);
  1279. input_mask = RD::get_singleton()->shader_get_vertex_input_attribute_mask(shader_rid);
  1280. vertex_input_masks[input_mask_index].store(input_mask, std::memory_order_relaxed);
  1281. }
  1282. return input_mask;
  1283. }
  1284. bool RendererCanvasRenderRD::CanvasShaderData::is_valid() const {
  1285. if (version.is_valid()) {
  1286. RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);
  1287. MutexLock lock(canvas_singleton->shader.mutex);
  1288. return canvas_singleton->shader.canvas_shader.version_is_valid(version);
  1289. } else {
  1290. return false;
  1291. }
  1292. }
  1293. RendererCanvasRenderRD::CanvasShaderData::CanvasShaderData() {
  1294. RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);
  1295. pipeline_hash_map.set_creation_object_and_function(this, &CanvasShaderData::_create_pipeline);
  1296. pipeline_hash_map.set_compilations(&canvas_singleton->shader.pipeline_compilations[0], &canvas_singleton->shader.mutex);
  1297. }
  1298. RendererCanvasRenderRD::CanvasShaderData::~CanvasShaderData() {
  1299. pipeline_hash_map.clear_pipelines();
  1300. if (version.is_valid()) {
  1301. RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);
  1302. MutexLock lock(canvas_singleton->shader.mutex);
  1303. canvas_singleton->shader.canvas_shader.version_free(version);
  1304. }
  1305. }
  1306. RendererRD::MaterialStorage::ShaderData *RendererCanvasRenderRD::_create_shader_func() {
  1307. CanvasShaderData *shader_data = memnew(CanvasShaderData);
  1308. return shader_data;
  1309. }
  1310. bool RendererCanvasRenderRD::CanvasMaterialData::update_parameters(const HashMap<StringName, Variant> &p_parameters, bool p_uniform_dirty, bool p_textures_dirty) {
  1311. RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);
  1312. MutexLock lock(canvas_singleton->shader.mutex);
  1313. RID shader_to_update = canvas_singleton->shader.canvas_shader.version_get_shader(shader_data->version, 0);
  1314. bool uniform_set_changed = update_parameters_uniform_set(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size, uniform_set, shader_to_update, MATERIAL_UNIFORM_SET, true, false);
  1315. bool uniform_set_srgb_changed = update_parameters_uniform_set(p_parameters, p_uniform_dirty, p_textures_dirty, shader_data->uniforms, shader_data->ubo_offsets.ptr(), shader_data->texture_uniforms, shader_data->default_texture_params, shader_data->ubo_size, uniform_set_srgb, shader_to_update, MATERIAL_UNIFORM_SET, false, false);
  1316. return uniform_set_changed || uniform_set_srgb_changed;
  1317. }
  1318. RendererCanvasRenderRD::CanvasMaterialData::~CanvasMaterialData() {
  1319. free_parameters_uniform_set(uniform_set);
  1320. free_parameters_uniform_set(uniform_set_srgb);
  1321. }
  1322. RendererRD::MaterialStorage::MaterialData *RendererCanvasRenderRD::_create_material_func(CanvasShaderData *p_shader) {
  1323. CanvasMaterialData *material_data = memnew(CanvasMaterialData);
  1324. material_data->shader_data = p_shader;
  1325. //update will happen later anyway so do nothing.
  1326. return material_data;
  1327. }
  1328. void RendererCanvasRenderRD::set_time(double p_time) {
  1329. state.time = p_time;
  1330. }
  1331. void RendererCanvasRenderRD::update() {
  1332. }
  1333. RendererCanvasRenderRD::RendererCanvasRenderRD() {
  1334. RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();
  1335. RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
  1336. { //create default samplers
  1337. default_samplers.default_filter = RS::CANVAS_ITEM_TEXTURE_FILTER_LINEAR;
  1338. default_samplers.default_repeat = RS::CANVAS_ITEM_TEXTURE_REPEAT_DISABLED;
  1339. }
  1340. // preallocate 5 slots for uniform set 3
  1341. state.batch_texture_uniforms.resize(5);
  1342. { //shader variants
  1343. String global_defines;
  1344. uint64_t uniform_max_size = RD::get_singleton()->limit_get(RD::LIMIT_MAX_UNIFORM_BUFFER_SIZE);
  1345. if (uniform_max_size < 65536) {
  1346. //Yes, you guessed right, ARM again
  1347. state.max_lights_per_render = 64;
  1348. global_defines += "#define MAX_LIGHTS 64\n";
  1349. } else {
  1350. state.max_lights_per_render = DEFAULT_MAX_LIGHTS_PER_RENDER;
  1351. global_defines += "#define MAX_LIGHTS " + itos(DEFAULT_MAX_LIGHTS_PER_RENDER) + "\n";
  1352. }
  1353. global_defines += "\n#define SAMPLERS_BINDING_FIRST_INDEX " + itos(SAMPLERS_BINDING_FIRST_INDEX) + "\n";
  1354. state.light_uniforms = memnew_arr(LightUniform, state.max_lights_per_render);
  1355. Vector<String> variants;
  1356. const uint32_t ubershader_iterations = 1;
  1357. for (uint32_t ubershader = 0; ubershader < ubershader_iterations; ubershader++) {
  1358. const String base_define = ubershader ? "\n#define UBERSHADER\n" : "";
  1359. variants.push_back(base_define + ""); // SHADER_VARIANT_QUAD
  1360. variants.push_back(base_define + "#define USE_NINEPATCH\n"); // SHADER_VARIANT_NINEPATCH
  1361. variants.push_back(base_define + "#define USE_PRIMITIVE\n"); // SHADER_VARIANT_PRIMITIVE
  1362. variants.push_back(base_define + "#define USE_PRIMITIVE\n#define USE_POINT_SIZE\n"); // SHADER_VARIANT_PRIMITIVE_POINTS
  1363. variants.push_back(base_define + "#define USE_ATTRIBUTES\n"); // SHADER_VARIANT_ATTRIBUTES
  1364. variants.push_back(base_define + "#define USE_ATTRIBUTES\n#define USE_POINT_SIZE\n"); // SHADER_VARIANT_ATTRIBUTES_POINTS
  1365. }
  1366. shader.canvas_shader.initialize(variants, global_defines);
  1367. shader.default_version_data = memnew(CanvasShaderData);
  1368. shader.default_version_data->version = shader.canvas_shader.version_create();
  1369. shader.default_version_data->blend_mode = RendererRD::MaterialStorage::ShaderData::BLEND_MODE_MIX;
  1370. shader.default_version_rd_shader = shader.default_version_data->get_shader(SHADER_VARIANT_QUAD, false);
  1371. }
  1372. {
  1373. //shader compiler
  1374. ShaderCompiler::DefaultIdentifierActions actions;
  1375. actions.renames["VERTEX"] = "vertex";
  1376. actions.renames["LIGHT_VERTEX"] = "light_vertex";
  1377. actions.renames["SHADOW_VERTEX"] = "shadow_vertex";
  1378. actions.renames["UV"] = "uv";
  1379. actions.renames["POINT_SIZE"] = "point_size";
  1380. actions.renames["MODEL_MATRIX"] = "model_matrix";
  1381. actions.renames["CANVAS_MATRIX"] = "canvas_data.canvas_transform";
  1382. actions.renames["SCREEN_MATRIX"] = "canvas_data.screen_transform";
  1383. actions.renames["TIME"] = "canvas_data.time";
  1384. actions.renames["PI"] = _MKSTR(Math_PI);
  1385. actions.renames["TAU"] = _MKSTR(Math_TAU);
  1386. actions.renames["E"] = _MKSTR(Math_E);
  1387. actions.renames["AT_LIGHT_PASS"] = "false";
  1388. actions.renames["INSTANCE_CUSTOM"] = "instance_custom";
  1389. actions.renames["COLOR"] = "color";
  1390. actions.renames["NORMAL"] = "normal";
  1391. actions.renames["NORMAL_MAP"] = "normal_map";
  1392. actions.renames["NORMAL_MAP_DEPTH"] = "normal_map_depth";
  1393. actions.renames["TEXTURE"] = "color_texture";
  1394. actions.renames["TEXTURE_PIXEL_SIZE"] = "draw_data.color_texture_pixel_size";
  1395. actions.renames["NORMAL_TEXTURE"] = "normal_texture";
  1396. actions.renames["SPECULAR_SHININESS_TEXTURE"] = "specular_texture";
  1397. actions.renames["SPECULAR_SHININESS"] = "specular_shininess";
  1398. actions.renames["SCREEN_UV"] = "screen_uv";
  1399. actions.renames["SCREEN_PIXEL_SIZE"] = "canvas_data.screen_pixel_size";
  1400. actions.renames["FRAGCOORD"] = "gl_FragCoord";
  1401. actions.renames["POINT_COORD"] = "gl_PointCoord";
  1402. actions.renames["INSTANCE_ID"] = "gl_InstanceIndex";
  1403. actions.renames["VERTEX_ID"] = "gl_VertexIndex";
  1404. actions.renames["CUSTOM0"] = "custom0";
  1405. actions.renames["CUSTOM1"] = "custom1";
  1406. actions.renames["LIGHT_POSITION"] = "light_position";
  1407. actions.renames["LIGHT_DIRECTION"] = "light_direction";
  1408. actions.renames["LIGHT_IS_DIRECTIONAL"] = "is_directional";
  1409. actions.renames["LIGHT_COLOR"] = "light_color";
  1410. actions.renames["LIGHT_ENERGY"] = "light_energy";
  1411. actions.renames["LIGHT"] = "light";
  1412. actions.renames["SHADOW_MODULATE"] = "shadow_modulate";
  1413. actions.renames["texture_sdf"] = "texture_sdf";
  1414. actions.renames["texture_sdf_normal"] = "texture_sdf_normal";
  1415. actions.renames["sdf_to_screen_uv"] = "sdf_to_screen_uv";
  1416. actions.renames["screen_uv_to_sdf"] = "screen_uv_to_sdf";
  1417. actions.usage_defines["COLOR"] = "#define COLOR_USED\n";
  1418. actions.usage_defines["SCREEN_UV"] = "#define SCREEN_UV_USED\n";
  1419. actions.usage_defines["SCREEN_PIXEL_SIZE"] = "@SCREEN_UV";
  1420. actions.usage_defines["NORMAL"] = "#define NORMAL_USED\n";
  1421. actions.usage_defines["NORMAL_MAP"] = "#define NORMAL_MAP_USED\n";
  1422. actions.usage_defines["SPECULAR_SHININESS"] = "#define SPECULAR_SHININESS_USED\n";
  1423. actions.usage_defines["POINT_SIZE"] = "#define USE_POINT_SIZE\n";
  1424. actions.usage_defines["CUSTOM0"] = "#define CUSTOM0_USED\n";
  1425. actions.usage_defines["CUSTOM1"] = "#define CUSTOM1_USED\n";
  1426. actions.render_mode_defines["skip_vertex_transform"] = "#define SKIP_TRANSFORM_USED\n";
  1427. actions.render_mode_defines["unshaded"] = "#define MODE_UNSHADED\n";
  1428. actions.render_mode_defines["light_only"] = "#define MODE_LIGHT_ONLY\n";
  1429. actions.render_mode_defines["world_vertex_coords"] = "#define USE_WORLD_VERTEX_COORDS\n";
  1430. actions.custom_samplers["TEXTURE"] = "texture_sampler";
  1431. actions.custom_samplers["NORMAL_TEXTURE"] = "texture_sampler";
  1432. actions.custom_samplers["SPECULAR_SHININESS_TEXTURE"] = "texture_sampler";
  1433. actions.base_texture_binding_index = 1;
  1434. actions.texture_layout_set = MATERIAL_UNIFORM_SET;
  1435. actions.base_uniform_string = "material.";
  1436. actions.default_filter = ShaderLanguage::FILTER_LINEAR;
  1437. actions.default_repeat = ShaderLanguage::REPEAT_DISABLE;
  1438. actions.base_varying_index = 5;
  1439. actions.global_buffer_array_variable = "global_shader_uniforms.data";
  1440. shader.compiler.initialize(actions);
  1441. }
  1442. { //shadow rendering
  1443. Vector<String> versions;
  1444. versions.push_back("\n#define MODE_SHADOW\n"); //shadow
  1445. versions.push_back("\n#define MODE_SDF\n"); //sdf
  1446. shadow_render.shader.initialize(versions);
  1447. {
  1448. Vector<RD::AttachmentFormat> attachments;
  1449. RD::AttachmentFormat af_color;
  1450. af_color.format = RD::DATA_FORMAT_R32_SFLOAT;
  1451. af_color.usage_flags = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  1452. attachments.push_back(af_color);
  1453. RD::AttachmentFormat af_depth;
  1454. af_depth.format = RD::DATA_FORMAT_D32_SFLOAT;
  1455. af_depth.usage_flags = RD::TEXTURE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  1456. attachments.push_back(af_depth);
  1457. shadow_render.framebuffer_format = RD::get_singleton()->framebuffer_format_create(attachments);
  1458. }
  1459. {
  1460. Vector<RD::AttachmentFormat> attachments;
  1461. RD::AttachmentFormat af_color;
  1462. af_color.format = RD::DATA_FORMAT_R8_UNORM;
  1463. af_color.usage_flags = RD::TEXTURE_USAGE_SAMPLING_BIT | RD::TEXTURE_USAGE_STORAGE_BIT | RD::TEXTURE_USAGE_COLOR_ATTACHMENT_BIT;
  1464. attachments.push_back(af_color);
  1465. shadow_render.sdf_framebuffer_format = RD::get_singleton()->framebuffer_format_create(attachments);
  1466. }
  1467. //pipelines
  1468. Vector<RD::VertexAttribute> vf;
  1469. RD::VertexAttribute vd;
  1470. vd.format = RD::DATA_FORMAT_R32G32B32_SFLOAT;
  1471. vd.stride = sizeof(float) * 3;
  1472. vd.location = 0;
  1473. vd.offset = 0;
  1474. vf.push_back(vd);
  1475. shadow_render.vertex_format = RD::get_singleton()->vertex_format_create(vf);
  1476. vd.format = RD::DATA_FORMAT_R32G32_SFLOAT;
  1477. vd.stride = sizeof(float) * 2;
  1478. vf.write[0] = vd;
  1479. shadow_render.sdf_vertex_format = RD::get_singleton()->vertex_format_create(vf);
  1480. shadow_render.shader_version = shadow_render.shader.version_create();
  1481. for (int i = 0; i < 3; i++) {
  1482. RD::PipelineRasterizationState rs;
  1483. rs.cull_mode = i == 0 ? RD::POLYGON_CULL_DISABLED : (i == 1 ? RD::POLYGON_CULL_FRONT : RD::POLYGON_CULL_BACK);
  1484. RD::PipelineDepthStencilState ds;
  1485. ds.enable_depth_write = true;
  1486. ds.enable_depth_test = true;
  1487. ds.depth_compare_operator = RD::COMPARE_OP_LESS;
  1488. shadow_render.render_pipelines[i] = RD::get_singleton()->render_pipeline_create(shadow_render.shader.version_get_shader(shadow_render.shader_version, SHADOW_RENDER_MODE_SHADOW), shadow_render.framebuffer_format, shadow_render.vertex_format, RD::RENDER_PRIMITIVE_TRIANGLES, rs, RD::PipelineMultisampleState(), ds, RD::PipelineColorBlendState::create_disabled(), 0);
  1489. }
  1490. for (int i = 0; i < 2; i++) {
  1491. shadow_render.sdf_render_pipelines[i] = RD::get_singleton()->render_pipeline_create(shadow_render.shader.version_get_shader(shadow_render.shader_version, SHADOW_RENDER_MODE_SDF), shadow_render.sdf_framebuffer_format, shadow_render.sdf_vertex_format, i == 0 ? RD::RENDER_PRIMITIVE_TRIANGLES : RD::RENDER_PRIMITIVE_LINES, RD::PipelineRasterizationState(), RD::PipelineMultisampleState(), RD::PipelineDepthStencilState(), RD::PipelineColorBlendState::create_disabled(), 0);
  1492. }
  1493. // Unload shader modules to save memory.
  1494. RD::get_singleton()->shader_destroy_modules(shadow_render.shader.version_get_shader(shadow_render.shader_version, SHADOW_RENDER_MODE_SHADOW));
  1495. RD::get_singleton()->shader_destroy_modules(shadow_render.shader.version_get_shader(shadow_render.shader_version, SHADOW_RENDER_MODE_SDF));
  1496. }
  1497. { //bindings
  1498. state.canvas_state_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(State::Buffer));
  1499. state.lights_uniform_buffer = RD::get_singleton()->uniform_buffer_create(sizeof(LightUniform) * state.max_lights_per_render);
  1500. RD::SamplerState shadow_sampler_state;
  1501. shadow_sampler_state.mag_filter = RD::SAMPLER_FILTER_LINEAR;
  1502. shadow_sampler_state.min_filter = RD::SAMPLER_FILTER_LINEAR;
  1503. shadow_sampler_state.repeat_u = RD::SAMPLER_REPEAT_MODE_REPEAT; //shadow wrap around
  1504. shadow_sampler_state.compare_op = RD::COMPARE_OP_GREATER;
  1505. shadow_sampler_state.enable_compare = true;
  1506. state.shadow_sampler = RD::get_singleton()->sampler_create(shadow_sampler_state);
  1507. }
  1508. {
  1509. //polygon buffers
  1510. polygon_buffers.last_id = 1;
  1511. }
  1512. { // default index buffer
  1513. Vector<uint8_t> pv;
  1514. pv.resize(6 * 2);
  1515. {
  1516. uint8_t *w = pv.ptrw();
  1517. uint16_t *p16 = (uint16_t *)w;
  1518. p16[0] = 0;
  1519. p16[1] = 1;
  1520. p16[2] = 2;
  1521. p16[3] = 0;
  1522. p16[4] = 2;
  1523. p16[5] = 3;
  1524. }
  1525. shader.quad_index_buffer = RD::get_singleton()->index_buffer_create(6, RenderingDevice::INDEX_BUFFER_FORMAT_UINT16, pv);
  1526. shader.quad_index_array = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 6);
  1527. }
  1528. { //primitive
  1529. primitive_arrays.index_array[0] = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 1);
  1530. primitive_arrays.index_array[1] = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 2);
  1531. primitive_arrays.index_array[2] = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 3);
  1532. primitive_arrays.index_array[3] = RD::get_singleton()->index_array_create(shader.quad_index_buffer, 0, 6);
  1533. }
  1534. {
  1535. //default shadow texture to keep uniform set happy
  1536. RD::TextureFormat tf;
  1537. tf.texture_type = RD::TEXTURE_TYPE_2D;
  1538. tf.width = 4;
  1539. tf.height = 4;
  1540. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT;
  1541. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  1542. state.shadow_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1543. }
  1544. {
  1545. Vector<RD::Uniform> uniforms;
  1546. {
  1547. RD::Uniform u;
  1548. u.uniform_type = RD::UNIFORM_TYPE_STORAGE_BUFFER;
  1549. u.binding = 0;
  1550. u.append_id(RendererRD::MeshStorage::get_singleton()->get_default_rd_storage_buffer());
  1551. uniforms.push_back(u);
  1552. }
  1553. state.default_transforms_uniform_set = RD::get_singleton()->uniform_set_create(uniforms, shader.default_version_rd_shader, TRANSFORMS_UNIFORM_SET);
  1554. }
  1555. default_canvas_texture = texture_storage->canvas_texture_allocate();
  1556. texture_storage->canvas_texture_initialize(default_canvas_texture);
  1557. RendererRD::TextureStorage::CanvasTextureInfo info = RendererRD::TextureStorage::get_singleton()->canvas_texture_get_info(default_canvas_texture, default_filter, default_repeat, false, false);
  1558. default_texture_info.diffuse = info.diffuse;
  1559. default_texture_info.normal = info.normal;
  1560. default_texture_info.specular = info.specular;
  1561. default_texture_info.sampler = info.sampler;
  1562. state.shadow_texture_size = GLOBAL_GET("rendering/2d/shadow_atlas/size");
  1563. //create functions for shader and material
  1564. material_storage->shader_set_data_request_function(RendererRD::MaterialStorage::SHADER_TYPE_2D, _create_shader_funcs);
  1565. material_storage->material_set_data_request_function(RendererRD::MaterialStorage::SHADER_TYPE_2D, _create_material_funcs);
  1566. state.time = 0;
  1567. {
  1568. default_canvas_group_shader = material_storage->shader_allocate();
  1569. material_storage->shader_initialize(default_canvas_group_shader);
  1570. material_storage->shader_set_code(default_canvas_group_shader, R"(
  1571. // Default CanvasGroup shader.
  1572. shader_type canvas_item;
  1573. render_mode unshaded;
  1574. uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_nearest;
  1575. void fragment() {
  1576. vec4 c = textureLod(screen_texture, SCREEN_UV, 0.0);
  1577. if (c.a > 0.0001) {
  1578. c.rgb /= c.a;
  1579. }
  1580. COLOR *= c;
  1581. }
  1582. )");
  1583. default_canvas_group_material = material_storage->material_allocate();
  1584. material_storage->material_initialize(default_canvas_group_material);
  1585. material_storage->material_set_shader(default_canvas_group_material, default_canvas_group_shader);
  1586. }
  1587. {
  1588. default_clip_children_shader = material_storage->shader_allocate();
  1589. material_storage->shader_initialize(default_clip_children_shader);
  1590. material_storage->shader_set_code(default_clip_children_shader, R"(
  1591. // Default clip children shader.
  1592. shader_type canvas_item;
  1593. render_mode unshaded;
  1594. uniform sampler2D screen_texture : hint_screen_texture, repeat_disable, filter_nearest;
  1595. void fragment() {
  1596. vec4 c = textureLod(screen_texture, SCREEN_UV, 0.0);
  1597. COLOR.rgb = c.rgb;
  1598. }
  1599. )");
  1600. default_clip_children_material = material_storage->material_allocate();
  1601. material_storage->material_initialize(default_clip_children_material);
  1602. material_storage->material_set_shader(default_clip_children_material, default_clip_children_shader);
  1603. }
  1604. {
  1605. uint32_t cache_size = uint32_t(GLOBAL_GET("rendering/2d/batching/uniform_set_cache_size"));
  1606. rid_set_to_uniform_set.set_capacity(cache_size);
  1607. }
  1608. {
  1609. state.max_instances_per_buffer = uint32_t(GLOBAL_GET("rendering/2d/batching/item_buffer_size"));
  1610. state.max_instance_buffer_size = state.max_instances_per_buffer * sizeof(InstanceData);
  1611. state.canvas_instance_batches.reserve(200);
  1612. for (uint32_t i = 0; i < BATCH_DATA_BUFFER_COUNT; i++) {
  1613. DataBuffer &db = state.canvas_instance_data_buffers[i];
  1614. db.instance_buffers.push_back(RD::get_singleton()->storage_buffer_create(state.max_instance_buffer_size));
  1615. }
  1616. state.instance_data_array = memnew_arr(InstanceData, state.max_instances_per_buffer);
  1617. }
  1618. }
  1619. bool RendererCanvasRenderRD::free(RID p_rid) {
  1620. if (canvas_light_owner.owns(p_rid)) {
  1621. CanvasLight *cl = canvas_light_owner.get_or_null(p_rid);
  1622. ERR_FAIL_NULL_V(cl, false);
  1623. light_set_use_shadow(p_rid, false);
  1624. canvas_light_owner.free(p_rid);
  1625. } else if (occluder_polygon_owner.owns(p_rid)) {
  1626. occluder_polygon_set_shape(p_rid, Vector<Vector2>(), false);
  1627. occluder_polygon_owner.free(p_rid);
  1628. } else {
  1629. return false;
  1630. }
  1631. return true;
  1632. }
  1633. void RendererCanvasRenderRD::set_shadow_texture_size(int p_size) {
  1634. p_size = MAX(1, nearest_power_of_2_templated(p_size));
  1635. if (p_size == state.shadow_texture_size) {
  1636. return;
  1637. }
  1638. state.shadow_texture_size = p_size;
  1639. if (state.shadow_fb.is_valid()) {
  1640. RD::get_singleton()->free(state.shadow_texture);
  1641. RD::get_singleton()->free(state.shadow_depth_texture);
  1642. state.shadow_fb = RID();
  1643. {
  1644. //create a default shadow texture to keep uniform set happy (and that it gets erased when a new one is created)
  1645. RD::TextureFormat tf;
  1646. tf.texture_type = RD::TEXTURE_TYPE_2D;
  1647. tf.width = 4;
  1648. tf.height = 4;
  1649. tf.usage_bits = RD::TEXTURE_USAGE_SAMPLING_BIT;
  1650. tf.format = RD::DATA_FORMAT_R32_SFLOAT;
  1651. state.shadow_texture = RD::get_singleton()->texture_create(tf, RD::TextureView());
  1652. }
  1653. }
  1654. }
  1655. void RendererCanvasRenderRD::set_debug_redraw(bool p_enabled, double p_time, const Color &p_color) {
  1656. debug_redraw = p_enabled;
  1657. debug_redraw_time = p_time;
  1658. debug_redraw_color = p_color;
  1659. }
  1660. uint32_t RendererCanvasRenderRD::get_pipeline_compilations(RS::PipelineSource p_source) {
  1661. RendererCanvasRenderRD *canvas_singleton = static_cast<RendererCanvasRenderRD *>(RendererCanvasRender::singleton);
  1662. MutexLock lock(canvas_singleton->shader.mutex);
  1663. return shader.pipeline_compilations[p_source];
  1664. }
  1665. void RendererCanvasRenderRD::_render_batch_items(RenderTarget p_to_render_target, int p_item_count, const Transform2D &p_canvas_transform_inverse, Light *p_lights, bool &r_sdf_used, bool p_to_backbuffer, RenderingMethod::RenderInfo *r_render_info) {
  1666. // Record batches
  1667. uint32_t instance_index = 0;
  1668. {
  1669. RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
  1670. Item *current_clip = nullptr;
  1671. // Record Batches.
  1672. // First item always forms its own batch.
  1673. bool batch_broken = false;
  1674. Batch *current_batch = _new_batch(batch_broken);
  1675. // Override the start position and index as we want to start from where we finished off last time.
  1676. current_batch->start = state.last_instance_index;
  1677. for (int i = 0; i < p_item_count; i++) {
  1678. Item *ci = items[i];
  1679. if (ci->final_clip_owner != current_batch->clip) {
  1680. current_batch = _new_batch(batch_broken);
  1681. current_batch->clip = ci->final_clip_owner;
  1682. current_clip = ci->final_clip_owner;
  1683. }
  1684. RID material = ci->material_owner == nullptr ? ci->material : ci->material_owner->material;
  1685. if (ci->use_canvas_group) {
  1686. if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_AND_DRAW) {
  1687. material = default_clip_children_material;
  1688. } else {
  1689. if (material.is_null()) {
  1690. if (ci->canvas_group->mode == RS::CANVAS_GROUP_MODE_CLIP_ONLY) {
  1691. material = default_clip_children_material;
  1692. } else {
  1693. material = default_canvas_group_material;
  1694. }
  1695. }
  1696. }
  1697. }
  1698. if (material != current_batch->material) {
  1699. current_batch = _new_batch(batch_broken);
  1700. CanvasMaterialData *material_data = nullptr;
  1701. if (material.is_valid()) {
  1702. material_data = static_cast<CanvasMaterialData *>(material_storage->material_get_data(material, RendererRD::MaterialStorage::SHADER_TYPE_2D));
  1703. }
  1704. current_batch->material = material;
  1705. current_batch->material_data = material_data;
  1706. }
  1707. if (ci->repeat_source_item == nullptr || ci->repeat_size == Vector2()) {
  1708. Transform2D base_transform = p_canvas_transform_inverse * ci->final_transform;
  1709. _record_item_commands(ci, p_to_render_target, base_transform, current_clip, p_lights, instance_index, batch_broken, r_sdf_used, current_batch);
  1710. } else {
  1711. Point2 start_pos = ci->repeat_size * -(ci->repeat_times / 2);
  1712. Point2 offset;
  1713. int repeat_times_x = ci->repeat_size.x ? ci->repeat_times : 0;
  1714. int repeat_times_y = ci->repeat_size.y ? ci->repeat_times : 0;
  1715. for (int ry = 0; ry <= repeat_times_y; ry++) {
  1716. offset.y = start_pos.y + ry * ci->repeat_size.y;
  1717. for (int rx = 0; rx <= repeat_times_x; rx++) {
  1718. offset.x = start_pos.x + rx * ci->repeat_size.x;
  1719. Transform2D base_transform = ci->final_transform;
  1720. base_transform.columns[2] += ci->repeat_source_item->final_transform.basis_xform(offset);
  1721. base_transform = p_canvas_transform_inverse * base_transform;
  1722. _record_item_commands(ci, p_to_render_target, base_transform, current_clip, p_lights, instance_index, batch_broken, r_sdf_used, current_batch);
  1723. }
  1724. }
  1725. }
  1726. }
  1727. // Copy over remaining data needed for rendering.
  1728. if (instance_index > 0) {
  1729. RD::get_singleton()->buffer_update(
  1730. state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.current_instance_buffer_index],
  1731. state.last_instance_index * sizeof(InstanceData),
  1732. instance_index * sizeof(InstanceData),
  1733. state.instance_data_array);
  1734. }
  1735. }
  1736. if (state.canvas_instance_batches.is_empty()) {
  1737. // Nothing to render, just return.
  1738. return;
  1739. }
  1740. // Render batches
  1741. RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();
  1742. RID framebuffer;
  1743. RID fb_uniform_set;
  1744. bool clear = false;
  1745. Vector<Color> clear_colors;
  1746. if (p_to_backbuffer) {
  1747. framebuffer = texture_storage->render_target_get_rd_backbuffer_framebuffer(p_to_render_target.render_target);
  1748. fb_uniform_set = texture_storage->render_target_get_backbuffer_uniform_set(p_to_render_target.render_target);
  1749. } else {
  1750. framebuffer = texture_storage->render_target_get_rd_framebuffer(p_to_render_target.render_target);
  1751. texture_storage->render_target_set_msaa_needs_resolve(p_to_render_target.render_target, false); // If MSAA is enabled, our framebuffer will be resolved!
  1752. if (texture_storage->render_target_is_clear_requested(p_to_render_target.render_target)) {
  1753. clear = true;
  1754. clear_colors.push_back(texture_storage->render_target_get_clear_request_color(p_to_render_target.render_target));
  1755. texture_storage->render_target_disable_clear_request(p_to_render_target.render_target);
  1756. }
  1757. // TODO: Obtain from framebuffer format eventually when this is implemented.
  1758. fb_uniform_set = texture_storage->render_target_get_framebuffer_uniform_set(p_to_render_target.render_target);
  1759. }
  1760. if (fb_uniform_set.is_null() || !RD::get_singleton()->uniform_set_is_valid(fb_uniform_set)) {
  1761. fb_uniform_set = _create_base_uniform_set(p_to_render_target.render_target, p_to_backbuffer);
  1762. }
  1763. RD::FramebufferFormatID fb_format = RD::get_singleton()->framebuffer_get_format(framebuffer);
  1764. RD::DrawListID draw_list = RD::get_singleton()->draw_list_begin(framebuffer, clear ? RD::DRAW_CLEAR_COLOR_0 : RD::DRAW_DEFAULT_ALL, clear_colors, 1.0f, 0, Rect2(), RDD::BreadcrumbMarker::UI_PASS);
  1765. RD::get_singleton()->draw_list_bind_uniform_set(draw_list, fb_uniform_set, BASE_UNIFORM_SET);
  1766. RD::get_singleton()->draw_list_bind_uniform_set(draw_list, state.default_transforms_uniform_set, TRANSFORMS_UNIFORM_SET);
  1767. Item *current_clip = nullptr;
  1768. state.current_batch_uniform_set = RID();
  1769. for (uint32_t i = 0; i <= state.current_batch_index; i++) {
  1770. Batch *current_batch = &state.canvas_instance_batches[i];
  1771. // Skipping when there is no instances.
  1772. if (current_batch->instance_count == 0) {
  1773. continue;
  1774. }
  1775. //setup clip
  1776. if (current_clip != current_batch->clip) {
  1777. current_clip = current_batch->clip;
  1778. if (current_clip) {
  1779. RD::get_singleton()->draw_list_enable_scissor(draw_list, current_clip->final_clip_rect);
  1780. } else {
  1781. RD::get_singleton()->draw_list_disable_scissor(draw_list);
  1782. }
  1783. }
  1784. CanvasShaderData *shader_data = shader.default_version_data;
  1785. CanvasMaterialData *material_data = current_batch->material_data;
  1786. if (material_data) {
  1787. if (material_data->shader_data->version.is_valid() && material_data->shader_data->is_valid()) {
  1788. shader_data = material_data->shader_data;
  1789. // Update uniform set.
  1790. RID uniform_set = texture_storage->render_target_is_using_hdr(p_to_render_target.render_target) ? material_data->uniform_set : material_data->uniform_set_srgb;
  1791. if (uniform_set.is_valid() && RD::get_singleton()->uniform_set_is_valid(uniform_set)) { // Material may not have a uniform set.
  1792. RD::get_singleton()->draw_list_bind_uniform_set(draw_list, uniform_set, MATERIAL_UNIFORM_SET);
  1793. material_data->set_as_used();
  1794. }
  1795. }
  1796. }
  1797. _render_batch(draw_list, shader_data, fb_format, p_lights, current_batch, r_render_info);
  1798. }
  1799. RD::get_singleton()->draw_list_end();
  1800. texture_info_map.clear();
  1801. state.current_batch_index = 0;
  1802. state.canvas_instance_batches.clear();
  1803. state.last_instance_index += instance_index;
  1804. }
  1805. RendererCanvasRenderRD::InstanceData *RendererCanvasRenderRD::new_instance_data(float *p_world, uint32_t *p_lights, uint32_t p_base_flags, uint32_t p_index, TextureInfo *p_info) {
  1806. InstanceData *instance_data = &state.instance_data_array[p_index];
  1807. // Zero out most fields.
  1808. for (int i = 0; i < 4; i++) {
  1809. instance_data->modulation[i] = 0.0;
  1810. instance_data->ninepatch_margins[i] = 0.0;
  1811. instance_data->src_rect[i] = 0.0;
  1812. instance_data->dst_rect[i] = 0.0;
  1813. }
  1814. instance_data->pad[0] = 0.0;
  1815. instance_data->pad[1] = 0.0;
  1816. instance_data->lights[0] = p_lights[0];
  1817. instance_data->lights[1] = p_lights[1];
  1818. instance_data->lights[2] = p_lights[2];
  1819. instance_data->lights[3] = p_lights[3];
  1820. for (int i = 0; i < 6; i++) {
  1821. instance_data->world[i] = p_world[i];
  1822. }
  1823. instance_data->flags = p_base_flags; // Reset on each command for safety.
  1824. instance_data->color_texture_pixel_size[0] = p_info->texpixel_size.width;
  1825. instance_data->color_texture_pixel_size[1] = p_info->texpixel_size.height;
  1826. instance_data->pad1 = 0;
  1827. return instance_data;
  1828. }
  1829. void RendererCanvasRenderRD::_record_item_commands(const Item *p_item, RenderTarget p_render_target, const Transform2D &p_base_transform, Item *&r_current_clip, Light *p_lights, uint32_t &r_index, bool &r_batch_broken, bool &r_sdf_used, Batch *&r_current_batch) {
  1830. const RenderingServer::CanvasItemTextureFilter texture_filter = p_item->texture_filter == RS::CANVAS_ITEM_TEXTURE_FILTER_DEFAULT ? default_filter : p_item->texture_filter;
  1831. const RenderingServer::CanvasItemTextureRepeat texture_repeat = p_item->texture_repeat == RS::CANVAS_ITEM_TEXTURE_REPEAT_DEFAULT ? default_repeat : p_item->texture_repeat;
  1832. Transform2D base_transform = p_base_transform;
  1833. float world[6];
  1834. Transform2D draw_transform; // Used by transform command
  1835. _update_transform_2d_to_mat2x3(base_transform, world);
  1836. Color base_color = p_item->final_modulate;
  1837. bool use_linear_colors = p_render_target.use_linear_colors;
  1838. uint32_t base_flags = 0;
  1839. bool reclip = false;
  1840. bool skipping = false;
  1841. // TODO: consider making lights a per-batch property and then baking light operations in the shader for better performance.
  1842. uint32_t lights[4] = { 0, 0, 0, 0 };
  1843. uint16_t light_count = 0;
  1844. uint16_t shadow_mask = 0;
  1845. {
  1846. Light *light = p_lights;
  1847. while (light) {
  1848. if (light->render_index_cache >= 0 && p_item->light_mask & light->item_mask && p_item->z_final >= light->z_min && p_item->z_final <= light->z_max && p_item->global_rect_cache.intersects_transformed(light->xform_cache, light->rect_cache)) {
  1849. uint32_t light_index = light->render_index_cache;
  1850. lights[light_count >> 2] |= light_index << ((light_count & 3) * 8);
  1851. if (p_item->light_mask & light->item_shadow_mask) {
  1852. shadow_mask |= 1 << light_count;
  1853. }
  1854. light_count++;
  1855. if (light_count == MAX_LIGHTS_PER_ITEM - 1) {
  1856. break;
  1857. }
  1858. }
  1859. light = light->next_ptr;
  1860. }
  1861. base_flags |= light_count << INSTANCE_FLAGS_LIGHT_COUNT_SHIFT;
  1862. base_flags |= shadow_mask << INSTANCE_FLAGS_SHADOW_MASKED_SHIFT;
  1863. }
  1864. bool use_lighting = (light_count > 0 || using_directional_lights);
  1865. if (use_lighting != r_current_batch->use_lighting) {
  1866. r_current_batch = _new_batch(r_batch_broken);
  1867. r_current_batch->use_lighting = use_lighting;
  1868. }
  1869. const Item::Command *c = p_item->commands;
  1870. while (c) {
  1871. if (skipping && c->type != Item::Command::TYPE_ANIMATION_SLICE) {
  1872. c = c->next;
  1873. continue;
  1874. }
  1875. switch (c->type) {
  1876. case Item::Command::TYPE_RECT: {
  1877. const Item::CommandRect *rect = static_cast<const Item::CommandRect *>(c);
  1878. // 1: If commands are different, start a new batch.
  1879. if (r_current_batch->command_type != Item::Command::TYPE_RECT) {
  1880. r_current_batch = _new_batch(r_batch_broken);
  1881. r_current_batch->command_type = Item::Command::TYPE_RECT;
  1882. r_current_batch->command = c;
  1883. // default variant
  1884. r_current_batch->shader_variant = SHADER_VARIANT_QUAD;
  1885. r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_TRIANGLES;
  1886. r_current_batch->flags = 0;
  1887. }
  1888. RenderingServer::CanvasItemTextureRepeat rect_repeat = texture_repeat;
  1889. if (bool(rect->flags & CANVAS_RECT_TILE)) {
  1890. rect_repeat = RenderingServer::CanvasItemTextureRepeat::CANVAS_ITEM_TEXTURE_REPEAT_ENABLED;
  1891. }
  1892. Color modulated = rect->modulate * base_color;
  1893. if (use_linear_colors) {
  1894. modulated = modulated.srgb_to_linear();
  1895. }
  1896. bool has_blend = bool(rect->flags & CANVAS_RECT_LCD);
  1897. // Start a new batch if the blend mode has changed,
  1898. // or blend mode is enabled and the modulation has changed.
  1899. if (has_blend != r_current_batch->has_blend || (has_blend && modulated != r_current_batch->modulate)) {
  1900. r_current_batch = _new_batch(r_batch_broken);
  1901. r_current_batch->has_blend = has_blend;
  1902. r_current_batch->modulate = modulated;
  1903. r_current_batch->shader_variant = SHADER_VARIANT_QUAD;
  1904. r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_TRIANGLES;
  1905. }
  1906. bool has_msdf = bool(rect->flags & CANVAS_RECT_MSDF);
  1907. TextureState tex_state(rect->texture, texture_filter, rect_repeat, has_msdf, use_linear_colors);
  1908. TextureInfo *tex_info = texture_info_map.getptr(tex_state);
  1909. if (!tex_info) {
  1910. tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;
  1911. _prepare_batch_texture_info(rect->texture, tex_state, tex_info);
  1912. }
  1913. if (r_current_batch->tex_info != tex_info) {
  1914. r_current_batch = _new_batch(r_batch_broken);
  1915. r_current_batch->tex_info = tex_info;
  1916. }
  1917. InstanceData *instance_data = new_instance_data(world, lights, base_flags, r_index, tex_info);
  1918. Rect2 src_rect;
  1919. Rect2 dst_rect;
  1920. if (rect->texture.is_valid()) {
  1921. src_rect = (rect->flags & CANVAS_RECT_REGION) ? Rect2(rect->source.position * tex_info->texpixel_size, rect->source.size * tex_info->texpixel_size) : Rect2(0, 0, 1, 1);
  1922. dst_rect = Rect2(rect->rect.position, rect->rect.size);
  1923. if (dst_rect.size.width < 0) {
  1924. dst_rect.position.x += dst_rect.size.width;
  1925. dst_rect.size.width *= -1;
  1926. }
  1927. if (dst_rect.size.height < 0) {
  1928. dst_rect.position.y += dst_rect.size.height;
  1929. dst_rect.size.height *= -1;
  1930. }
  1931. if (rect->flags & CANVAS_RECT_FLIP_H) {
  1932. src_rect.size.x *= -1;
  1933. }
  1934. if (rect->flags & CANVAS_RECT_FLIP_V) {
  1935. src_rect.size.y *= -1;
  1936. }
  1937. if (rect->flags & CANVAS_RECT_TRANSPOSE) {
  1938. instance_data->flags |= INSTANCE_FLAGS_TRANSPOSE_RECT;
  1939. }
  1940. if (rect->flags & CANVAS_RECT_CLIP_UV) {
  1941. instance_data->flags |= INSTANCE_FLAGS_CLIP_RECT_UV;
  1942. }
  1943. } else {
  1944. dst_rect = Rect2(rect->rect.position, rect->rect.size);
  1945. if (dst_rect.size.width < 0) {
  1946. dst_rect.position.x += dst_rect.size.width;
  1947. dst_rect.size.width *= -1;
  1948. }
  1949. if (dst_rect.size.height < 0) {
  1950. dst_rect.position.y += dst_rect.size.height;
  1951. dst_rect.size.height *= -1;
  1952. }
  1953. src_rect = Rect2(0, 0, 1, 1);
  1954. }
  1955. if (has_msdf) {
  1956. instance_data->flags |= INSTANCE_FLAGS_USE_MSDF;
  1957. instance_data->msdf[0] = rect->px_range; // Pixel range.
  1958. instance_data->msdf[1] = rect->outline; // Outline size.
  1959. instance_data->msdf[2] = 0.f; // Reserved.
  1960. instance_data->msdf[3] = 0.f; // Reserved.
  1961. } else if (rect->flags & CANVAS_RECT_LCD) {
  1962. instance_data->flags |= INSTANCE_FLAGS_USE_LCD;
  1963. }
  1964. instance_data->modulation[0] = modulated.r;
  1965. instance_data->modulation[1] = modulated.g;
  1966. instance_data->modulation[2] = modulated.b;
  1967. instance_data->modulation[3] = modulated.a;
  1968. instance_data->src_rect[0] = src_rect.position.x;
  1969. instance_data->src_rect[1] = src_rect.position.y;
  1970. instance_data->src_rect[2] = src_rect.size.width;
  1971. instance_data->src_rect[3] = src_rect.size.height;
  1972. instance_data->dst_rect[0] = dst_rect.position.x;
  1973. instance_data->dst_rect[1] = dst_rect.position.y;
  1974. instance_data->dst_rect[2] = dst_rect.size.width;
  1975. instance_data->dst_rect[3] = dst_rect.size.height;
  1976. _add_to_batch(r_index, r_batch_broken, r_current_batch);
  1977. } break;
  1978. case Item::Command::TYPE_NINEPATCH: {
  1979. const Item::CommandNinePatch *np = static_cast<const Item::CommandNinePatch *>(c);
  1980. if (r_current_batch->command_type != Item::Command::TYPE_NINEPATCH) {
  1981. r_current_batch = _new_batch(r_batch_broken);
  1982. r_current_batch->command_type = Item::Command::TYPE_NINEPATCH;
  1983. r_current_batch->command = c;
  1984. r_current_batch->has_blend = false;
  1985. r_current_batch->shader_variant = SHADER_VARIANT_NINEPATCH;
  1986. r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_TRIANGLES;
  1987. r_current_batch->flags = 0;
  1988. }
  1989. TextureState tex_state(np->texture, texture_filter, texture_repeat, false, use_linear_colors);
  1990. TextureInfo *tex_info = texture_info_map.getptr(tex_state);
  1991. if (!tex_info) {
  1992. tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;
  1993. _prepare_batch_texture_info(np->texture, tex_state, tex_info);
  1994. }
  1995. if (r_current_batch->tex_info != tex_info) {
  1996. r_current_batch = _new_batch(r_batch_broken);
  1997. r_current_batch->tex_info = tex_info;
  1998. }
  1999. InstanceData *instance_data = new_instance_data(world, lights, base_flags, r_index, tex_info);
  2000. Rect2 src_rect;
  2001. Rect2 dst_rect(np->rect.position.x, np->rect.position.y, np->rect.size.x, np->rect.size.y);
  2002. if (np->texture.is_null()) {
  2003. src_rect = Rect2(0, 0, 1, 1);
  2004. } else {
  2005. if (np->source != Rect2()) {
  2006. src_rect = Rect2(np->source.position.x * tex_info->texpixel_size.width, np->source.position.y * tex_info->texpixel_size.height, np->source.size.x * tex_info->texpixel_size.width, np->source.size.y * tex_info->texpixel_size.height);
  2007. instance_data->color_texture_pixel_size[0] = 1.0 / np->source.size.width;
  2008. instance_data->color_texture_pixel_size[1] = 1.0 / np->source.size.height;
  2009. } else {
  2010. src_rect = Rect2(0, 0, 1, 1);
  2011. }
  2012. }
  2013. Color modulated = np->color * base_color;
  2014. if (use_linear_colors) {
  2015. modulated = modulated.srgb_to_linear();
  2016. }
  2017. instance_data->modulation[0] = modulated.r;
  2018. instance_data->modulation[1] = modulated.g;
  2019. instance_data->modulation[2] = modulated.b;
  2020. instance_data->modulation[3] = modulated.a;
  2021. instance_data->src_rect[0] = src_rect.position.x;
  2022. instance_data->src_rect[1] = src_rect.position.y;
  2023. instance_data->src_rect[2] = src_rect.size.width;
  2024. instance_data->src_rect[3] = src_rect.size.height;
  2025. instance_data->dst_rect[0] = dst_rect.position.x;
  2026. instance_data->dst_rect[1] = dst_rect.position.y;
  2027. instance_data->dst_rect[2] = dst_rect.size.width;
  2028. instance_data->dst_rect[3] = dst_rect.size.height;
  2029. instance_data->flags |= int(np->axis_x) << INSTANCE_FLAGS_NINEPATCH_H_MODE_SHIFT;
  2030. instance_data->flags |= int(np->axis_y) << INSTANCE_FLAGS_NINEPATCH_V_MODE_SHIFT;
  2031. if (np->draw_center) {
  2032. instance_data->flags |= INSTANCE_FLAGS_NINEPACH_DRAW_CENTER;
  2033. }
  2034. instance_data->ninepatch_margins[0] = np->margin[SIDE_LEFT];
  2035. instance_data->ninepatch_margins[1] = np->margin[SIDE_TOP];
  2036. instance_data->ninepatch_margins[2] = np->margin[SIDE_RIGHT];
  2037. instance_data->ninepatch_margins[3] = np->margin[SIDE_BOTTOM];
  2038. _add_to_batch(r_index, r_batch_broken, r_current_batch);
  2039. } break;
  2040. case Item::Command::TYPE_POLYGON: {
  2041. const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(c);
  2042. // Polygon's can't be batched, so always create a new batch
  2043. r_current_batch = _new_batch(r_batch_broken);
  2044. r_current_batch->command_type = Item::Command::TYPE_POLYGON;
  2045. r_current_batch->has_blend = false;
  2046. r_current_batch->command = c;
  2047. r_current_batch->flags = 0;
  2048. TextureState tex_state(polygon->texture, texture_filter, texture_repeat, false, use_linear_colors);
  2049. TextureInfo *tex_info = texture_info_map.getptr(tex_state);
  2050. if (!tex_info) {
  2051. tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;
  2052. _prepare_batch_texture_info(polygon->texture, tex_state, tex_info);
  2053. }
  2054. if (r_current_batch->tex_info != tex_info) {
  2055. r_current_batch = _new_batch(r_batch_broken);
  2056. r_current_batch->tex_info = tex_info;
  2057. }
  2058. // pipeline variant
  2059. {
  2060. ERR_CONTINUE(polygon->primitive < 0 || polygon->primitive >= RS::PRIMITIVE_MAX);
  2061. r_current_batch->shader_variant = polygon->primitive == RS::PRIMITIVE_POINTS ? SHADER_VARIANT_ATTRIBUTES_POINTS : SHADER_VARIANT_ATTRIBUTES;
  2062. r_current_batch->render_primitive = _primitive_type_to_render_primitive(polygon->primitive);
  2063. }
  2064. InstanceData *instance_data = new_instance_data(world, lights, base_flags, r_index, tex_info);
  2065. Color color = base_color;
  2066. if (use_linear_colors) {
  2067. color = color.srgb_to_linear();
  2068. }
  2069. instance_data->modulation[0] = color.r;
  2070. instance_data->modulation[1] = color.g;
  2071. instance_data->modulation[2] = color.b;
  2072. instance_data->modulation[3] = color.a;
  2073. _add_to_batch(r_index, r_batch_broken, r_current_batch);
  2074. } break;
  2075. case Item::Command::TYPE_PRIMITIVE: {
  2076. const Item::CommandPrimitive *primitive = static_cast<const Item::CommandPrimitive *>(c);
  2077. if (primitive->point_count != r_current_batch->primitive_points || r_current_batch->command_type != Item::Command::TYPE_PRIMITIVE) {
  2078. r_current_batch = _new_batch(r_batch_broken);
  2079. r_current_batch->command_type = Item::Command::TYPE_PRIMITIVE;
  2080. r_current_batch->has_blend = false;
  2081. r_current_batch->command = c;
  2082. r_current_batch->primitive_points = primitive->point_count;
  2083. r_current_batch->flags = 0;
  2084. ERR_CONTINUE(primitive->point_count == 0 || primitive->point_count > 4);
  2085. switch (primitive->point_count) {
  2086. case 1:
  2087. r_current_batch->shader_variant = SHADER_VARIANT_PRIMITIVE_POINTS;
  2088. r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_POINTS;
  2089. break;
  2090. case 2:
  2091. r_current_batch->shader_variant = SHADER_VARIANT_PRIMITIVE;
  2092. r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_LINES;
  2093. break;
  2094. case 3:
  2095. case 4:
  2096. r_current_batch->shader_variant = SHADER_VARIANT_PRIMITIVE;
  2097. r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_TRIANGLES;
  2098. break;
  2099. default:
  2100. // Unknown point count.
  2101. break;
  2102. }
  2103. }
  2104. TextureState tex_state(primitive->texture, texture_filter, texture_repeat, false, use_linear_colors);
  2105. TextureInfo *tex_info = texture_info_map.getptr(tex_state);
  2106. if (!tex_info) {
  2107. tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;
  2108. _prepare_batch_texture_info(primitive->texture, tex_state, tex_info);
  2109. }
  2110. if (r_current_batch->tex_info != tex_info) {
  2111. r_current_batch = _new_batch(r_batch_broken);
  2112. r_current_batch->tex_info = tex_info;
  2113. }
  2114. InstanceData *instance_data = new_instance_data(world, lights, base_flags, r_index, tex_info);
  2115. for (uint32_t j = 0; j < MIN(3u, primitive->point_count); j++) {
  2116. instance_data->points[j * 2 + 0] = primitive->points[j].x;
  2117. instance_data->points[j * 2 + 1] = primitive->points[j].y;
  2118. instance_data->uvs[j * 2 + 0] = primitive->uvs[j].x;
  2119. instance_data->uvs[j * 2 + 1] = primitive->uvs[j].y;
  2120. Color col = primitive->colors[j] * base_color;
  2121. if (use_linear_colors) {
  2122. col = col.srgb_to_linear();
  2123. }
  2124. instance_data->colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
  2125. instance_data->colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
  2126. }
  2127. _add_to_batch(r_index, r_batch_broken, r_current_batch);
  2128. if (primitive->point_count == 4) {
  2129. instance_data = new_instance_data(world, lights, base_flags, r_index, tex_info);
  2130. for (uint32_t j = 0; j < 3; j++) {
  2131. int offset = j == 0 ? 0 : 1;
  2132. // Second triangle in the quad. Uses vertices 0, 2, 3.
  2133. instance_data->points[j * 2 + 0] = primitive->points[j + offset].x;
  2134. instance_data->points[j * 2 + 1] = primitive->points[j + offset].y;
  2135. instance_data->uvs[j * 2 + 0] = primitive->uvs[j + offset].x;
  2136. instance_data->uvs[j * 2 + 1] = primitive->uvs[j + offset].y;
  2137. Color col = primitive->colors[j + offset] * base_color;
  2138. if (use_linear_colors) {
  2139. col = col.srgb_to_linear();
  2140. }
  2141. instance_data->colors[j * 2 + 0] = (uint32_t(Math::make_half_float(col.g)) << 16) | Math::make_half_float(col.r);
  2142. instance_data->colors[j * 2 + 1] = (uint32_t(Math::make_half_float(col.a)) << 16) | Math::make_half_float(col.b);
  2143. }
  2144. _add_to_batch(r_index, r_batch_broken, r_current_batch);
  2145. }
  2146. } break;
  2147. case Item::Command::TYPE_MESH:
  2148. case Item::Command::TYPE_MULTIMESH:
  2149. case Item::Command::TYPE_PARTICLES: {
  2150. // Mesh's can't be batched, so always create a new batch
  2151. r_current_batch = _new_batch(r_batch_broken);
  2152. r_current_batch->command = c;
  2153. r_current_batch->command_type = c->type;
  2154. r_current_batch->has_blend = false;
  2155. r_current_batch->flags = 0;
  2156. InstanceData *instance_data = nullptr;
  2157. Color modulate(1, 1, 1, 1);
  2158. if (c->type == Item::Command::TYPE_MESH) {
  2159. const Item::CommandMesh *m = static_cast<const Item::CommandMesh *>(c);
  2160. TextureState tex_state(m->texture, texture_filter, texture_repeat, false, use_linear_colors);
  2161. TextureInfo *tex_info = texture_info_map.getptr(tex_state);
  2162. if (!tex_info) {
  2163. tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;
  2164. _prepare_batch_texture_info(m->texture, tex_state, tex_info);
  2165. }
  2166. r_current_batch->tex_info = tex_info;
  2167. instance_data = new_instance_data(world, lights, base_flags, r_index, tex_info);
  2168. r_current_batch->mesh_instance_count = 1;
  2169. _update_transform_2d_to_mat2x3(base_transform * draw_transform * m->transform, instance_data->world);
  2170. modulate = m->modulate;
  2171. } else if (c->type == Item::Command::TYPE_MULTIMESH) {
  2172. RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton();
  2173. const Item::CommandMultiMesh *mm = static_cast<const Item::CommandMultiMesh *>(c);
  2174. RID multimesh = mm->multimesh;
  2175. if (mesh_storage->multimesh_get_transform_format(multimesh) != RS::MULTIMESH_TRANSFORM_2D) {
  2176. break;
  2177. }
  2178. r_current_batch->mesh_instance_count = mesh_storage->multimesh_get_instances_to_draw(multimesh);
  2179. if (r_current_batch->mesh_instance_count == 0) {
  2180. break;
  2181. }
  2182. TextureState tex_state(mm->texture, texture_filter, texture_repeat, false, use_linear_colors);
  2183. TextureInfo *tex_info = texture_info_map.getptr(tex_state);
  2184. if (!tex_info) {
  2185. tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;
  2186. _prepare_batch_texture_info(mm->texture, tex_state, tex_info);
  2187. }
  2188. r_current_batch->tex_info = tex_info;
  2189. instance_data = new_instance_data(world, lights, base_flags, r_index, tex_info);
  2190. r_current_batch->flags |= 1; // multimesh, trails disabled
  2191. if (mesh_storage->multimesh_uses_colors(mm->multimesh)) {
  2192. r_current_batch->flags |= BATCH_FLAGS_INSTANCING_HAS_COLORS;
  2193. }
  2194. if (mesh_storage->multimesh_uses_custom_data(mm->multimesh)) {
  2195. r_current_batch->flags |= BATCH_FLAGS_INSTANCING_HAS_CUSTOM_DATA;
  2196. }
  2197. } else if (c->type == Item::Command::TYPE_PARTICLES) {
  2198. RendererRD::TextureStorage *texture_storage = RendererRD::TextureStorage::get_singleton();
  2199. RendererRD::ParticlesStorage *particles_storage = RendererRD::ParticlesStorage::get_singleton();
  2200. const Item::CommandParticles *pt = static_cast<const Item::CommandParticles *>(c);
  2201. TextureState tex_state(pt->texture, texture_filter, texture_repeat, false, use_linear_colors);
  2202. TextureInfo *tex_info = texture_info_map.getptr(tex_state);
  2203. if (!tex_info) {
  2204. tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;
  2205. _prepare_batch_texture_info(pt->texture, tex_state, tex_info);
  2206. }
  2207. r_current_batch->tex_info = tex_info;
  2208. instance_data = new_instance_data(world, lights, base_flags, r_index, tex_info);
  2209. uint32_t divisor = 1;
  2210. r_current_batch->mesh_instance_count = particles_storage->particles_get_amount(pt->particles, divisor);
  2211. r_current_batch->flags |= (divisor & BATCH_FLAGS_INSTANCING_MASK);
  2212. r_current_batch->mesh_instance_count /= divisor;
  2213. RID particles = pt->particles;
  2214. r_current_batch->flags |= BATCH_FLAGS_INSTANCING_HAS_COLORS;
  2215. r_current_batch->flags |= BATCH_FLAGS_INSTANCING_HAS_CUSTOM_DATA;
  2216. if (particles_storage->particles_has_collision(particles) && texture_storage->render_target_is_sdf_enabled(p_render_target.render_target)) {
  2217. // Pass collision information.
  2218. Transform2D xform = p_item->final_transform;
  2219. RID sdf_texture = texture_storage->render_target_get_sdf_texture(p_render_target.render_target);
  2220. Rect2 to_screen;
  2221. {
  2222. Rect2 sdf_rect = texture_storage->render_target_get_sdf_rect(p_render_target.render_target);
  2223. to_screen.size = Vector2(1.0 / sdf_rect.size.width, 1.0 / sdf_rect.size.height);
  2224. to_screen.position = -sdf_rect.position * to_screen.size;
  2225. }
  2226. particles_storage->particles_set_canvas_sdf_collision(pt->particles, true, xform, to_screen, sdf_texture);
  2227. } else {
  2228. particles_storage->particles_set_canvas_sdf_collision(pt->particles, false, Transform2D(), Rect2(), RID());
  2229. }
  2230. r_sdf_used |= particles_storage->particles_has_collision(particles);
  2231. }
  2232. Color modulated = modulate * base_color;
  2233. if (use_linear_colors) {
  2234. modulated = modulated.srgb_to_linear();
  2235. }
  2236. instance_data->modulation[0] = modulated.r;
  2237. instance_data->modulation[1] = modulated.g;
  2238. instance_data->modulation[2] = modulated.b;
  2239. instance_data->modulation[3] = modulated.a;
  2240. _add_to_batch(r_index, r_batch_broken, r_current_batch);
  2241. } break;
  2242. case Item::Command::TYPE_TRANSFORM: {
  2243. const Item::CommandTransform *transform = static_cast<const Item::CommandTransform *>(c);
  2244. draw_transform = transform->xform;
  2245. _update_transform_2d_to_mat2x3(base_transform * transform->xform, world);
  2246. } break;
  2247. case Item::Command::TYPE_CLIP_IGNORE: {
  2248. const Item::CommandClipIgnore *ci = static_cast<const Item::CommandClipIgnore *>(c);
  2249. if (r_current_clip) {
  2250. if (ci->ignore != reclip) {
  2251. r_current_batch = _new_batch(r_batch_broken);
  2252. if (ci->ignore) {
  2253. r_current_batch->clip = nullptr;
  2254. reclip = true;
  2255. } else {
  2256. r_current_batch->clip = r_current_clip;
  2257. reclip = false;
  2258. }
  2259. }
  2260. }
  2261. } break;
  2262. case Item::Command::TYPE_ANIMATION_SLICE: {
  2263. const Item::CommandAnimationSlice *as = static_cast<const Item::CommandAnimationSlice *>(c);
  2264. double current_time = RSG::rasterizer->get_total_time();
  2265. double local_time = Math::fposmod(current_time - as->offset, as->animation_length);
  2266. skipping = !(local_time >= as->slice_begin && local_time < as->slice_end);
  2267. RenderingServerDefault::redraw_request(); // animation visible means redraw request
  2268. } break;
  2269. }
  2270. c = c->next;
  2271. r_batch_broken = false;
  2272. }
  2273. #ifdef DEBUG_ENABLED
  2274. if (debug_redraw && p_item->debug_redraw_time > 0.0) {
  2275. Color dc = debug_redraw_color;
  2276. dc.a *= p_item->debug_redraw_time / debug_redraw_time;
  2277. // 1: If commands are different, start a new batch.
  2278. if (r_current_batch->command_type != Item::Command::TYPE_RECT) {
  2279. r_current_batch = _new_batch(r_batch_broken);
  2280. r_current_batch->command_type = Item::Command::TYPE_RECT;
  2281. // it is ok to be null for a TYPE_RECT
  2282. r_current_batch->command = nullptr;
  2283. // default variant
  2284. r_current_batch->shader_variant = SHADER_VARIANT_QUAD;
  2285. r_current_batch->render_primitive = RD::RENDER_PRIMITIVE_TRIANGLES;
  2286. r_current_batch->flags = 0;
  2287. }
  2288. // 2: If the current batch has lighting, start a new batch.
  2289. if (r_current_batch->use_lighting) {
  2290. r_current_batch = _new_batch(r_batch_broken);
  2291. r_current_batch->use_lighting = false;
  2292. }
  2293. // 3: If the current batch has blend, start a new batch.
  2294. if (r_current_batch->has_blend) {
  2295. r_current_batch = _new_batch(r_batch_broken);
  2296. r_current_batch->has_blend = false;
  2297. }
  2298. TextureState tex_state(default_canvas_texture, texture_filter, texture_repeat, false, use_linear_colors);
  2299. TextureInfo *tex_info = texture_info_map.getptr(tex_state);
  2300. if (!tex_info) {
  2301. tex_info = &texture_info_map.insert(tex_state, TextureInfo())->value;
  2302. _prepare_batch_texture_info(default_canvas_texture, tex_state, tex_info);
  2303. }
  2304. if (r_current_batch->tex_info != tex_info) {
  2305. r_current_batch = _new_batch(r_batch_broken);
  2306. r_current_batch->tex_info = tex_info;
  2307. }
  2308. InstanceData *instance_data = new_instance_data(world, lights, base_flags, r_index, tex_info);
  2309. Rect2 src_rect;
  2310. Rect2 dst_rect;
  2311. dst_rect = Rect2(Vector2(), p_item->rect.size);
  2312. if (dst_rect.size.width < 0) {
  2313. dst_rect.position.x += dst_rect.size.width;
  2314. dst_rect.size.width *= -1;
  2315. }
  2316. if (dst_rect.size.height < 0) {
  2317. dst_rect.position.y += dst_rect.size.height;
  2318. dst_rect.size.height *= -1;
  2319. }
  2320. src_rect = Rect2(0, 0, 1, 1);
  2321. instance_data->modulation[0] = dc.r;
  2322. instance_data->modulation[1] = dc.g;
  2323. instance_data->modulation[2] = dc.b;
  2324. instance_data->modulation[3] = dc.a;
  2325. instance_data->src_rect[0] = src_rect.position.x;
  2326. instance_data->src_rect[1] = src_rect.position.y;
  2327. instance_data->src_rect[2] = src_rect.size.width;
  2328. instance_data->src_rect[3] = src_rect.size.height;
  2329. instance_data->dst_rect[0] = dst_rect.position.x;
  2330. instance_data->dst_rect[1] = dst_rect.position.y;
  2331. instance_data->dst_rect[2] = dst_rect.size.width;
  2332. instance_data->dst_rect[3] = dst_rect.size.height;
  2333. _add_to_batch(r_index, r_batch_broken, r_current_batch);
  2334. p_item->debug_redraw_time -= RSG::rasterizer->get_frame_delta_time();
  2335. RenderingServerDefault::redraw_request();
  2336. r_batch_broken = false;
  2337. }
  2338. #endif
  2339. if (r_current_clip && reclip) {
  2340. // will make it re-enable clipping if needed afterwards
  2341. r_current_clip = nullptr;
  2342. }
  2343. }
  2344. void RendererCanvasRenderRD::_before_evict(RendererCanvasRenderRD::RIDSetKey &p_key, RID &p_rid) {
  2345. RD::get_singleton()->uniform_set_set_invalidation_callback(p_rid, nullptr, nullptr);
  2346. RD::get_singleton()->free(p_rid);
  2347. }
  2348. void RendererCanvasRenderRD::_uniform_set_invalidation_callback(void *p_userdata) {
  2349. const RIDSetKey *key = static_cast<RIDSetKey *>(p_userdata);
  2350. static_cast<RendererCanvasRenderRD *>(singleton)->rid_set_to_uniform_set.erase(*key);
  2351. }
  2352. void RendererCanvasRenderRD::_render_batch(RD::DrawListID p_draw_list, CanvasShaderData *p_shader_data, RenderingDevice::FramebufferFormatID p_framebuffer_format, Light *p_lights, Batch const *p_batch, RenderingMethod::RenderInfo *r_render_info) {
  2353. {
  2354. RIDSetKey key(
  2355. p_batch->tex_info->state,
  2356. state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[p_batch->instance_buffer_index]);
  2357. const RID *uniform_set = rid_set_to_uniform_set.getptr(key);
  2358. if (uniform_set == nullptr) {
  2359. RD::Uniform *uniform_ptrw = state.batch_texture_uniforms.ptrw();
  2360. uniform_ptrw[0] = RD::Uniform(RD::UNIFORM_TYPE_TEXTURE, 0, p_batch->tex_info->diffuse);
  2361. uniform_ptrw[1] = RD::Uniform(RD::UNIFORM_TYPE_TEXTURE, 1, p_batch->tex_info->normal);
  2362. uniform_ptrw[2] = RD::Uniform(RD::UNIFORM_TYPE_TEXTURE, 2, p_batch->tex_info->specular);
  2363. uniform_ptrw[3] = RD::Uniform(RD::UNIFORM_TYPE_SAMPLER, 3, p_batch->tex_info->sampler);
  2364. uniform_ptrw[4] = RD::Uniform(RD::UNIFORM_TYPE_STORAGE_BUFFER, 4, state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[p_batch->instance_buffer_index]);
  2365. RID rid = RD::get_singleton()->uniform_set_create(state.batch_texture_uniforms, shader.default_version_rd_shader, BATCH_UNIFORM_SET);
  2366. ERR_FAIL_COND_MSG(rid.is_null(), "Failed to create uniform set for batch.");
  2367. const RIDCache::Pair *iter = rid_set_to_uniform_set.insert(key, rid);
  2368. uniform_set = &iter->data;
  2369. RD::get_singleton()->uniform_set_set_invalidation_callback(rid, RendererCanvasRenderRD::_uniform_set_invalidation_callback, (void *)&iter->key);
  2370. }
  2371. if (state.current_batch_uniform_set != *uniform_set) {
  2372. state.current_batch_uniform_set = *uniform_set;
  2373. RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, *uniform_set, BATCH_UNIFORM_SET);
  2374. }
  2375. }
  2376. PushConstant push_constant;
  2377. push_constant.base_instance_index = p_batch->start;
  2378. push_constant.specular_shininess = p_batch->tex_info->specular_shininess;
  2379. push_constant.batch_flags = p_batch->tex_info->flags | p_batch->flags;
  2380. RID pipeline;
  2381. PipelineKey pipeline_key;
  2382. pipeline_key.framebuffer_format_id = p_framebuffer_format;
  2383. pipeline_key.variant = p_batch->shader_variant;
  2384. pipeline_key.render_primitive = p_batch->render_primitive;
  2385. pipeline_key.shader_specialization.use_lighting = p_batch->use_lighting;
  2386. pipeline_key.lcd_blend = p_batch->has_blend;
  2387. switch (p_batch->command_type) {
  2388. case Item::Command::TYPE_RECT:
  2389. case Item::Command::TYPE_NINEPATCH: {
  2390. pipeline = _get_pipeline_specialization_or_ubershader(p_shader_data, pipeline_key, push_constant);
  2391. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
  2392. if (p_batch->has_blend) {
  2393. RD::get_singleton()->draw_list_set_blend_constants(p_draw_list, p_batch->modulate);
  2394. }
  2395. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
  2396. RD::get_singleton()->draw_list_bind_index_array(p_draw_list, shader.quad_index_array);
  2397. RD::get_singleton()->draw_list_draw(p_draw_list, true, p_batch->instance_count);
  2398. if (r_render_info) {
  2399. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME] += p_batch->instance_count;
  2400. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += 2 * p_batch->instance_count;
  2401. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
  2402. }
  2403. } break;
  2404. case Item::Command::TYPE_POLYGON: {
  2405. ERR_FAIL_NULL(p_batch->command);
  2406. const Item::CommandPolygon *polygon = static_cast<const Item::CommandPolygon *>(p_batch->command);
  2407. PolygonBuffers *pb = polygon_buffers.polygons.getptr(polygon->polygon.polygon_id);
  2408. ERR_FAIL_NULL(pb);
  2409. pipeline_key.vertex_format_id = pb->vertex_format_id;
  2410. pipeline = _get_pipeline_specialization_or_ubershader(p_shader_data, pipeline_key, push_constant);
  2411. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
  2412. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
  2413. RD::get_singleton()->draw_list_bind_vertex_array(p_draw_list, pb->vertex_array);
  2414. if (pb->indices.is_valid()) {
  2415. RD::get_singleton()->draw_list_bind_index_array(p_draw_list, pb->indices);
  2416. }
  2417. RD::get_singleton()->draw_list_draw(p_draw_list, pb->indices.is_valid());
  2418. if (r_render_info) {
  2419. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME]++;
  2420. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += _indices_to_primitives(polygon->primitive, pb->primitive_count);
  2421. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
  2422. }
  2423. } break;
  2424. case Item::Command::TYPE_PRIMITIVE: {
  2425. ERR_FAIL_NULL(p_batch->command);
  2426. const Item::CommandPrimitive *primitive = static_cast<const Item::CommandPrimitive *>(p_batch->command);
  2427. pipeline = _get_pipeline_specialization_or_ubershader(p_shader_data, pipeline_key, push_constant);
  2428. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
  2429. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
  2430. RD::get_singleton()->draw_list_bind_index_array(p_draw_list, primitive_arrays.index_array[MIN(3u, primitive->point_count) - 1]);
  2431. uint32_t instance_count = p_batch->instance_count;
  2432. RD::get_singleton()->draw_list_draw(p_draw_list, true, instance_count);
  2433. if (r_render_info) {
  2434. const RenderingServer::PrimitiveType rs_primitive[5] = { RS::PRIMITIVE_POINTS, RS::PRIMITIVE_POINTS, RS::PRIMITIVE_LINES, RS::PRIMITIVE_TRIANGLES, RS::PRIMITIVE_TRIANGLES };
  2435. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME] += instance_count;
  2436. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += _indices_to_primitives(rs_primitive[p_batch->primitive_points], p_batch->primitive_points) * instance_count;
  2437. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
  2438. }
  2439. } break;
  2440. case Item::Command::TYPE_MESH:
  2441. case Item::Command::TYPE_MULTIMESH:
  2442. case Item::Command::TYPE_PARTICLES: {
  2443. ERR_FAIL_NULL(p_batch->command);
  2444. RendererRD::MeshStorage *mesh_storage = RendererRD::MeshStorage::get_singleton();
  2445. RendererRD::ParticlesStorage *particles_storage = RendererRD::ParticlesStorage::get_singleton();
  2446. RID mesh;
  2447. RID mesh_instance;
  2448. if (p_batch->command_type == Item::Command::TYPE_MESH) {
  2449. const Item::CommandMesh *m = static_cast<const Item::CommandMesh *>(p_batch->command);
  2450. mesh = m->mesh;
  2451. mesh_instance = m->mesh_instance;
  2452. } else if (p_batch->command_type == Item::Command::TYPE_MULTIMESH) {
  2453. const Item::CommandMultiMesh *mm = static_cast<const Item::CommandMultiMesh *>(p_batch->command);
  2454. RID multimesh = mm->multimesh;
  2455. mesh = mesh_storage->multimesh_get_mesh(multimesh);
  2456. RID uniform_set = mesh_storage->multimesh_get_2d_uniform_set(multimesh, shader.default_version_rd_shader, TRANSFORMS_UNIFORM_SET);
  2457. RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, uniform_set, TRANSFORMS_UNIFORM_SET);
  2458. } else if (p_batch->command_type == Item::Command::TYPE_PARTICLES) {
  2459. const Item::CommandParticles *pt = static_cast<const Item::CommandParticles *>(p_batch->command);
  2460. RID particles = pt->particles;
  2461. mesh = particles_storage->particles_get_draw_pass_mesh(particles, 0);
  2462. ERR_BREAK(particles_storage->particles_get_mode(particles) != RS::PARTICLES_MODE_2D);
  2463. particles_storage->particles_request_process(particles);
  2464. if (particles_storage->particles_is_inactive(particles)) {
  2465. break;
  2466. }
  2467. RenderingServerDefault::redraw_request(); // Active particles means redraw request.
  2468. int dpc = particles_storage->particles_get_draw_passes(particles);
  2469. if (dpc == 0) {
  2470. break; // Nothing to draw.
  2471. }
  2472. RID uniform_set = particles_storage->particles_get_instance_buffer_uniform_set(pt->particles, shader.default_version_rd_shader, TRANSFORMS_UNIFORM_SET);
  2473. RD::get_singleton()->draw_list_bind_uniform_set(p_draw_list, uniform_set, TRANSFORMS_UNIFORM_SET);
  2474. }
  2475. if (mesh.is_null()) {
  2476. break;
  2477. }
  2478. uint32_t surf_count = mesh_storage->mesh_get_surface_count(mesh);
  2479. for (uint32_t j = 0; j < surf_count; j++) {
  2480. void *surface = mesh_storage->mesh_get_surface(mesh, j);
  2481. RS::PrimitiveType primitive = mesh_storage->mesh_surface_get_primitive(surface);
  2482. ERR_CONTINUE(primitive < 0 || primitive >= RS::PRIMITIVE_MAX);
  2483. RID vertex_array;
  2484. pipeline_key.variant = primitive == RS::PRIMITIVE_POINTS ? SHADER_VARIANT_ATTRIBUTES_POINTS : SHADER_VARIANT_ATTRIBUTES;
  2485. pipeline_key.render_primitive = _primitive_type_to_render_primitive(primitive);
  2486. pipeline_key.vertex_format_id = RD::INVALID_FORMAT_ID;
  2487. pipeline = _get_pipeline_specialization_or_ubershader(p_shader_data, pipeline_key, push_constant, mesh_instance, surface, j, &vertex_array);
  2488. RD::get_singleton()->draw_list_bind_render_pipeline(p_draw_list, pipeline);
  2489. RD::get_singleton()->draw_list_set_push_constant(p_draw_list, &push_constant, sizeof(PushConstant));
  2490. RID index_array = mesh_storage->mesh_surface_get_index_array(surface, 0);
  2491. if (index_array.is_valid()) {
  2492. RD::get_singleton()->draw_list_bind_index_array(p_draw_list, index_array);
  2493. }
  2494. RD::get_singleton()->draw_list_bind_vertex_array(p_draw_list, vertex_array);
  2495. RD::get_singleton()->draw_list_draw(p_draw_list, index_array.is_valid(), p_batch->mesh_instance_count);
  2496. if (r_render_info) {
  2497. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_OBJECTS_IN_FRAME]++;
  2498. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_PRIMITIVES_IN_FRAME] += _indices_to_primitives(primitive, mesh_storage->mesh_surface_get_vertices_drawn_count(surface)) * p_batch->mesh_instance_count;
  2499. r_render_info->info[RS::VIEWPORT_RENDER_INFO_TYPE_CANVAS][RS::VIEWPORT_RENDER_INFO_DRAW_CALLS_IN_FRAME]++;
  2500. }
  2501. }
  2502. } break;
  2503. case Item::Command::TYPE_TRANSFORM:
  2504. case Item::Command::TYPE_CLIP_IGNORE:
  2505. case Item::Command::TYPE_ANIMATION_SLICE: {
  2506. // Can ignore these as they only impact batch creation.
  2507. } break;
  2508. }
  2509. }
  2510. RendererCanvasRenderRD::Batch *RendererCanvasRenderRD::_new_batch(bool &r_batch_broken) {
  2511. if (state.canvas_instance_batches.size() == 0) {
  2512. state.canvas_instance_batches.push_back(Batch());
  2513. return state.canvas_instance_batches.ptr();
  2514. }
  2515. if (r_batch_broken || state.canvas_instance_batches[state.current_batch_index].instance_count == 0) {
  2516. return &state.canvas_instance_batches[state.current_batch_index];
  2517. }
  2518. r_batch_broken = true;
  2519. // Copy the properties of the current batch, we will manually update the things that changed.
  2520. Batch new_batch = state.canvas_instance_batches[state.current_batch_index];
  2521. new_batch.instance_count = 0;
  2522. new_batch.start = state.canvas_instance_batches[state.current_batch_index].start + state.canvas_instance_batches[state.current_batch_index].instance_count;
  2523. new_batch.instance_buffer_index = state.current_instance_buffer_index;
  2524. state.current_batch_index++;
  2525. state.canvas_instance_batches.push_back(new_batch);
  2526. return &state.canvas_instance_batches[state.current_batch_index];
  2527. }
  2528. void RendererCanvasRenderRD::_add_to_batch(uint32_t &r_index, bool &r_batch_broken, Batch *&r_current_batch) {
  2529. r_current_batch->instance_count++;
  2530. r_index++;
  2531. if (r_index + state.last_instance_index >= state.max_instances_per_buffer) {
  2532. // Copy over all data needed for rendering right away
  2533. // then go back to recording item commands.
  2534. RD::get_singleton()->buffer_update(
  2535. state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers[state.current_instance_buffer_index],
  2536. state.last_instance_index * sizeof(InstanceData),
  2537. r_index * sizeof(InstanceData),
  2538. state.instance_data_array);
  2539. _allocate_instance_buffer();
  2540. r_index = 0;
  2541. state.last_instance_index = 0;
  2542. r_batch_broken = false; // Force a new batch to be created
  2543. r_current_batch = _new_batch(r_batch_broken);
  2544. r_current_batch->start = 0;
  2545. }
  2546. }
  2547. void RendererCanvasRenderRD::_allocate_instance_buffer() {
  2548. state.current_instance_buffer_index++;
  2549. if (state.current_instance_buffer_index < state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers.size()) {
  2550. // We already allocated another buffer in a previous frame, so we can just use it.
  2551. return;
  2552. }
  2553. // Allocate a new buffer.
  2554. RID buf = RD::get_singleton()->storage_buffer_create(state.max_instance_buffer_size);
  2555. state.canvas_instance_data_buffers[state.current_data_buffer_index].instance_buffers.push_back(buf);
  2556. }
  2557. void RendererCanvasRenderRD::_prepare_batch_texture_info(RID p_texture, TextureState &p_state, TextureInfo *p_info) {
  2558. if (p_texture.is_null()) {
  2559. p_texture = default_canvas_texture;
  2560. }
  2561. RendererRD::TextureStorage::CanvasTextureInfo info =
  2562. RendererRD::TextureStorage::get_singleton()->canvas_texture_get_info(
  2563. p_texture,
  2564. p_state.texture_filter(),
  2565. p_state.texture_repeat(),
  2566. p_state.linear_colors(),
  2567. p_state.texture_is_data());
  2568. // something odd happened
  2569. if (info.is_null()) {
  2570. _prepare_batch_texture_info(default_canvas_texture, p_state, p_info);
  2571. return;
  2572. }
  2573. p_info->state = p_state;
  2574. p_info->diffuse = info.diffuse;
  2575. p_info->normal = info.normal;
  2576. p_info->specular = info.specular;
  2577. p_info->sampler = info.sampler;
  2578. // cache values to be copied to instance data
  2579. if (info.specular_color.a < 0.999) {
  2580. p_info->flags |= BATCH_FLAGS_DEFAULT_SPECULAR_MAP_USED;
  2581. }
  2582. if (info.use_normal) {
  2583. p_info->flags |= BATCH_FLAGS_DEFAULT_NORMAL_MAP_USED;
  2584. }
  2585. uint8_t a = uint8_t(CLAMP(info.specular_color.a * 255.0, 0.0, 255.0));
  2586. uint8_t b = uint8_t(CLAMP(info.specular_color.b * 255.0, 0.0, 255.0));
  2587. uint8_t g = uint8_t(CLAMP(info.specular_color.g * 255.0, 0.0, 255.0));
  2588. uint8_t r = uint8_t(CLAMP(info.specular_color.r * 255.0, 0.0, 255.0));
  2589. p_info->specular_shininess = uint32_t(a) << 24 | uint32_t(b) << 16 | uint32_t(g) << 8 | uint32_t(r);
  2590. p_info->texpixel_size = Vector2(1.0 / float(info.size.width), 1.0 / float(info.size.height));
  2591. }
  2592. RendererCanvasRenderRD::~RendererCanvasRenderRD() {
  2593. RendererRD::MaterialStorage *material_storage = RendererRD::MaterialStorage::get_singleton();
  2594. //canvas state
  2595. material_storage->material_free(default_canvas_group_material);
  2596. material_storage->shader_free(default_canvas_group_shader);
  2597. material_storage->material_free(default_clip_children_material);
  2598. material_storage->shader_free(default_clip_children_shader);
  2599. {
  2600. if (state.canvas_state_buffer.is_valid()) {
  2601. RD::get_singleton()->free(state.canvas_state_buffer);
  2602. }
  2603. memdelete_arr(state.light_uniforms);
  2604. RD::get_singleton()->free(state.lights_uniform_buffer);
  2605. }
  2606. //shadow rendering
  2607. {
  2608. shadow_render.shader.version_free(shadow_render.shader_version);
  2609. //this will also automatically clear all pipelines
  2610. RD::get_singleton()->free(state.shadow_sampler);
  2611. }
  2612. //buffers
  2613. {
  2614. RD::get_singleton()->free(shader.quad_index_array);
  2615. RD::get_singleton()->free(shader.quad_index_buffer);
  2616. //primitives are erase by dependency
  2617. }
  2618. if (state.shadow_fb.is_valid()) {
  2619. RD::get_singleton()->free(state.shadow_depth_texture);
  2620. }
  2621. RD::get_singleton()->free(state.shadow_texture);
  2622. memdelete_arr(state.instance_data_array);
  2623. for (uint32_t i = 0; i < BATCH_DATA_BUFFER_COUNT; i++) {
  2624. for (uint32_t j = 0; j < state.canvas_instance_data_buffers[i].instance_buffers.size(); j++) {
  2625. RD::get_singleton()->free(state.canvas_instance_data_buffers[i].instance_buffers[j]);
  2626. }
  2627. }
  2628. RendererRD::TextureStorage::get_singleton()->canvas_texture_free(default_canvas_texture);
  2629. //pipelines don't need freeing, they are all gone after shaders are gone
  2630. memdelete(shader.default_version_data);
  2631. }