ElementImage.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 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 "ElementImage.h"
  29. #include "../TextureDatabase.h"
  30. #include "../../../Include/RmlUi/Core/URL.h"
  31. #include "../../../Include/RmlUi/Core/PropertyIdSet.h"
  32. #include "../../../Include/RmlUi/Core/GeometryUtilities.h"
  33. #include "../../../Include/RmlUi/Core/ElementDocument.h"
  34. #include "../../../Include/RmlUi/Core/ElementUtilities.h"
  35. #include "../../../Include/RmlUi/Core/StyleSheet.h"
  36. namespace Rml {
  37. // Constructs a new ElementImage.
  38. ElementImage::ElementImage(const String& tag) : Element(tag), dimensions(-1, -1), rect_source(RectSource::None), geometry(this)
  39. {
  40. dimensions_scale = 1.0f;
  41. geometry_dirty = false;
  42. texture_dirty = true;
  43. }
  44. ElementImage::~ElementImage()
  45. {
  46. }
  47. // Sizes the box to the element's inherent size.
  48. bool ElementImage::GetIntrinsicDimensions(Vector2f& _dimensions, float& _ratio)
  49. {
  50. // Check if we need to reload the texture.
  51. if (texture_dirty)
  52. LoadTexture();
  53. // Calculate the x dimension.
  54. if (HasAttribute("width"))
  55. dimensions.x = GetAttribute< float >("width", -1);
  56. else if (rect_source == RectSource::None)
  57. dimensions.x = (float)texture.GetDimensions(GetRenderInterface()).x;
  58. else
  59. dimensions.x = rect.width;
  60. // Calculate the y dimension.
  61. if (HasAttribute("height"))
  62. dimensions.y = GetAttribute< float >("height", -1);
  63. else if (rect_source == RectSource::None)
  64. dimensions.y = (float)texture.GetDimensions(GetRenderInterface()).y;
  65. else
  66. dimensions.y = rect.height;
  67. dimensions *= dimensions_scale;
  68. // Return the calculated dimensions. If this changes the size of the element, it will result in
  69. // a call to 'onresize' below which will regenerate the geometry.
  70. _dimensions = dimensions;
  71. _ratio = dimensions.x / dimensions.y;
  72. return true;
  73. }
  74. // Renders the element.
  75. void ElementImage::OnRender()
  76. {
  77. // Regenerate the geometry if required (this will be set if 'rect' changes but does not result in a resize).
  78. if (geometry_dirty)
  79. GenerateGeometry();
  80. // Render the geometry beginning at this element's content region.
  81. geometry.Render(GetAbsoluteOffset(Box::CONTENT).Round());
  82. }
  83. // Called when attributes on the element are changed.
  84. void ElementImage::OnAttributeChange(const ElementAttributes& changed_attributes)
  85. {
  86. // Call through to the base element's OnAttributeChange().
  87. Element::OnAttributeChange(changed_attributes);
  88. bool dirty_layout = false;
  89. // Check for a changed 'src' attribute. If this changes, the old texture handle is released,
  90. // forcing a reload when the layout is regenerated.
  91. if (changed_attributes.find("src") != changed_attributes.end() ||
  92. changed_attributes.find("sprite") != changed_attributes.end())
  93. {
  94. texture_dirty = true;
  95. dirty_layout = true;
  96. }
  97. // Check for a changed 'width' attribute. If this changes, a layout is forced which will
  98. // recalculate the dimensions.
  99. if (changed_attributes.find("width") != changed_attributes.end() ||
  100. changed_attributes.find("height") != changed_attributes.end())
  101. {
  102. dirty_layout = true;
  103. }
  104. // Check for a change to the 'rect' attribute. If this changes, the coordinates are
  105. // recomputed and a layout forced. If a sprite is set to source, then that will override any attribute.
  106. if (changed_attributes.find("rect") != changed_attributes.end())
  107. {
  108. UpdateRect();
  109. // Rectangle has changed; this will most likely result in a size change, so we need to force a layout.
  110. dirty_layout = true;
  111. }
  112. if (dirty_layout)
  113. DirtyLayout();
  114. }
  115. void ElementImage::OnPropertyChange(const PropertyIdSet& changed_properties)
  116. {
  117. Element::OnPropertyChange(changed_properties);
  118. if (changed_properties.Contains(PropertyId::ImageColor) ||
  119. changed_properties.Contains(PropertyId::Opacity)) {
  120. GenerateGeometry();
  121. }
  122. }
  123. void ElementImage::OnChildAdd(Element* child)
  124. {
  125. if (child == this && texture_dirty)
  126. {
  127. // Load the texture once we have attached to the document
  128. LoadTexture();
  129. }
  130. }
  131. // Regenerates the element's geometry.
  132. void ElementImage::OnResize()
  133. {
  134. GenerateGeometry();
  135. }
  136. void ElementImage::OnDpRatioChange()
  137. {
  138. texture_dirty = true;
  139. DirtyLayout();
  140. }
  141. void ElementImage::GenerateGeometry()
  142. {
  143. // Release the old geometry before specifying the new vertices.
  144. geometry.Release(true);
  145. Vector< Vertex >& vertices = geometry.GetVertices();
  146. Vector< int >& indices = geometry.GetIndices();
  147. vertices.resize(4);
  148. indices.resize(6);
  149. // Generate the texture coordinates.
  150. Vector2f texcoords[2];
  151. if (rect_source != RectSource::None)
  152. {
  153. Vector2f texture_dimensions((float) texture.GetDimensions(GetRenderInterface()).x, (float) texture.GetDimensions(GetRenderInterface()).y);
  154. if (texture_dimensions.x == 0)
  155. texture_dimensions.x = 1;
  156. if (texture_dimensions.y == 0)
  157. texture_dimensions.y = 1;
  158. texcoords[0].x = rect.x / texture_dimensions.x;
  159. texcoords[0].y = rect.y / texture_dimensions.y;
  160. texcoords[1].x = (rect.x + rect.width) / texture_dimensions.x;
  161. texcoords[1].y = (rect.y + rect.height) / texture_dimensions.y;
  162. }
  163. else
  164. {
  165. texcoords[0] = Vector2f(0, 0);
  166. texcoords[1] = Vector2f(1, 1);
  167. }
  168. const ComputedValues& computed = GetComputedValues();
  169. float opacity = computed.opacity;
  170. Colourb quad_colour = computed.image_color;
  171. quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha);
  172. Vector2f quad_size = GetBox().GetSize(Box::CONTENT).Round();
  173. GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Vector2f(0, 0), quad_size, quad_colour, texcoords[0], texcoords[1]);
  174. geometry_dirty = false;
  175. }
  176. bool ElementImage::LoadTexture()
  177. {
  178. texture_dirty = false;
  179. geometry_dirty = true;
  180. dimensions_scale = 1.0f;
  181. const float dp_ratio = ElementUtilities::GetDensityIndependentPixelRatio(this);
  182. // Check for a sprite first, this takes precedence.
  183. const String sprite_name = GetAttribute< String >("sprite", "");
  184. if (!sprite_name.empty())
  185. {
  186. // Load sprite.
  187. bool valid_sprite = false;
  188. if (ElementDocument* document = GetOwnerDocument())
  189. {
  190. if (const StyleSheet* style_sheet = document->GetStyleSheet())
  191. {
  192. if (const Sprite* sprite = style_sheet->GetSprite(sprite_name))
  193. {
  194. rect = sprite->rectangle;
  195. rect_source = RectSource::Sprite;
  196. texture = sprite->sprite_sheet->texture;
  197. dimensions_scale = sprite->sprite_sheet->display_scale * dp_ratio;
  198. valid_sprite = true;
  199. }
  200. }
  201. }
  202. if (!valid_sprite)
  203. {
  204. texture = Texture();
  205. rect_source = RectSource::None;
  206. UpdateRect();
  207. Log::Message(Log::LT_WARNING, "Could not find sprite '%s' specified in img element %s", sprite_name.c_str(), GetAddress().c_str());
  208. return false;
  209. }
  210. }
  211. else
  212. {
  213. // Load image from source URL.
  214. const String source_name = GetAttribute< String >("src", "");
  215. if (source_name.empty())
  216. {
  217. texture = Texture();
  218. rect_source = RectSource::None;
  219. return false;
  220. }
  221. URL source_url;
  222. if (ElementDocument* document = GetOwnerDocument())
  223. source_url.SetURL(document->GetSourceURL());
  224. texture.Set(source_name, source_url.GetPath());
  225. dimensions_scale = dp_ratio;
  226. }
  227. // Set the texture onto our geometry object.
  228. geometry.SetTexture(&texture);
  229. return true;
  230. }
  231. void ElementImage::UpdateRect()
  232. {
  233. if(rect_source != RectSource::Sprite)
  234. {
  235. bool valid_rect = false;
  236. String rect_string = GetAttribute< String >("rect", "");
  237. if (!rect_string.empty())
  238. {
  239. StringList coords_list;
  240. StringUtilities::ExpandString(coords_list, rect_string, ' ');
  241. if (coords_list.size() != 4)
  242. {
  243. Log::Message(Log::LT_WARNING, "Element '%s' has an invalid 'rect' attribute; rect requires 4 space-separated values, found %d.", GetAddress().c_str(), coords_list.size());
  244. }
  245. else
  246. {
  247. rect.x = (float)std::atof(coords_list[0].c_str());
  248. rect.y = (float)std::atof(coords_list[1].c_str());
  249. rect.width = (float)std::atof(coords_list[2].c_str());
  250. rect.height = (float)std::atof(coords_list[3].c_str());
  251. // We have new, valid coordinates; force the geometry to be regenerated.
  252. valid_rect = true;
  253. geometry_dirty = true;
  254. rect_source = RectSource::Attribute;
  255. }
  256. }
  257. if (!valid_rect)
  258. {
  259. rect = {};
  260. rect_source = RectSource::None;
  261. }
  262. }
  263. }
  264. } // namespace Rml