DecoratorTiled.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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 "DecoratorTiled.h"
  29. #include "../../Include/RmlUi/Core/Element.h"
  30. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  31. #include "../../Include/RmlUi/Core/GeometryUtilities.h"
  32. #include "../../Include/RmlUi/Core/Math.h"
  33. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  34. #include "../../Include/RmlUi/Core/Spritesheet.h"
  35. #include <algorithm>
  36. namespace Rml {
  37. DecoratorTiled::DecoratorTiled() {}
  38. DecoratorTiled::~DecoratorTiled() {}
  39. static const Vector2f oriented_texcoords[4][2] = {
  40. {Vector2f(0, 0), Vector2f(1, 1)}, // ORIENTATION_NONE
  41. {Vector2f(1, 0), Vector2f(0, 1)}, // FLIP_HORIZONTAL
  42. {Vector2f(0, 1), Vector2f(1, 0)}, // FLIP_VERTICAL
  43. {Vector2f(1, 1), Vector2f(0, 0)} // ROTATE_180
  44. };
  45. DecoratorTiled::Tile::Tile() : display_scale(1), position(0, 0), size(0, 0)
  46. {
  47. texture_index = -1;
  48. fit_mode = FILL;
  49. orientation = ORIENTATION_NONE;
  50. }
  51. void DecoratorTiled::Tile::CalculateDimensions(const Texture& texture) const
  52. {
  53. if (!tile_data_calculated)
  54. {
  55. tile_data_calculated = true;
  56. tile_data = {};
  57. const Vector2f texture_dimensions(texture.GetDimensions());
  58. if (texture_dimensions.x == 0 || texture_dimensions.y == 0)
  59. {
  60. tile_data.size = Vector2f(0, 0);
  61. tile_data.texcoords[0] = Vector2f(0, 0);
  62. tile_data.texcoords[1] = Vector2f(0, 0);
  63. }
  64. else
  65. {
  66. // Need to scale the coordinates to normalized units and 'size' to absolute size (pixels)
  67. if (size.x == 0 && size.y == 0 && position.x == 0 && position.y == 0)
  68. tile_data.size = texture_dimensions;
  69. else
  70. tile_data.size = size;
  71. const Vector2f size_relative = tile_data.size / texture_dimensions;
  72. tile_data.size = Vector2f(Math::Absolute(tile_data.size.x), Math::Absolute(tile_data.size.y));
  73. tile_data.texcoords[0] = position / texture_dimensions;
  74. tile_data.texcoords[1] = size_relative + tile_data.texcoords[0];
  75. }
  76. }
  77. }
  78. Vector2f DecoratorTiled::Tile::GetNaturalDimensions(Element* element) const
  79. {
  80. if (!tile_data_calculated)
  81. return Vector2f(0, 0);
  82. const float scale_raw_to_natural_dimensions = ElementUtilities::GetDensityIndependentPixelRatio(element) * display_scale;
  83. const Vector2f raw_dimensions = tile_data.size;
  84. return raw_dimensions * scale_raw_to_natural_dimensions;
  85. }
  86. void DecoratorTiled::Tile::GenerateGeometry(Vector<Vertex>& vertices, Vector<int>& indices, const ComputedValues& computed,
  87. const Vector2f surface_origin, const Vector2f surface_dimensions, const Vector2f tile_dimensions) const
  88. {
  89. if (surface_dimensions.x <= 0 || surface_dimensions.y <= 0)
  90. return;
  91. float opacity = computed.opacity();
  92. Colourb quad_colour = computed.image_color();
  93. // Apply opacity
  94. quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha);
  95. if (!tile_data_calculated)
  96. return;
  97. // Generate the oriented texture coordinates for the tiles.
  98. Vector2f scaled_texcoords[2];
  99. for (int i = 0; i < 2; i++)
  100. {
  101. scaled_texcoords[i] = tile_data.texcoords[0] + oriented_texcoords[orientation][i] * (tile_data.texcoords[1] - tile_data.texcoords[0]);
  102. }
  103. Vector2f final_tile_dimensions;
  104. bool offset_and_clip_tile = false;
  105. switch (fit_mode)
  106. {
  107. case FILL:
  108. {
  109. final_tile_dimensions = surface_dimensions;
  110. }
  111. break;
  112. case CONTAIN:
  113. {
  114. Vector2f scale_factor = surface_dimensions / tile_dimensions;
  115. float min_factor = std::min(scale_factor.x, scale_factor.y);
  116. final_tile_dimensions = tile_dimensions * min_factor;
  117. offset_and_clip_tile = true;
  118. }
  119. break;
  120. case COVER:
  121. {
  122. Vector2f scale_factor = surface_dimensions / tile_dimensions;
  123. float max_factor = std::max(scale_factor.x, scale_factor.y);
  124. final_tile_dimensions = tile_dimensions * max_factor;
  125. offset_and_clip_tile = true;
  126. }
  127. break;
  128. case SCALE_NONE:
  129. {
  130. final_tile_dimensions = tile_dimensions;
  131. offset_and_clip_tile = true;
  132. }
  133. break;
  134. case SCALE_DOWN:
  135. {
  136. Vector2f scale_factor = surface_dimensions / tile_dimensions;
  137. float min_factor = std::min(scale_factor.x, scale_factor.y);
  138. if (min_factor < 1.0f)
  139. final_tile_dimensions = tile_dimensions * min_factor;
  140. else
  141. final_tile_dimensions = tile_dimensions;
  142. offset_and_clip_tile = true;
  143. }
  144. break;
  145. }
  146. Vector2f tile_offset(0, 0);
  147. if (offset_and_clip_tile)
  148. {
  149. // Offset tile along each dimension.
  150. for (int i = 0; i < 2; i++)
  151. {
  152. switch (align[i].type)
  153. {
  154. case Style::LengthPercentage::Length: tile_offset[i] = align[i].value; break;
  155. case Style::LengthPercentage::Percentage:
  156. tile_offset[i] = (surface_dimensions[i] - final_tile_dimensions[i]) * align[i].value * 0.01f;
  157. break;
  158. }
  159. }
  160. tile_offset = tile_offset.Round();
  161. // Clip tile. See if our tile extends outside the boundary at either side, along each dimension.
  162. for (int i = 0; i < 2; i++)
  163. {
  164. // Left/right acts as top/bottom during the second iteration.
  165. float overshoot_left = std::max(-tile_offset[i], 0.0f);
  166. float overshoot_right = std::max(tile_offset[i] + final_tile_dimensions[i] - surface_dimensions[i], 0.0f);
  167. if (overshoot_left > 0.f || overshoot_right > 0.f)
  168. {
  169. float& left = scaled_texcoords[0][i];
  170. float& right = scaled_texcoords[1][i];
  171. float width = right - left;
  172. left += overshoot_left / final_tile_dimensions[i] * width;
  173. right -= overshoot_right / final_tile_dimensions[i] * width;
  174. final_tile_dimensions[i] -= overshoot_left + overshoot_right;
  175. tile_offset[i] += overshoot_left;
  176. }
  177. }
  178. }
  179. // Resize the vertex and index arrays to fit the new geometry.
  180. int index_offset = (int)vertices.size();
  181. vertices.resize(vertices.size() + 4);
  182. Vertex* new_vertices = &vertices[0] + index_offset;
  183. size_t num_indices = indices.size();
  184. indices.resize(indices.size() + 6);
  185. int* new_indices = &indices[0] + num_indices;
  186. // Generate the vertices for the tiled surface.
  187. Vector2f tile_position = (surface_origin + tile_offset);
  188. Math::SnapToPixelGrid(tile_position, final_tile_dimensions);
  189. GeometryUtilities::GenerateQuad(new_vertices, new_indices, tile_position, final_tile_dimensions, quad_colour, scaled_texcoords[0],
  190. scaled_texcoords[1], index_offset);
  191. }
  192. void DecoratorTiled::ScaleTileDimensions(Vector2f& tile_dimensions, float axis_value, Axis axis_enum) const
  193. {
  194. int axis = static_cast<int>(axis_enum);
  195. if (tile_dimensions[axis] != axis_value)
  196. {
  197. tile_dimensions[1 - axis] = tile_dimensions[1 - axis] * (axis_value / tile_dimensions[axis]);
  198. tile_dimensions[axis] = axis_value;
  199. }
  200. }
  201. DecoratorTiledInstancer::DecoratorTiledInstancer(size_t num_tiles)
  202. {
  203. tile_property_ids.reserve(num_tiles);
  204. }
  205. void DecoratorTiledInstancer::RegisterTileProperty(const String& name, bool register_fit_modes)
  206. {
  207. TilePropertyIds ids = {};
  208. ids.src = RegisterProperty(CreateString(32, "%s-src", name.c_str()), "").AddParser("string").GetId();
  209. String additional_modes;
  210. if (register_fit_modes)
  211. {
  212. String fit_name = CreateString(32, "%s-fit", name.c_str());
  213. ids.fit = RegisterProperty(fit_name, "fill").AddParser("keyword", "fill, contain, cover, scale-none, scale-down").GetId();
  214. String align_x_name = CreateString(32, "%s-align-x", name.c_str());
  215. ids.align_x = RegisterProperty(align_x_name, "center").AddParser("keyword", "left, center, right").AddParser("length_percent").GetId();
  216. String align_y_name = CreateString(32, "%s-align-y", name.c_str());
  217. ids.align_y = RegisterProperty(align_y_name, "center").AddParser("keyword", "top, center, bottom").AddParser("length_percent").GetId();
  218. additional_modes += ", " + fit_name + ", " + align_x_name + ", " + align_y_name;
  219. }
  220. ids.orientation = RegisterProperty(CreateString(32, "%s-orientation", name.c_str()), "none")
  221. .AddParser("keyword", "none, flip-horizontal, flip-vertical, rotate-180")
  222. .GetId();
  223. RegisterShorthand(name,
  224. CreateString(256, ("%s-src, %s-orientation" + additional_modes).c_str(), name.c_str(), name.c_str(), name.c_str(), name.c_str(), name.c_str(),
  225. name.c_str()),
  226. ShorthandType::FallThrough);
  227. tile_property_ids.push_back(ids);
  228. }
  229. bool DecoratorTiledInstancer::GetTileProperties(DecoratorTiled::Tile* tiles, Texture* textures, size_t num_tiles_and_textures,
  230. const PropertyDictionary& properties, const DecoratorInstancerInterface& instancer_interface) const
  231. {
  232. RMLUI_ASSERT(num_tiles_and_textures == tile_property_ids.size());
  233. String previous_texture_name;
  234. Texture previous_texture;
  235. for (size_t i = 0; i < num_tiles_and_textures; i++)
  236. {
  237. const TilePropertyIds& ids = tile_property_ids[i];
  238. const Property* src_property = properties.GetProperty(ids.src);
  239. const String texture_name = src_property->Get<String>();
  240. // Skip the tile if it has no source name.
  241. // Declaring the name 'auto' is the same as an empty string. This gives an easy way to skip certain
  242. // tiles in a shorthand since we can't always declare an empty string.
  243. if (texture_name.empty() || texture_name == "auto")
  244. continue;
  245. // We are required to set default values before instancing the tile, thus, all properties should always be
  246. // dereferencable. If the debugger captures a zero-dereference, check that all properties for every tile is set
  247. // and default values are set just before instancing.
  248. DecoratorTiled::Tile& tile = tiles[i];
  249. Texture& texture = textures[i];
  250. // A tile is always either a sprite or an image.
  251. if (const Sprite* sprite = instancer_interface.GetSprite(texture_name))
  252. {
  253. tile.position = sprite->rectangle.Position();
  254. tile.size = sprite->rectangle.Size();
  255. tile.display_scale = sprite->sprite_sheet->display_scale;
  256. texture = sprite->sprite_sheet->texture;
  257. }
  258. else
  259. {
  260. // No sprite found, so assume that the name is an image source. Since the common use case is to specify the
  261. // same texture for all tiles, check the previous texture first before fetching from the global database.
  262. if (texture_name == previous_texture_name)
  263. {
  264. texture = previous_texture;
  265. }
  266. else
  267. {
  268. texture = instancer_interface.GetTexture(texture_name);
  269. if (!texture)
  270. return false;
  271. previous_texture_name = texture_name;
  272. previous_texture = texture;
  273. }
  274. }
  275. if (ids.fit != PropertyId::Invalid)
  276. {
  277. RMLUI_ASSERT(ids.align_x != PropertyId::Invalid && ids.align_y != PropertyId::Invalid);
  278. const Property& fit_property = *properties.GetProperty(ids.fit);
  279. tile.fit_mode = (DecoratorTiled::TileFitMode)fit_property.value.Get<int>();
  280. const Property* align_properties[2] = {properties.GetProperty(ids.align_x), properties.GetProperty(ids.align_y)};
  281. for (int dimension = 0; dimension < 2; dimension++)
  282. {
  283. using Style::LengthPercentage;
  284. LengthPercentage& align = tile.align[dimension];
  285. const Property& property = *align_properties[dimension];
  286. if (property.unit == Unit::KEYWORD)
  287. {
  288. enum { TOP_LEFT, CENTER, BOTTOM_RIGHT };
  289. switch (property.Get<int>())
  290. {
  291. case TOP_LEFT: align = LengthPercentage(LengthPercentage::Percentage, 0.0f); break;
  292. case CENTER: align = LengthPercentage(LengthPercentage::Percentage, 50.0f); break;
  293. case BOTTOM_RIGHT: align = LengthPercentage(LengthPercentage::Percentage, 100.0f); break;
  294. }
  295. }
  296. else if (property.unit == Unit::PERCENT)
  297. {
  298. align = LengthPercentage(LengthPercentage::Percentage, property.Get<float>());
  299. }
  300. else if (property.unit == Unit::PX)
  301. {
  302. align = LengthPercentage(LengthPercentage::Length, property.Get<float>());
  303. }
  304. else
  305. {
  306. Log::Message(Log::LT_WARNING, "Decorator alignment value is '%s' which uses an unsupported unit (use px, %%, or keyword)",
  307. property.ToString().c_str());
  308. }
  309. }
  310. }
  311. if (ids.orientation != PropertyId::Invalid)
  312. {
  313. const Property& orientation_property = *properties.GetProperty(ids.orientation);
  314. tile.orientation = (DecoratorTiled::TileOrientation)orientation_property.value.Get<int>();
  315. }
  316. }
  317. return true;
  318. }
  319. } // namespace Rml