ElementLottie.cpp 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 "../../Include/RmlUi/Lottie/ElementLottie.h"
  29. #include "../../Include/RmlUi/Core/ComputedValues.h"
  30. #include "../../Include/RmlUi/Core/Context.h"
  31. #include "../../Include/RmlUi/Core/Core.h"
  32. #include "../../Include/RmlUi/Core/ElementDocument.h"
  33. #include "../../Include/RmlUi/Core/ElementUtilities.h"
  34. #include "../../Include/RmlUi/Core/FileInterface.h"
  35. #include "../../Include/RmlUi/Core/MeshUtilities.h"
  36. #include "../../Include/RmlUi/Core/PropertyIdSet.h"
  37. #include "../../Include/RmlUi/Core/RenderManager.h"
  38. #include "../../Include/RmlUi/Core/SystemInterface.h"
  39. #include <cmath>
  40. #include <rlottie.h>
  41. namespace Rml {
  42. ElementLottie::ElementLottie(const String& tag) : Element(tag) {}
  43. ElementLottie::~ElementLottie() {}
  44. bool ElementLottie::GetIntrinsicDimensions(Vector2f& dimensions, float& ratio)
  45. {
  46. EnsureSourceLoaded();
  47. dimensions = intrinsic_dimensions;
  48. if (dimensions.y > 0)
  49. ratio = dimensions.x / dimensions.y;
  50. dimensions *= ElementUtilities::GetDensityIndependentPixelRatio(this);
  51. return true;
  52. }
  53. void ElementLottie::EnsureSourceLoaded()
  54. {
  55. if (animation_dirty)
  56. LoadAnimation();
  57. }
  58. void ElementLottie::OnUpdate()
  59. {
  60. EnsureSourceLoaded();
  61. if (!animation)
  62. return;
  63. const auto t = GetSystemInterface()->GetElapsedTime();
  64. if (time_animation_start < 0.0)
  65. time_animation_start = t;
  66. double _unused;
  67. const double frame_duration = 1.0 / animation->frameRate();
  68. const double delay = std::modf((t - time_animation_start) / frame_duration, &_unused) * frame_duration;
  69. if (IsVisible(true))
  70. {
  71. if (Context* ctx = GetContext())
  72. ctx->RequestNextUpdate(delay);
  73. }
  74. }
  75. void ElementLottie::OnRender()
  76. {
  77. if (animation)
  78. {
  79. if (geometry_dirty)
  80. GenerateGeometry();
  81. UpdateTexture();
  82. geometry.Render(GetAbsoluteOffset(BoxArea::Content).Round(), texture);
  83. }
  84. }
  85. void ElementLottie::OnResize()
  86. {
  87. geometry_dirty = true;
  88. texture_size_dirty = true;
  89. }
  90. void ElementLottie::OnAttributeChange(const ElementAttributes& changed_attributes)
  91. {
  92. Element::OnAttributeChange(changed_attributes);
  93. if (changed_attributes.count("src"))
  94. {
  95. animation_dirty = true;
  96. DirtyLayout();
  97. }
  98. }
  99. void ElementLottie::OnPropertyChange(const PropertyIdSet& changed_properties)
  100. {
  101. Element::OnPropertyChange(changed_properties);
  102. if (changed_properties.Contains(PropertyId::ImageColor) || changed_properties.Contains(PropertyId::Opacity))
  103. {
  104. geometry_dirty = true;
  105. }
  106. }
  107. void ElementLottie::GenerateGeometry()
  108. {
  109. const ComputedValues& computed = GetComputedValues();
  110. ColourbPremultiplied quad_colour = computed.image_color().ToPremultiplied(computed.opacity());
  111. const Vector2f render_dimensions_f = GetBox().GetSize(BoxArea::Content).Round();
  112. render_dimensions = Vector2i(render_dimensions_f);
  113. Mesh mesh = geometry.Release(Geometry::ReleaseMode::ClearMesh);
  114. MeshUtilities::GenerateQuad(mesh, Vector2f(0), render_dimensions_f, quad_colour, Vector2f(0), Vector2f(1));
  115. geometry = GetRenderManager()->MakeGeometry(std::move(mesh));
  116. geometry_dirty = false;
  117. }
  118. bool ElementLottie::LoadAnimation()
  119. {
  120. animation_dirty = false;
  121. intrinsic_dimensions = Vector2f{};
  122. texture = {};
  123. animation.reset();
  124. prev_animation_frame = size_t(-1);
  125. time_animation_start = -1;
  126. const String attribute_src = GetAttribute<String>("src", "");
  127. if (attribute_src.empty())
  128. return false;
  129. String path = attribute_src;
  130. String directory;
  131. if (ElementDocument* document = GetOwnerDocument())
  132. {
  133. const String document_source_url = StringUtilities::Replace(document->GetSourceURL(), '|', ':');
  134. GetSystemInterface()->JoinPath(path, document_source_url, attribute_src);
  135. GetSystemInterface()->JoinPath(directory, document_source_url, "");
  136. }
  137. String json_data;
  138. if (path.empty() || !GetFileInterface()->LoadFile(path, json_data))
  139. {
  140. Log::Message(Rml::Log::Type::LT_WARNING, "Could not load lottie file %s", path.c_str());
  141. return false;
  142. }
  143. animation = rlottie::Animation::loadFromData(std::move(json_data), path, directory);
  144. if (!animation)
  145. {
  146. Log::Message(Rml::Log::Type::LT_WARNING, "Could not construct the lottie animation %s", path.c_str());
  147. return false;
  148. }
  149. size_t width = 0, height = 0;
  150. animation->size(width, height);
  151. intrinsic_dimensions.x = float(width);
  152. intrinsic_dimensions.y = float(height);
  153. return true;
  154. }
  155. void ElementLottie::UpdateTexture()
  156. {
  157. if (!animation)
  158. return;
  159. RenderManager* render_manager = GetRenderManager();
  160. if (!render_manager)
  161. return;
  162. const double t = GetSystemInterface()->GetElapsedTime();
  163. // Find the next animation frame to display.
  164. // Here it is possible to add more logic to control playback speed, pause/resume, and more.
  165. double _unused;
  166. // Find the normalized animation progress [0, 1].
  167. const double pos = std::modf((t - time_animation_start) / animation->duration(), &_unused);
  168. const size_t next_frame = animation->frameAtPos(pos);
  169. if (!texture_size_dirty && next_frame == prev_animation_frame)
  170. {
  171. // No need to update the texture if we are drawing the same frame at the same size.
  172. return;
  173. }
  174. // Resize the texture buffer if necessary.
  175. const size_t new_texture_data_size = 4 * render_dimensions.x * render_dimensions.y;
  176. if (new_texture_data_size > texture_data_size)
  177. {
  178. texture_data.reset(new byte[new_texture_data_size]);
  179. texture_data_size = new_texture_data_size;
  180. }
  181. // Callback for generating texture.
  182. auto texture_callback = [this, next_frame](const CallbackTextureInterface& texture_interface) -> bool {
  183. RMLUI_ASSERT(animation);
  184. const size_t bytes_per_line = 4 * render_dimensions.x;
  185. const size_t total_bytes = bytes_per_line * render_dimensions.y;
  186. byte* p_data = texture_data.get();
  187. rlottie::Surface surface(reinterpret_cast<uint32_t*>(p_data), render_dimensions.x, render_dimensions.y, bytes_per_line);
  188. animation->renderSync(next_frame, surface);
  189. // Swizzle the channel order from rlottie's BGRA to RmlUi's RGBA.
  190. for (size_t i = 0; i < total_bytes; i += 4)
  191. {
  192. // Swap the RB order for correct color channels.
  193. std::swap(p_data[i], p_data[i + 2]);
  194. #ifdef RMLUI_DEBUG
  195. const byte alpha = p_data[i + 3];
  196. for (int c = 0; c < 3; c++)
  197. RMLUI_ASSERTMSG(p_data[i + c] <= alpha, "Glyph data is assumed to be encoded in premultiplied alpha, but that is not the case.");
  198. #endif
  199. }
  200. if (!texture_interface.GenerateTexture({p_data, total_bytes}, render_dimensions))
  201. {
  202. Log::Message(Rml::Log::Type::LT_WARNING, "Could not generate texture for lottie animation: %s", GetAttribute<String>("src", "").c_str());
  203. return false;
  204. }
  205. return true;
  206. };
  207. texture = render_manager->MakeCallbackTexture(std::move(texture_callback));
  208. prev_animation_frame = next_frame;
  209. texture_size_dirty = false;
  210. }
  211. } // namespace Rml