DecoratorGradient.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "DecoratorGradient.h"
  29. #include "../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../Include/RmlUi/Core/Element.h"
  31. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  32. #include "../../Include/RmlUi/Core/Geometry.h"
  33. #include "../../Include/RmlUi/Core/GeometryUtilities.h"
  34. #include "../../Include/RmlUi/Core/Math.h"
  35. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  36. #include "ComputeProperty.h"
  37. #include "Pool.h"
  38. namespace Rml {
  39. struct GradientElementData {
  40. GradientElementData(Geometry&& geometry, CompiledShaderHandle shader) : geometry(std::move(geometry)), shader(shader) {}
  41. Geometry geometry;
  42. CompiledShaderHandle shader;
  43. };
  44. Pool<GradientElementData>& GetGradientElementDataPool()
  45. {
  46. static Pool<GradientElementData> gradient_element_data_pool(20, true);
  47. return gradient_element_data_pool;
  48. }
  49. // Returns the point along the input line ('line_point', 'line_vector') closest to the input 'point'.
  50. static Vector2f IntersectionPointToLineNormal(const Vector2f point, const Vector2f line_point, const Vector2f line_vector)
  51. {
  52. const Vector2f delta = line_point - point;
  53. return line_point - delta.DotProduct(line_vector) * line_vector;
  54. }
  55. /// Convert all color stop positions to normalized numbers.
  56. /// @param[in] element The element to resolve lengths against.
  57. /// @param[in] gradient_line_length The length of the gradient line, along which color stops are placed.
  58. /// @param[in] soft_spacing The desired minimum distance between stops to avoid aliasing, in normalized number units.
  59. /// @param[in] unresolved_stops
  60. /// @return A list of resolved color stops, all in number units.
  61. static ColorStopList ResolveColorStops(Element* element, const float gradient_line_length, const float soft_spacing,
  62. const ColorStopList& unresolved_stops)
  63. {
  64. ColorStopList stops = unresolved_stops;
  65. const int num_stops = (int)stops.size();
  66. // Resolve all lengths, percentages, and angles to numbers. After this step all stops with a unit other than Number are considered as Auto.
  67. for (ColorStop& stop : stops)
  68. {
  69. if (Any(stop.position.unit & Unit::LENGTH))
  70. {
  71. const float resolved_position = element->ResolveLength(stop.position);
  72. stop.position = NumericValue(resolved_position / gradient_line_length, Unit::NUMBER);
  73. }
  74. else if (stop.position.unit == Unit::PERCENT)
  75. {
  76. stop.position = NumericValue(stop.position.number * 0.01f, Unit::NUMBER);
  77. }
  78. else if (Any(stop.position.unit & Unit::ANGLE))
  79. {
  80. stop.position = NumericValue(ComputeAngle(stop.position) * (1.f / (2.f * Math::RMLUI_PI)), Unit::NUMBER);
  81. }
  82. }
  83. // Resolve auto positions of the first and last color stops.
  84. auto resolve_edge_stop = [](ColorStop& stop, float auto_to_number) {
  85. if (stop.position.unit != Unit::NUMBER)
  86. stop.position = NumericValue(auto_to_number, Unit::NUMBER);
  87. };
  88. resolve_edge_stop(stops[0], 0.f);
  89. resolve_edge_stop(stops[num_stops - 1], 1.f);
  90. // Ensures that color stop positions are strictly increasing, and have at least 1px spacing to avoid aliasing.
  91. auto nudge_stop = [prev_position = stops[0].position.number](ColorStop& stop, bool update_prev = true) mutable {
  92. stop.position.number = Math::Max(stop.position.number, prev_position);
  93. if (update_prev)
  94. prev_position = stop.position.number;
  95. };
  96. int auto_begin_i = -1;
  97. // Evenly space stops with sequential auto indices, and nudge stop positions to ensure strictly increasing positions.
  98. for (int i = 1; i < num_stops; i++)
  99. {
  100. ColorStop& stop = stops[i];
  101. if (stop.position.unit != Unit::NUMBER)
  102. {
  103. // Mark the first of any consecutive auto stops.
  104. if (auto_begin_i < 0)
  105. auto_begin_i = i;
  106. }
  107. else if (auto_begin_i < 0)
  108. {
  109. // The stop has a definite position and there are no previous autos to handle, just ensure it is properly spaced.
  110. nudge_stop(stop);
  111. }
  112. else
  113. {
  114. // Space out all the previous auto stops, indices [auto_begin_i, i).
  115. nudge_stop(stop, false);
  116. const int num_auto_stops = i - auto_begin_i;
  117. const float t0 = stops[auto_begin_i - 1].position.number;
  118. const float t1 = stop.position.number;
  119. for (int j = 0; j < num_auto_stops; j++)
  120. {
  121. const float fraction_along_t0_t1 = float(j + 1) / float(num_auto_stops + 1);
  122. stops[j + auto_begin_i].position = NumericValue(t0 + (t1 - t0) * fraction_along_t0_t1, Unit::NUMBER);
  123. nudge_stop(stops[j + auto_begin_i]);
  124. }
  125. nudge_stop(stop);
  126. auto_begin_i = -1;
  127. }
  128. }
  129. // Ensures that stops are placed some minimum distance from each other to avoid aliasing, if possible.
  130. for (int i = 1; i < num_stops - 1; i++)
  131. {
  132. const float p0 = stops[i - 1].position.number;
  133. const float p1 = stops[i].position.number;
  134. const float p2 = stops[i + 1].position.number;
  135. float& new_position = stops[i].position.number;
  136. if (p1 - p0 < soft_spacing)
  137. {
  138. if (p2 - p0 < 2.f * soft_spacing)
  139. new_position = 0.5f * (p2 + p0);
  140. else
  141. new_position = p0 + soft_spacing;
  142. }
  143. }
  144. RMLUI_ASSERT(std::all_of(stops.begin(), stops.end(), [](auto&& stop) { return stop.position.unit == Unit::NUMBER; }));
  145. return stops;
  146. }
  147. // Compute a 2d-position property value into a percentage-length vector.
  148. static Vector2Numeric ComputePosition(const Property* p_position[2])
  149. {
  150. Vector2Numeric position;
  151. for (int dimension = 0; dimension < 2; dimension++)
  152. {
  153. NumericValue& value = position[dimension];
  154. const Property& property = *p_position[dimension];
  155. if (property.unit == Unit::KEYWORD)
  156. {
  157. enum { TOP_LEFT, CENTER, BOTTOM_RIGHT };
  158. switch (property.Get<int>())
  159. {
  160. case TOP_LEFT: value = NumericValue(0.f, Unit::PERCENT); break;
  161. case CENTER: value = NumericValue(50.f, Unit::PERCENT); break;
  162. case BOTTOM_RIGHT: value = NumericValue(100.f, Unit::PERCENT); break;
  163. }
  164. }
  165. else
  166. {
  167. value = property.GetNumericValue();
  168. }
  169. }
  170. return position;
  171. }
  172. DecoratorStraightGradient::DecoratorStraightGradient() {}
  173. DecoratorStraightGradient::~DecoratorStraightGradient() {}
  174. bool DecoratorStraightGradient::Initialise(const Direction in_direction, const Colourb in_start, const Colourb in_stop)
  175. {
  176. direction = in_direction;
  177. start = in_start;
  178. stop = in_stop;
  179. return true;
  180. }
  181. DecoratorDataHandle DecoratorStraightGradient::GenerateElementData(Element* element, BoxArea paint_area) const
  182. {
  183. Geometry* geometry = new Geometry();
  184. const Box& box = element->GetBox();
  185. const ComputedValues& computed = element->GetComputedValues();
  186. const float opacity = computed.opacity();
  187. GeometryUtilities::GenerateBackground(geometry, element->GetBox(), Vector2f(0), computed.border_radius(), Colourb(), paint_area);
  188. // Apply opacity
  189. Colourb colour_start = start;
  190. colour_start.alpha = (byte)(opacity * (float)colour_start.alpha);
  191. Colourb colour_stop = stop;
  192. colour_stop.alpha = (byte)(opacity * (float)colour_stop.alpha);
  193. const Vector2f offset = box.GetPosition(paint_area);
  194. const Vector2f size = box.GetSize(paint_area);
  195. Vector<Vertex>& vertices = geometry->GetVertices();
  196. if (direction == Direction::Horizontal)
  197. {
  198. for (int i = 0; i < (int)vertices.size(); i++)
  199. {
  200. const float t = Math::Clamp((vertices[i].position.x - offset.x) / size.x, 0.0f, 1.0f);
  201. vertices[i].colour = Math::RoundedLerp(t, colour_start, colour_stop);
  202. }
  203. }
  204. else if (direction == Direction::Vertical)
  205. {
  206. for (int i = 0; i < (int)vertices.size(); i++)
  207. {
  208. const float t = Math::Clamp((vertices[i].position.y - offset.y) / size.y, 0.0f, 1.0f);
  209. vertices[i].colour = Math::RoundedLerp(t, colour_start, colour_stop);
  210. }
  211. }
  212. return reinterpret_cast<DecoratorDataHandle>(geometry);
  213. }
  214. void DecoratorStraightGradient::ReleaseElementData(DecoratorDataHandle element_data) const
  215. {
  216. delete reinterpret_cast<Geometry*>(element_data);
  217. }
  218. void DecoratorStraightGradient::RenderElement(Element* element, DecoratorDataHandle element_data) const
  219. {
  220. auto* data = reinterpret_cast<Geometry*>(element_data);
  221. data->Render(element->GetAbsoluteOffset(BoxArea::Border));
  222. }
  223. DecoratorStraightGradientInstancer::DecoratorStraightGradientInstancer()
  224. {
  225. ids.direction = RegisterProperty("direction", "horizontal").AddParser("keyword", "horizontal, vertical").GetId();
  226. ids.start = RegisterProperty("start-color", "#ffffff").AddParser("color").GetId();
  227. ids.stop = RegisterProperty("stop-color", "#ffffff").AddParser("color").GetId();
  228. RegisterShorthand("decorator", "direction, start-color, stop-color", ShorthandType::FallThrough);
  229. }
  230. DecoratorStraightGradientInstancer::~DecoratorStraightGradientInstancer() {}
  231. SharedPtr<Decorator> DecoratorStraightGradientInstancer::InstanceDecorator(const String& name, const PropertyDictionary& properties_,
  232. const DecoratorInstancerInterface& /*interface_*/)
  233. {
  234. using Direction = DecoratorStraightGradient::Direction;
  235. Direction direction;
  236. if (name == "horizontal-gradient")
  237. direction = Direction::Horizontal;
  238. else if (name == "vertical-gradient")
  239. direction = Direction::Vertical;
  240. else
  241. {
  242. direction = (Direction)properties_.GetProperty(ids.direction)->Get<int>();
  243. Log::Message(Log::LT_WARNING,
  244. "Decorator syntax 'gradient(horizontal|vertical ...)' is deprecated, please replace with 'horizontal-gradient(...)' or "
  245. "'vertical-gradient(...)'");
  246. }
  247. Colourb start = properties_.GetProperty(ids.start)->Get<Colourb>();
  248. Colourb stop = properties_.GetProperty(ids.stop)->Get<Colourb>();
  249. auto decorator = MakeShared<DecoratorStraightGradient>();
  250. if (decorator->Initialise(direction, start, stop))
  251. return decorator;
  252. return nullptr;
  253. }
  254. DecoratorLinearGradient::DecoratorLinearGradient() {}
  255. DecoratorLinearGradient::~DecoratorLinearGradient() {}
  256. bool DecoratorLinearGradient::Initialise(bool in_repeating, Corner in_corner, float in_angle, const ColorStopList& in_color_stops)
  257. {
  258. repeating = in_repeating;
  259. corner = in_corner;
  260. angle = in_angle;
  261. color_stops = in_color_stops;
  262. return !color_stops.empty();
  263. }
  264. DecoratorDataHandle DecoratorLinearGradient::GenerateElementData(Element* element, BoxArea paint_area) const
  265. {
  266. RenderInterface* render_interface = GetRenderInterface();
  267. if (!render_interface)
  268. return INVALID_DECORATORDATAHANDLE;
  269. RMLUI_ASSERT(!color_stops.empty());
  270. const Box& box = element->GetBox();
  271. const Vector2f dimensions = box.GetSize(paint_area);
  272. LinearGradientShape gradient_shape = CalculateShape(dimensions);
  273. // One-pixel minimum color stop spacing to avoid aliasing.
  274. const float soft_spacing = 1.f / gradient_shape.length;
  275. ColorStopList resolved_stops = ResolveColorStops(element, gradient_shape.length, soft_spacing, color_stops);
  276. CompiledShaderHandle shader_handle = render_interface->CompileShader("linear-gradient",
  277. Dictionary{
  278. {"angle", Variant(angle)},
  279. {"p0", Variant(gradient_shape.p0)},
  280. {"p1", Variant(gradient_shape.p1)},
  281. {"length", Variant(gradient_shape.length)},
  282. {"repeating", Variant(repeating)},
  283. {"color_stop_list", Variant(std::move(resolved_stops))},
  284. });
  285. if (!shader_handle)
  286. return INVALID_DECORATORDATAHANDLE;
  287. Geometry geometry;
  288. const ComputedValues& computed = element->GetComputedValues();
  289. const byte alpha = byte(computed.opacity() * 255.f);
  290. GeometryUtilities::GenerateBackground(&geometry, box, Vector2f(), computed.border_radius(), Colourb(255, alpha), paint_area);
  291. const Vector2f render_offset = box.GetPosition(paint_area);
  292. for (Vertex& vertex : geometry.GetVertices())
  293. vertex.tex_coord = vertex.position - render_offset;
  294. GradientElementData* element_data = GetGradientElementDataPool().AllocateAndConstruct(std::move(geometry), shader_handle);
  295. return reinterpret_cast<DecoratorDataHandle>(element_data);
  296. }
  297. void DecoratorLinearGradient::ReleaseElementData(DecoratorDataHandle handle) const
  298. {
  299. GradientElementData* element_data = reinterpret_cast<GradientElementData*>(handle);
  300. GetRenderInterface()->ReleaseCompiledShader(element_data->shader);
  301. GetGradientElementDataPool().DestroyAndDeallocate(element_data);
  302. }
  303. void DecoratorLinearGradient::RenderElement(Element* element, DecoratorDataHandle handle) const
  304. {
  305. GradientElementData* element_data = reinterpret_cast<GradientElementData*>(handle);
  306. element_data->geometry.RenderWithShader(element_data->shader, element->GetAbsoluteOffset(BoxArea::Border));
  307. }
  308. DecoratorLinearGradient::LinearGradientShape DecoratorLinearGradient::CalculateShape(Vector2f dim) const
  309. {
  310. using uint = unsigned int;
  311. const Vector2f corners[(int)Corner::Count] = {Vector2f(dim.x, 0), dim, Vector2f(0, dim.y), Vector2f(0, 0)};
  312. const Vector2f center = 0.5f * dim;
  313. uint quadrant = 0;
  314. Vector2f line_vector;
  315. if (corner == Corner::None)
  316. {
  317. // Find the target quadrant and unit vector for the given angle.
  318. quadrant = uint(Math::NormaliseAngle(angle) * (4.f / (2.f * Math::RMLUI_PI))) % 4u;
  319. line_vector = Vector2f(Math::Sin(angle), -Math::Cos(angle));
  320. }
  321. else
  322. {
  323. // Quadrant given by the corner, need to find the vector perpendicular to the line connecting the neighboring corners.
  324. quadrant = uint(corner);
  325. const Vector2f v_neighbors = (corners[(quadrant + 1u) % 4u] - corners[(quadrant + 3u) % 4u]).Normalise();
  326. line_vector = {v_neighbors.y, -v_neighbors.x};
  327. }
  328. const uint quadrant_opposite = (quadrant + 2u) % 4u;
  329. const Vector2f starting_point = IntersectionPointToLineNormal(corners[quadrant_opposite], center, line_vector);
  330. const Vector2f ending_point = IntersectionPointToLineNormal(corners[quadrant], center, line_vector);
  331. const float length = Math::Absolute(dim.x * line_vector.x) + Math::Absolute(-dim.y * line_vector.y);
  332. return LinearGradientShape{starting_point, ending_point, length};
  333. }
  334. DecoratorLinearGradientInstancer::DecoratorLinearGradientInstancer()
  335. {
  336. ids.angle = RegisterProperty("angle", "180deg").AddParser("angle").GetId();
  337. ids.direction_to = RegisterProperty("to", "unspecified").AddParser("keyword", "unspecified, to").GetId();
  338. // See Direction enum for keyword values.
  339. ids.direction_x = RegisterProperty("direction-x", "unspecified").AddParser("keyword", "unspecified=0, left=8, right=2").GetId();
  340. ids.direction_y = RegisterProperty("direction-y", "unspecified").AddParser("keyword", "unspecified=0, top=1, bottom=4").GetId();
  341. ids.color_stop_list = RegisterProperty("color-stops", "").AddParser("color_stop_list").GetId();
  342. RegisterShorthand("direction", "angle, to, direction-x, direction-y, direction-x", ShorthandType::FallThrough);
  343. RegisterShorthand("decorator", "direction?, color-stops#", ShorthandType::RecursiveCommaSeparated);
  344. }
  345. DecoratorLinearGradientInstancer::~DecoratorLinearGradientInstancer() {}
  346. SharedPtr<Decorator> DecoratorLinearGradientInstancer::InstanceDecorator(const String& name, const PropertyDictionary& properties_,
  347. const DecoratorInstancerInterface& /*interface_*/)
  348. {
  349. const Property* p_angle = properties_.GetProperty(ids.angle);
  350. const Property* p_direction_to = properties_.GetProperty(ids.direction_to);
  351. const Property* p_direction_x = properties_.GetProperty(ids.direction_x);
  352. const Property* p_direction_y = properties_.GetProperty(ids.direction_y);
  353. const Property* p_color_stop_list = properties_.GetProperty(ids.color_stop_list);
  354. if (!p_angle || !p_direction_to || !p_direction_x || !p_direction_y || !p_color_stop_list)
  355. return nullptr;
  356. using Corner = DecoratorLinearGradient::Corner;
  357. Corner corner = Corner::None;
  358. float angle = 0.f;
  359. if (p_direction_to->Get<bool>())
  360. {
  361. const Direction direction = (Direction)(p_direction_x->Get<int>() | p_direction_y->Get<int>());
  362. switch (direction)
  363. {
  364. case Direction::Top: angle = 0.f; break;
  365. case Direction::Right: angle = 0.5f * Math::RMLUI_PI; break;
  366. case Direction::Bottom: angle = Math::RMLUI_PI; break;
  367. case Direction::Left: angle = 1.5f * Math::RMLUI_PI; break;
  368. case Direction::TopLeft: corner = Corner::TopLeft; break;
  369. case Direction::TopRight: corner = Corner::TopRight; break;
  370. case Direction::BottomRight: corner = Corner::BottomRight; break;
  371. case Direction::BottomLeft: corner = Corner::BottomLeft; break;
  372. case Direction::None:
  373. default: return nullptr; break;
  374. }
  375. }
  376. else
  377. {
  378. angle = ComputeAngle(p_angle->GetNumericValue());
  379. }
  380. if (p_color_stop_list->unit != Unit::COLORSTOPLIST)
  381. return nullptr;
  382. const ColorStopList& color_stop_list = p_color_stop_list->value.GetReference<ColorStopList>();
  383. const bool repeating = (name == "repeating-linear-gradient");
  384. auto decorator = MakeShared<DecoratorLinearGradient>();
  385. if (decorator->Initialise(repeating, corner, angle, color_stop_list))
  386. return decorator;
  387. return nullptr;
  388. }
  389. DecoratorRadialGradient::DecoratorRadialGradient() {}
  390. DecoratorRadialGradient::~DecoratorRadialGradient() {}
  391. bool DecoratorRadialGradient::Initialise(bool in_repeating, Shape in_shape, SizeType in_size_type, Vector2Numeric in_size, Vector2Numeric in_position,
  392. const ColorStopList& in_color_stops)
  393. {
  394. repeating = in_repeating;
  395. shape = in_shape;
  396. size_type = in_size_type;
  397. size = in_size;
  398. position = in_position;
  399. color_stops = in_color_stops;
  400. return !color_stops.empty();
  401. }
  402. DecoratorDataHandle DecoratorRadialGradient::GenerateElementData(Element* element, BoxArea box_area) const
  403. {
  404. RenderInterface* render_interface = GetRenderInterface();
  405. if (!render_interface)
  406. return INVALID_DECORATORDATAHANDLE;
  407. RMLUI_ASSERT(!color_stops.empty() && (shape == Shape::Circle || shape == Shape::Ellipse));
  408. const Box& box = element->GetBox();
  409. const Vector2f dimensions = box.GetSize(box_area);
  410. RadialGradientShape gradient_shape = CalculateRadialGradientShape(element, dimensions);
  411. // One-pixel minimum color stop spacing to avoid aliasing.
  412. const float soft_spacing = 1.f / Math::Min(gradient_shape.radius.x, gradient_shape.radius.y);
  413. ColorStopList resolved_stops = ResolveColorStops(element, gradient_shape.radius.x, soft_spacing, color_stops);
  414. CompiledShaderHandle shader_handle = render_interface->CompileShader("radial-gradient",
  415. Dictionary{
  416. {"center", Variant(gradient_shape.center)},
  417. {"radius", Variant(gradient_shape.radius)},
  418. {"repeating", Variant(repeating)},
  419. {"color_stop_list", Variant(std::move(resolved_stops))},
  420. });
  421. Geometry geometry;
  422. const ComputedValues& computed = element->GetComputedValues();
  423. const byte alpha = byte(computed.opacity() * 255.f);
  424. GeometryUtilities::GenerateBackground(&geometry, box, Vector2f(), computed.border_radius(), Colourb(255, alpha), box_area);
  425. const Vector2f render_offset = box.GetPosition(box_area);
  426. for (Vertex& vertex : geometry.GetVertices())
  427. vertex.tex_coord = vertex.position - render_offset;
  428. GradientElementData* element_data = GetGradientElementDataPool().AllocateAndConstruct(std::move(geometry), shader_handle);
  429. return reinterpret_cast<DecoratorDataHandle>(element_data);
  430. }
  431. void DecoratorRadialGradient::ReleaseElementData(DecoratorDataHandle handle) const
  432. {
  433. GradientElementData* element_data = reinterpret_cast<GradientElementData*>(handle);
  434. GetRenderInterface()->ReleaseCompiledShader(element_data->shader);
  435. GetGradientElementDataPool().DestroyAndDeallocate(element_data);
  436. }
  437. void DecoratorRadialGradient::RenderElement(Element* element, DecoratorDataHandle handle) const
  438. {
  439. GradientElementData* element_data = reinterpret_cast<GradientElementData*>(handle);
  440. element_data->geometry.RenderWithShader(element_data->shader, element->GetAbsoluteOffset(BoxArea::Border));
  441. }
  442. DecoratorRadialGradient::RadialGradientShape DecoratorRadialGradient::CalculateRadialGradientShape(Element* element, Vector2f dimensions) const
  443. {
  444. RadialGradientShape result;
  445. result.center.x = element->ResolveNumericValue(position.x, dimensions.x);
  446. result.center.y = element->ResolveNumericValue(position.y, dimensions.y);
  447. const bool is_circle = (shape == Shape::Circle);
  448. auto Abs = [](Vector2f v) { return Vector2f{Math::Absolute(v.x), Math::Absolute(v.y)}; };
  449. auto d = dimensions;
  450. auto c = result.center;
  451. Vector2f r;
  452. switch (size_type)
  453. {
  454. case SizeType::ClosestSide:
  455. {
  456. r = Abs(Math::Min(c, d - c));
  457. result.radius = (is_circle ? Vector2f(Math::Min(r.x, r.y)) : r);
  458. }
  459. break;
  460. case SizeType::FarthestSide:
  461. {
  462. r = Abs(Math::Max(c, d - c));
  463. result.radius = (is_circle ? Vector2f(Math::Max(r.x, r.y)) : r);
  464. }
  465. break;
  466. case SizeType::ClosestCorner:
  467. case SizeType::FarthestCorner:
  468. {
  469. if (size_type == SizeType::ClosestCorner)
  470. r = Abs(Math::Min(c, d - c)); // Same as closest-side.
  471. else
  472. r = Abs(Math::Max(c, d - c)); // Same as farthest-side.
  473. if (is_circle)
  474. {
  475. result.radius = Vector2f(r.Magnitude());
  476. }
  477. else
  478. {
  479. r = Math::Max(r, Vector2f(1)); // In case r.x ~= 0
  480. result.radius.x = Math::SquareRoot(2.f * r.x * r.x);
  481. result.radius.y = result.radius.x * (r.y / r.x);
  482. }
  483. }
  484. break;
  485. case SizeType::LengthPercentage:
  486. {
  487. result.radius.x = element->ResolveNumericValue(size.x, d.x);
  488. result.radius.y = (is_circle ? result.radius.x : element->ResolveNumericValue(size.y, d.y));
  489. result.radius = Abs(result.radius);
  490. }
  491. break;
  492. }
  493. result.radius = Math::Max(result.radius, Vector2f(1.f));
  494. return result;
  495. }
  496. DecoratorRadialGradientInstancer::DecoratorRadialGradientInstancer()
  497. {
  498. ids.ending_shape = RegisterProperty("ending-shape", "unspecified").AddParser("keyword", "circle, ellipse, unspecified").GetId();
  499. ids.size_x = RegisterProperty("size-x", "farthest-corner")
  500. .AddParser("keyword", "closest-side, farthest-side, closest-corner, farthest-corner")
  501. .AddParser("length_percent")
  502. .GetId();
  503. ids.size_y = RegisterProperty("size-y", "unspecified").AddParser("keyword", "unspecified").AddParser("length_percent").GetId();
  504. RegisterProperty("at", "unspecified").AddParser("keyword", "at, unspecified");
  505. ids.position_x = RegisterProperty("position-x", "center").AddParser("keyword", "left, center, right").AddParser("length_percent").GetId();
  506. ids.position_y = RegisterProperty("position-y", "center").AddParser("keyword", "top, center, bottom").AddParser("length_percent").GetId();
  507. ids.color_stop_list = RegisterProperty("color-stops", "").AddParser("color_stop_list").GetId();
  508. RegisterShorthand("shape", "ending-shape, size-x, size-y, at, position-x, position-y, position-x", ShorthandType::FallThrough);
  509. RegisterShorthand("decorator", "shape?, color-stops#", ShorthandType::RecursiveCommaSeparated);
  510. }
  511. DecoratorRadialGradientInstancer::~DecoratorRadialGradientInstancer() {}
  512. SharedPtr<Decorator> DecoratorRadialGradientInstancer::InstanceDecorator(const String& name, const PropertyDictionary& properties_,
  513. const DecoratorInstancerInterface& /*interface_*/)
  514. {
  515. const Property* p_ending_shape = properties_.GetProperty(ids.ending_shape);
  516. const Property* p_size_x = properties_.GetProperty(ids.size_x);
  517. const Property* p_size_y = properties_.GetProperty(ids.size_y);
  518. const Property* p_position[2] = {properties_.GetProperty(ids.position_x), properties_.GetProperty(ids.position_y)};
  519. const Property* p_color_stop_list = properties_.GetProperty(ids.color_stop_list);
  520. if (!p_ending_shape || !p_size_x || !p_size_y || !p_position[0] || !p_position[1] || !p_color_stop_list)
  521. return nullptr;
  522. using SizeType = DecoratorRadialGradient::SizeType;
  523. using Shape = DecoratorRadialGradient::Shape;
  524. Shape shape = (Shape)p_ending_shape->Get<int>();
  525. if (shape == Shape::Unspecified)
  526. {
  527. const bool circle_sized = (Any(p_size_x->unit & Unit::LENGTH_PERCENT) && p_size_y->unit == Unit::KEYWORD);
  528. shape = (circle_sized ? Shape::Circle : Shape::Ellipse);
  529. }
  530. if (shape == Shape::Circle && (p_size_x->unit == Unit::PERCENT || p_size_y->unit != Unit::KEYWORD))
  531. return nullptr;
  532. SizeType size_type = {};
  533. Vector2Numeric size;
  534. if (p_size_x->unit == Unit::KEYWORD)
  535. {
  536. size_type = (SizeType)p_size_x->Get<int>();
  537. }
  538. else
  539. {
  540. size_type = SizeType::LengthPercentage;
  541. size.x = p_size_x->GetNumericValue();
  542. size.y = (p_size_y->unit == Unit::KEYWORD ? size.x : p_size_y->GetNumericValue());
  543. }
  544. const Vector2Numeric position = ComputePosition(p_position);
  545. const bool repeating = (name == "repeating-radial-gradient");
  546. if (p_color_stop_list->unit != Unit::COLORSTOPLIST)
  547. return nullptr;
  548. const ColorStopList& color_stop_list = p_color_stop_list->value.GetReference<ColorStopList>();
  549. auto decorator = MakeShared<DecoratorRadialGradient>();
  550. if (decorator->Initialise(repeating, shape, size_type, size, position, color_stop_list))
  551. return decorator;
  552. return nullptr;
  553. }
  554. DecoratorConicGradient::DecoratorConicGradient() {}
  555. DecoratorConicGradient::~DecoratorConicGradient() {}
  556. bool DecoratorConicGradient::Initialise(bool in_repeating, float in_angle, Vector2Numeric in_position, const ColorStopList& in_color_stops)
  557. {
  558. repeating = in_repeating;
  559. angle = in_angle;
  560. position = in_position;
  561. color_stops = in_color_stops;
  562. return !color_stops.empty();
  563. }
  564. DecoratorDataHandle DecoratorConicGradient::GenerateElementData(Element* element, BoxArea box_area) const
  565. {
  566. RenderInterface* render_interface = GetRenderInterface();
  567. if (!render_interface)
  568. return INVALID_DECORATORDATAHANDLE;
  569. RMLUI_ASSERT(!color_stops.empty());
  570. const Box& box = element->GetBox();
  571. const Vector2f dimensions = box.GetSize(box_area);
  572. const Vector2f center =
  573. Vector2f{element->ResolveNumericValue(position.x, dimensions.x), element->ResolveNumericValue(position.y, dimensions.y)}.Round();
  574. ColorStopList resolved_stops = ResolveColorStops(element, 1.f, 0.f, color_stops);
  575. CompiledShaderHandle shader_handle = render_interface->CompileShader("conic-gradient",
  576. Dictionary{
  577. {"angle", Variant(angle)},
  578. {"center", Variant(center)},
  579. {"repeating", Variant(repeating)},
  580. {"color_stop_list", Variant(std::move(resolved_stops))},
  581. });
  582. Geometry geometry;
  583. const ComputedValues& computed = element->GetComputedValues();
  584. const byte alpha = byte(computed.opacity() * 255.f);
  585. GeometryUtilities::GenerateBackground(&geometry, box, Vector2f(), computed.border_radius(), Colourb(255, alpha), box_area);
  586. const Vector2f render_offset = box.GetPosition(box_area);
  587. for (Vertex& vertex : geometry.GetVertices())
  588. vertex.tex_coord = vertex.position - render_offset;
  589. GradientElementData* element_data = GetGradientElementDataPool().AllocateAndConstruct(std::move(geometry), shader_handle);
  590. return reinterpret_cast<DecoratorDataHandle>(element_data);
  591. }
  592. void DecoratorConicGradient::ReleaseElementData(DecoratorDataHandle handle) const
  593. {
  594. GradientElementData* element_data = reinterpret_cast<GradientElementData*>(handle);
  595. GetRenderInterface()->ReleaseCompiledShader(element_data->shader);
  596. GetGradientElementDataPool().DestroyAndDeallocate(element_data);
  597. }
  598. void DecoratorConicGradient::RenderElement(Element* element, DecoratorDataHandle handle) const
  599. {
  600. GradientElementData* element_data = reinterpret_cast<GradientElementData*>(handle);
  601. element_data->geometry.RenderWithShader(element_data->shader, element->GetAbsoluteOffset(BoxArea::Border));
  602. }
  603. DecoratorConicGradientInstancer::DecoratorConicGradientInstancer()
  604. {
  605. RegisterProperty("from", "from").AddParser("keyword", "from");
  606. ids.angle = RegisterProperty("angle", "0deg").AddParser("angle").GetId();
  607. RegisterProperty("at", "unspecified").AddParser("keyword", "at, unspecified");
  608. ids.position_x = RegisterProperty("position-x", "center").AddParser("keyword", "left, center, right").AddParser("length_percent").GetId();
  609. ids.position_y = RegisterProperty("position-y", "center").AddParser("keyword", "top, center, bottom").AddParser("length_percent").GetId();
  610. ids.color_stop_list = RegisterProperty("color-stops", "").AddParser("color_stop_list", "angle").GetId();
  611. RegisterShorthand("shape", "from, angle, at, position-x, position-y, position-x", ShorthandType::FallThrough);
  612. RegisterShorthand("decorator", "shape?, color-stops#", ShorthandType::RecursiveCommaSeparated);
  613. }
  614. DecoratorConicGradientInstancer::~DecoratorConicGradientInstancer() {}
  615. SharedPtr<Decorator> DecoratorConicGradientInstancer::InstanceDecorator(const String& name, const PropertyDictionary& properties_,
  616. const DecoratorInstancerInterface& /*interface_*/)
  617. {
  618. const Property* p_angle = properties_.GetProperty(ids.angle);
  619. const Property* p_position[2] = {properties_.GetProperty(ids.position_x), properties_.GetProperty(ids.position_y)};
  620. const Property* p_color_stop_list = properties_.GetProperty(ids.color_stop_list);
  621. if (!p_angle || !p_position[0] || !p_position[1] || !p_color_stop_list)
  622. return nullptr;
  623. const float angle = ComputeAngle(p_angle->GetNumericValue());
  624. const Vector2Numeric position = ComputePosition(p_position);
  625. const bool repeating = (name == "repeating-conic-gradient");
  626. if (p_color_stop_list->unit != Unit::COLORSTOPLIST)
  627. return nullptr;
  628. const ColorStopList& color_stop_list = p_color_stop_list->value.GetReference<ColorStopList>();
  629. auto decorator = MakeShared<DecoratorConicGradient>();
  630. if (decorator->Initialise(repeating, angle, position, color_stop_list))
  631. return decorator;
  632. return nullptr;
  633. }
  634. } // namespace Rml