ElementLottie.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 "../../Include/RmlUi/Lottie/ElementLottie.h"
  29. #include "../../Include/RmlUi/Core/Core.h"
  30. #include "../../Include/RmlUi/Core/PropertyIdSet.h"
  31. #include "../../Include/RmlUi/Core/GeometryUtilities.h"
  32. #include "../../Include/RmlUi/Core/ElementDocument.h"
  33. #include "../../Include/RmlUi/Core/SystemInterface.h"
  34. #include "../../Include/RmlUi/Core/FileInterface.h"
  35. #include <cmath>
  36. #include <rlottie.h>
  37. namespace Rml {
  38. ElementLottie::ElementLottie(const String& tag) : Element(tag), geometry(this)
  39. {
  40. }
  41. ElementLottie::~ElementLottie()
  42. {
  43. }
  44. bool ElementLottie::GetIntrinsicDimensions(Vector2f& dimensions, float& ratio)
  45. {
  46. if (animation_dirty)
  47. LoadAnimation();
  48. dimensions = intrinsic_dimensions;
  49. if (dimensions.y > 0)
  50. ratio = dimensions.x / dimensions.y;
  51. return true;
  52. }
  53. void ElementLottie::OnRender()
  54. {
  55. if (animation)
  56. {
  57. if (geometry_dirty)
  58. GenerateGeometry();
  59. UpdateTexture();
  60. geometry.Render(GetAbsoluteOffset(Box::CONTENT).Round());
  61. }
  62. }
  63. void ElementLottie::OnResize()
  64. {
  65. geometry_dirty = true;
  66. texture_size_dirty = true;
  67. }
  68. void ElementLottie::OnAttributeChange(const ElementAttributes& changed_attributes)
  69. {
  70. Element::OnAttributeChange(changed_attributes);
  71. if (changed_attributes.count("src"))
  72. {
  73. animation_dirty = true;
  74. DirtyLayout();
  75. }
  76. }
  77. void ElementLottie::OnPropertyChange(const PropertyIdSet& changed_properties)
  78. {
  79. Element::OnPropertyChange(changed_properties);
  80. if (changed_properties.Contains(PropertyId::ImageColor) ||
  81. changed_properties.Contains(PropertyId::Opacity)) {
  82. geometry_dirty = true;
  83. }
  84. }
  85. void ElementLottie::GenerateGeometry()
  86. {
  87. geometry.Release(true);
  88. Vector< Vertex >& vertices = geometry.GetVertices();
  89. Vector< int >& indices = geometry.GetIndices();
  90. vertices.resize(4);
  91. indices.resize(6);
  92. Vector2f texcoords[2] = {
  93. {0.0f, 0.0f},
  94. {1.0f, 1.0f}
  95. };
  96. const ComputedValues& computed = GetComputedValues();
  97. const float opacity = computed.opacity;
  98. Colourb quad_colour = computed.image_color;
  99. quad_colour.alpha = (byte)(opacity * (float)quad_colour.alpha);
  100. const Vector2f render_dimensions_f = GetBox().GetSize(Box::CONTENT).Round();
  101. render_dimensions = Vector2i(render_dimensions_f);
  102. GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Vector2f(0, 0), render_dimensions_f, quad_colour, texcoords[0], texcoords[1]);
  103. geometry_dirty = false;
  104. }
  105. bool ElementLottie::LoadAnimation()
  106. {
  107. animation_dirty = false;
  108. intrinsic_dimensions = Vector2f{};
  109. geometry.SetTexture(nullptr);
  110. animation.reset();
  111. prev_animation_frame = size_t(-1);
  112. time_animation_start = -1;
  113. const String attribute_src = GetAttribute<String>("src", "");
  114. if (attribute_src.empty())
  115. return false;
  116. String path = attribute_src;
  117. String directory;
  118. if (ElementDocument* document = GetOwnerDocument())
  119. {
  120. const String document_source_url = StringUtilities::Replace(document->GetSourceURL(), '|', ':');
  121. GetSystemInterface()->JoinPath(path, document_source_url, attribute_src);
  122. GetSystemInterface()->JoinPath(directory, document_source_url, "");
  123. }
  124. String json_data;
  125. if (path.empty() || !GetFileInterface()->LoadFile(path, json_data))
  126. {
  127. Log::Message(Rml::Log::Type::LT_WARNING, "Could not load lottie file %s", path.c_str());
  128. return false;
  129. }
  130. animation = rlottie::Animation::loadFromData(std::move(json_data), path, directory);
  131. if (!animation)
  132. {
  133. Log::Message(Rml::Log::Type::LT_WARNING, "Could not construct the lottie animation %s", path.c_str());
  134. return false;
  135. }
  136. size_t width = 0, height = 0;
  137. animation->size(width, height);
  138. intrinsic_dimensions.x = float(width);
  139. intrinsic_dimensions.y = float(height);
  140. return true;
  141. }
  142. void ElementLottie::UpdateTexture()
  143. {
  144. if (!animation)
  145. return;
  146. const double t = GetSystemInterface()->GetElapsedTime();
  147. if (time_animation_start < 0.0)
  148. time_animation_start = t;
  149. // Find the next animation frame to display.
  150. // Here it is possible to add more logic to control playback speed, pause/resume, and more.
  151. double _unused;
  152. // Find the normalized animation progress [0, 1].
  153. const double pos = std::modf((t - time_animation_start) / animation->duration(), &_unused);
  154. const size_t next_frame = animation->frameAtPos(pos);
  155. if (!texture_size_dirty && next_frame == prev_animation_frame)
  156. {
  157. // No need to update the texture if we are drawing the same frame at the same size.
  158. return;
  159. }
  160. // Callback for generating texture.
  161. auto p_callback = [this, next_frame](const String& /*name*/, UniquePtr<const byte[]>& data, Vector2i& dimensions) -> bool {
  162. RMLUI_ASSERT(animation);
  163. const size_t bytes_per_line = 4 * render_dimensions.x;
  164. const size_t total_bytes = bytes_per_line * render_dimensions.y;
  165. byte* p_data = new byte[total_bytes];
  166. rlottie::Surface surface(reinterpret_cast<std::uint32_t*>(p_data), render_dimensions.x, render_dimensions.y, bytes_per_line);
  167. animation->renderSync(next_frame, surface);
  168. // Swizzle the channel order from rlottie's BGRA to RmlUi's RGBA, and change pre-multiplied to post-multiplied alpha.
  169. for (size_t i = 0; i < total_bytes; i += 4)
  170. {
  171. // Swap the RB order for correct color channels.
  172. std::swap(p_data[i], p_data[i + 2]);
  173. const byte a = p_data[i + 3];
  174. // The RmlUi samples shell uses post-multiplied alpha, while rlottie serves pre-multiplied alpha.
  175. // Here, we un-premultiply the colors.
  176. if (a > 0 && a < 255)
  177. {
  178. for (size_t j = 0; j < 3; j++)
  179. p_data[i + j] = (p_data[i + j] * 255) / a;
  180. }
  181. }
  182. data.reset(p_data);
  183. dimensions = render_dimensions;
  184. return true;
  185. };
  186. texture.Set("lottie", p_callback);
  187. geometry.SetTexture(&texture);
  188. prev_animation_frame = next_frame;
  189. texture_size_dirty = false;
  190. }
  191. } // namespace Rml