ElementAnimation.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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) 2018 Michael R. P. Ragazzon
  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 "ElementAnimation.h"
  29. #include "../../Include/RmlUi/Core/Decorator.h"
  30. #include "../../Include/RmlUi/Core/Element.h"
  31. #include "../../Include/RmlUi/Core/Filter.h"
  32. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  33. #include "../../Include/RmlUi/Core/PropertySpecification.h"
  34. #include "../../Include/RmlUi/Core/StyleSheet.h"
  35. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  36. #include "../../Include/RmlUi/Core/StyleSheetTypes.h"
  37. #include "../../Include/RmlUi/Core/Transform.h"
  38. #include "../../Include/RmlUi/Core/TransformPrimitive.h"
  39. #include "ComputeProperty.h"
  40. #include "ElementStyle.h"
  41. #include "TransformUtilities.h"
  42. namespace Rml {
  43. static Property InterpolateProperties(const Property& p0, const Property& p1, float alpha, Element& element, const PropertyDefinition* definition);
  44. static Colourf ColourToLinearSpace(Colourb c)
  45. {
  46. Colourf result;
  47. // Approximate inverse sRGB function
  48. result.red = c.red / 255.f;
  49. result.red *= result.red;
  50. result.green = c.green / 255.f;
  51. result.green *= result.green;
  52. result.blue = c.blue / 255.f;
  53. result.blue *= result.blue;
  54. result.alpha = c.alpha / 255.f;
  55. return result;
  56. }
  57. static Colourb ColourFromLinearSpace(Colourf c)
  58. {
  59. Colourb result;
  60. result.red = (byte)Math::Clamp(Math::SquareRoot(c.red) * 255.f, 0.0f, 255.f);
  61. result.green = (byte)Math::Clamp(Math::SquareRoot(c.green) * 255.f, 0.0f, 255.f);
  62. result.blue = (byte)Math::Clamp(Math::SquareRoot(c.blue) * 255.f, 0.0f, 255.f);
  63. result.alpha = (byte)Math::Clamp(c.alpha * 255.f, 0.0f, 255.f);
  64. return result;
  65. }
  66. // Merges all the primitives to a single DecomposedMatrix4 primitive
  67. static bool CombineAndDecompose(Transform& t, Element& e)
  68. {
  69. Matrix4f m = Matrix4f::Identity();
  70. for (TransformPrimitive& primitive : t.GetPrimitives())
  71. {
  72. Matrix4f m_primitive = TransformUtilities::ResolveTransform(primitive, e);
  73. m *= m_primitive;
  74. }
  75. Transforms::DecomposedMatrix4 decomposed;
  76. if (!TransformUtilities::Decompose(decomposed, m))
  77. return false;
  78. t.ClearPrimitives();
  79. t.AddPrimitive(decomposed);
  80. return true;
  81. }
  82. /**
  83. An abstraction for decorator and filter declarations.
  84. */
  85. struct EffectDeclarationView {
  86. EffectDeclarationView() = default;
  87. EffectDeclarationView(const DecoratorDeclaration& declaration) :
  88. instancer(declaration.instancer), type(&declaration.type), properties(&declaration.properties), paint_area(declaration.paint_area)
  89. {}
  90. EffectDeclarationView(const NamedDecorator* named_decorator) :
  91. instancer(named_decorator->instancer), type(&named_decorator->type), properties(&named_decorator->properties)
  92. {}
  93. EffectDeclarationView(const FilterDeclaration& declaration) :
  94. instancer(declaration.instancer), type(&declaration.type), properties(&declaration.properties)
  95. {}
  96. EffectSpecification* instancer = nullptr;
  97. const String* type = nullptr;
  98. const PropertyDictionary* properties = nullptr;
  99. BoxArea paint_area = BoxArea::Auto;
  100. explicit operator bool() const { return instancer != nullptr; }
  101. };
  102. // Interpolate two effect declarations. One of them can be empty, in which case the empty one is replaced by default values.
  103. static bool InterpolateEffectProperties(PropertyDictionary& properties, const EffectDeclarationView& d0, const EffectDeclarationView& d1, float alpha,
  104. Element& element)
  105. {
  106. if (d0 && d1)
  107. {
  108. // Both declarations are specified, check if they are compatible for interpolation.
  109. if (!d0.instancer || d0.instancer != d1.instancer || *d0.type != *d1.type ||
  110. d0.properties->GetNumProperties() != d1.properties->GetNumProperties() || d0.paint_area != d1.paint_area)
  111. return false;
  112. const auto& properties0 = d0.properties->GetProperties();
  113. const auto& properties1 = d1.properties->GetProperties();
  114. for (const auto& pair0 : properties0)
  115. {
  116. const PropertyId id = pair0.first;
  117. const Property& prop0 = pair0.second;
  118. auto it = properties1.find(id);
  119. if (it == properties1.end())
  120. {
  121. RMLUI_ERRORMSG("Incompatible decorator properties.");
  122. return false;
  123. }
  124. const Property& prop1 = it->second;
  125. Property p = InterpolateProperties(prop0, prop1, alpha, element, prop0.definition);
  126. p.definition = prop0.definition;
  127. properties.SetProperty(id, p);
  128. }
  129. return true;
  130. }
  131. else if ((d0 && !d1) || (!d0 && d1))
  132. {
  133. // One of the declarations is empty, interpolate against the default values of its type.
  134. const auto& d_filled = (d0 ? d0 : d1);
  135. const PropertySpecification& specification = d_filled.instancer->GetPropertySpecification();
  136. const PropertyMap& properties_filled = d_filled.properties->GetProperties();
  137. for (const auto& pair_filled : properties_filled)
  138. {
  139. const PropertyId id = pair_filled.first;
  140. const PropertyDefinition* underlying_definition = specification.GetProperty(id);
  141. if (!underlying_definition)
  142. return false;
  143. const Property& p_filled = pair_filled.second;
  144. const Property& p_default = *underlying_definition->GetDefaultValue();
  145. const Property& p_interp0 = (d0 ? p_filled : p_default);
  146. const Property& p_interp1 = (d1 ? p_filled : p_default);
  147. Property p = InterpolateProperties(p_interp0, p_interp1, alpha, element, p_filled.definition);
  148. p.definition = p_filled.definition;
  149. properties.SetProperty(id, p);
  150. }
  151. return true;
  152. }
  153. return false;
  154. }
  155. static Property InterpolateProperties(const Property& p0, const Property& p1, float alpha, Element& element, const PropertyDefinition* definition)
  156. {
  157. const Property& p_discrete = (alpha < 0.5f ? p0 : p1);
  158. if (Any(p0.unit & Unit::NUMBER_LENGTH_PERCENT) && Any(p1.unit & Unit::NUMBER_LENGTH_PERCENT))
  159. {
  160. if (p0.unit == p1.unit || !definition)
  161. {
  162. // If we have the same units, we can just interpolate regardless of what the value represents.
  163. // Or if we have distinct units but no definition, all bets are off. This shouldn't occur, just interpolate values.
  164. float f0 = p0.value.Get<float>();
  165. float f1 = p1.value.Get<float>();
  166. float f = (1.0f - alpha) * f0 + alpha * f1;
  167. return Property{f, p0.unit};
  168. }
  169. else
  170. {
  171. // Otherwise, convert units to pixels.
  172. float f0 = element.GetStyle()->ResolveRelativeLength(p0.GetNumericValue(), definition->GetRelativeTarget());
  173. float f1 = element.GetStyle()->ResolveRelativeLength(p1.GetNumericValue(), definition->GetRelativeTarget());
  174. float f = (1.0f - alpha) * f0 + alpha * f1;
  175. return Property{f, Unit::PX};
  176. }
  177. }
  178. if (Any(p0.unit & Unit::ANGLE) && Any(p1.unit & Unit::ANGLE))
  179. {
  180. float f0 = ComputeAngle(p0.GetNumericValue());
  181. float f1 = ComputeAngle(p1.GetNumericValue());
  182. float f = (1.0f - alpha) * f0 + alpha * f1;
  183. return Property{f, Unit::RAD};
  184. }
  185. if (p0.unit == Unit::KEYWORD && p1.unit == Unit::KEYWORD)
  186. {
  187. // Discrete interpolation, swap at alpha = 0.5.
  188. // Special case for the 'visibility' property as in the CSS specs:
  189. // Apply the visible property if present during the entire transition period, ie. alpha (0,1).
  190. if (definition && definition->GetId() == PropertyId::Visibility)
  191. {
  192. if (p0.Get<int>() == (int)Style::Visibility::Visible)
  193. return alpha < 1.f ? p0 : p1;
  194. else if (p1.Get<int>() == (int)Style::Visibility::Visible)
  195. return alpha <= 0.f ? p0 : p1;
  196. }
  197. return p_discrete;
  198. }
  199. if (p0.unit == Unit::COLOUR && p1.unit == Unit::COLOUR)
  200. {
  201. Colourf c0 = ColourToLinearSpace(p0.value.Get<Colourb>());
  202. Colourf c1 = ColourToLinearSpace(p1.value.Get<Colourb>());
  203. Colourf c = c0 * (1.0f - alpha) + c1 * alpha;
  204. return Property{ColourFromLinearSpace(c), Unit::COLOUR};
  205. }
  206. if (p0.unit == Unit::TRANSFORM && p1.unit == Unit::TRANSFORM)
  207. {
  208. auto& t0 = p0.value.GetReference<TransformPtr>();
  209. auto& t1 = p1.value.GetReference<TransformPtr>();
  210. const auto& prim0 = t0->GetPrimitives();
  211. const auto& prim1 = t1->GetPrimitives();
  212. if (prim0.size() != prim1.size())
  213. {
  214. RMLUI_ERRORMSG("Transform primitives not of same size during interpolation. Were the transforms properly prepared for interpolation?");
  215. return Property{t0, Unit::TRANSFORM};
  216. }
  217. // Build the new, interpolating transform
  218. UniquePtr<Transform> t(new Transform);
  219. t->GetPrimitives().reserve(t0->GetPrimitives().size());
  220. for (size_t i = 0; i < prim0.size(); i++)
  221. {
  222. TransformPrimitive p = prim0[i];
  223. if (!TransformUtilities::InterpolateWith(p, prim1[i], alpha))
  224. {
  225. RMLUI_ERRORMSG("Transform primitives can not be interpolated. Were the transforms properly prepared for interpolation?");
  226. return Property{t0, Unit::TRANSFORM};
  227. }
  228. t->AddPrimitive(p);
  229. }
  230. return Property{TransformPtr(std::move(t)), Unit::TRANSFORM};
  231. }
  232. if (p0.unit == Unit::DECORATOR && p1.unit == Unit::DECORATOR)
  233. {
  234. auto GetEffectDeclarationView = [](const Vector<DecoratorDeclaration>& declarations, size_t i, Element& element) -> EffectDeclarationView {
  235. if (i >= declarations.size())
  236. return EffectDeclarationView();
  237. const DecoratorDeclaration& declaration = declarations[i];
  238. if (declaration.instancer)
  239. return EffectDeclarationView(declaration);
  240. // If we don't have a decorator instancer, then this should be a named @decorator, look for one now.
  241. const StyleSheet* style_sheet = element.GetStyleSheet();
  242. if (!style_sheet)
  243. return EffectDeclarationView();
  244. const NamedDecorator* named_decorator = style_sheet->GetNamedDecorator(declaration.type);
  245. if (!named_decorator)
  246. {
  247. Log::Message(Log::LT_WARNING, "Could not find a named @decorator '%s'.", declaration.type.c_str());
  248. return EffectDeclarationView();
  249. }
  250. return EffectDeclarationView(named_decorator);
  251. };
  252. auto& ptr0 = p0.value.GetReference<DecoratorsPtr>();
  253. auto& ptr1 = p1.value.GetReference<DecoratorsPtr>();
  254. if (!ptr0 || !ptr1)
  255. {
  256. RMLUI_ERRORMSG("Invalid decorator pointer, were the decorator keys properly prepared?");
  257. return p_discrete;
  258. }
  259. // Build the new, interpolated decorator list.
  260. const bool p0_bigger = ptr0->list.size() > ptr1->list.size();
  261. auto& big_list = (p0_bigger ? ptr0->list : ptr1->list);
  262. auto decorator = MakeUnique<DecoratorDeclarationList>();
  263. auto& list = decorator->list;
  264. list.reserve(big_list.size());
  265. for (size_t i = 0; i < big_list.size(); i++)
  266. {
  267. EffectDeclarationView d0 = GetEffectDeclarationView(ptr0->list, i, element);
  268. EffectDeclarationView d1 = GetEffectDeclarationView(ptr1->list, i, element);
  269. const EffectDeclarationView& declaration = (p0_bigger ? d0 : d1);
  270. list.push_back(DecoratorDeclaration{*declaration.type, static_cast<DecoratorInstancer*>(declaration.instancer), PropertyDictionary(),
  271. declaration.paint_area});
  272. if (!InterpolateEffectProperties(list.back().properties, d0, d1, alpha, element))
  273. return p_discrete;
  274. }
  275. return Property{DecoratorsPtr(std::move(decorator)), Unit::DECORATOR};
  276. }
  277. if (p0.unit == Unit::FILTER && p1.unit == Unit::FILTER)
  278. {
  279. auto GetEffectDeclarationView = [](const Vector<FilterDeclaration>& declarations, size_t i) -> EffectDeclarationView {
  280. if (i >= declarations.size())
  281. return EffectDeclarationView();
  282. return EffectDeclarationView(declarations[i]);
  283. };
  284. auto& ptr0 = p0.value.GetReference<FiltersPtr>();
  285. auto& ptr1 = p1.value.GetReference<FiltersPtr>();
  286. if (!ptr0 || !ptr1)
  287. {
  288. RMLUI_ERRORMSG("Invalid filter pointer, were the filter keys properly prepared?");
  289. return p_discrete;
  290. }
  291. // Build the new, interpolated filter list.
  292. const bool p0_bigger = ptr0->list.size() > ptr1->list.size();
  293. auto& big_list = (p0_bigger ? ptr0->list : ptr1->list);
  294. auto filter = MakeUnique<FilterDeclarationList>();
  295. auto& list = filter->list;
  296. list.reserve(big_list.size());
  297. for (size_t i = 0; i < big_list.size(); i++)
  298. {
  299. EffectDeclarationView d0 = GetEffectDeclarationView(ptr0->list, i);
  300. EffectDeclarationView d1 = GetEffectDeclarationView(ptr1->list, i);
  301. const EffectDeclarationView& declaration = (p0_bigger ? d0 : d1);
  302. list.push_back(FilterDeclaration{*declaration.type, static_cast<FilterInstancer*>(declaration.instancer), PropertyDictionary()});
  303. if (!InterpolateEffectProperties(list.back().properties, d0, d1, alpha, element))
  304. return p_discrete;
  305. }
  306. return Property{FiltersPtr(std::move(filter)), Unit::FILTER};
  307. }
  308. // Fall back to discrete interpolation for incompatible units.
  309. return p_discrete;
  310. }
  311. enum class PrepareTransformResult { Unchanged = 0, ChangedT0 = 1, ChangedT1 = 2, ChangedT0andT1 = 3, Invalid = 4 };
  312. static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, Element& element)
  313. {
  314. using namespace Transforms;
  315. // Insert or modify primitives such that the two transforms match exactly in both number of and types of primitives.
  316. // Based largely on https://drafts.csswg.org/css-transforms-1/#interpolation-of-transforms
  317. auto& prims0 = t0.GetPrimitives();
  318. auto& prims1 = t1.GetPrimitives();
  319. // Check for trivial case where they contain the same primitives
  320. if (prims0.size() == prims1.size())
  321. {
  322. PrepareTransformResult result = PrepareTransformResult::Unchanged;
  323. bool same_primitives = true;
  324. for (size_t i = 0; i < prims0.size(); i++)
  325. {
  326. auto p0_type = prims0[i].type;
  327. auto p1_type = prims1[i].type;
  328. // See if they are the same or can be converted to a matching generic type.
  329. if (TransformUtilities::TryConvertToMatchingGenericType(prims0[i], prims1[i]))
  330. {
  331. if (prims0[i].type != p0_type)
  332. result = PrepareTransformResult((int)result | (int)PrepareTransformResult::ChangedT0);
  333. if (prims1[i].type != p1_type)
  334. result = PrepareTransformResult((int)result | (int)PrepareTransformResult::ChangedT1);
  335. }
  336. else
  337. {
  338. same_primitives = false;
  339. break;
  340. }
  341. }
  342. if (same_primitives)
  343. return result;
  344. }
  345. if (prims0.size() != prims1.size())
  346. {
  347. // Try to match the smallest set of primitives to the larger set, set missing keys in the small set to identity.
  348. // Requirement: The small set must match types in the same order they appear in the big set.
  349. // Example: (letter indicates type, number represents values)
  350. // big: a0 b0 c0 b1
  351. // ^ ^
  352. // small: b2 b3
  353. // ^ ^
  354. // new small: a1 b2 c1 b3
  355. bool prims0_smallest = (prims0.size() < prims1.size());
  356. auto& small = (prims0_smallest ? prims0 : prims1);
  357. auto& big = (prims0_smallest ? prims1 : prims0);
  358. Vector<size_t> matching_indices; // Indices into 'big' for matching types
  359. matching_indices.reserve(small.size() + 1);
  360. size_t i_big = 0;
  361. bool match_success = true;
  362. bool changed_big = false;
  363. // Iterate through the small set to see if its types fit into the big set
  364. for (size_t i_small = 0; i_small < small.size(); i_small++)
  365. {
  366. match_success = false;
  367. for (; i_big < big.size(); i_big++)
  368. {
  369. auto big_type = big[i_big].type;
  370. if (TransformUtilities::TryConvertToMatchingGenericType(small[i_small], big[i_big]))
  371. {
  372. // They matched exactly or in their more generic form. One or both primitives may have been converted.
  373. if (big[i_big].type != big_type)
  374. changed_big = true;
  375. matching_indices.push_back(i_big);
  376. match_success = true;
  377. i_big += 1;
  378. break;
  379. }
  380. }
  381. if (!match_success)
  382. break;
  383. }
  384. if (match_success)
  385. {
  386. // Success, insert the missing primitives into the small set
  387. matching_indices.push_back(big.size()); // Needed to copy elements behind the last matching primitive
  388. small.reserve(big.size());
  389. size_t i0 = 0;
  390. for (size_t match_index : matching_indices)
  391. {
  392. for (size_t i = i0; i < match_index; i++)
  393. {
  394. TransformPrimitive p = big[i];
  395. TransformUtilities::SetIdentity(p);
  396. small.insert(small.begin() + i, p);
  397. }
  398. // Next value to copy is one-past the matching primitive
  399. i0 = match_index + 1;
  400. }
  401. // The small set has always been changed if we get here, but the big set is only changed
  402. // if one or more of its primitives were converted to a general form.
  403. if (changed_big)
  404. return PrepareTransformResult::ChangedT0andT1;
  405. return (prims0_smallest ? PrepareTransformResult::ChangedT0 : PrepareTransformResult::ChangedT1);
  406. }
  407. }
  408. // If we get here, things get tricky. Need to do full matrix interpolation.
  409. // In short, we decompose the Transforms into translation, rotation, scale, skew and perspective components.
  410. // Then, during update, interpolate these components and combine into a new transform matrix.
  411. if (!CombineAndDecompose(t0, element))
  412. return PrepareTransformResult::Invalid;
  413. if (!CombineAndDecompose(t1, element))
  414. return PrepareTransformResult::Invalid;
  415. return PrepareTransformResult::ChangedT0andT1;
  416. }
  417. static bool PrepareTransforms(Vector<AnimationKey>& keys, Element& element, int start_index)
  418. {
  419. bool result = true;
  420. // Prepare each transform individually.
  421. for (int i = start_index; i < (int)keys.size(); i++)
  422. {
  423. Property& property = keys[i].property;
  424. RMLUI_ASSERT(property.value.GetType() == Variant::TRANSFORMPTR);
  425. if (!property.value.GetReference<TransformPtr>())
  426. property.value = MakeShared<Transform>();
  427. bool must_decompose = false;
  428. Transform& transform = *property.value.GetReference<TransformPtr>();
  429. for (TransformPrimitive& primitive : transform.GetPrimitives())
  430. {
  431. if (!TransformUtilities::PrepareForInterpolation(primitive, element))
  432. {
  433. must_decompose = true;
  434. break;
  435. }
  436. }
  437. if (must_decompose)
  438. result &= CombineAndDecompose(transform, element);
  439. }
  440. if (!result)
  441. return false;
  442. // We don't need to prepare the transforms pairwise if we only have a single key added so far.
  443. if (keys.size() < 2 || start_index < 1)
  444. return true;
  445. // Now, prepare the transforms pair-wise so they can be interpolated.
  446. const int N = (int)keys.size();
  447. int count_iterations = -1;
  448. const int max_iterations = 3 * N;
  449. Vector<bool> dirty_list(N + 1, false);
  450. dirty_list[start_index] = true;
  451. // For each pair of keys, match the transform primitives such that they can be interpolated during animation update
  452. for (int i = start_index; i < N && count_iterations < max_iterations; count_iterations++)
  453. {
  454. if (!dirty_list[i])
  455. {
  456. ++i;
  457. continue;
  458. }
  459. auto& prop0 = keys[i - 1].property;
  460. auto& prop1 = keys[i].property;
  461. if (prop0.unit != Unit::TRANSFORM || prop1.unit != Unit::TRANSFORM)
  462. return false;
  463. auto& t0 = prop0.value.GetReference<TransformPtr>();
  464. auto& t1 = prop1.value.GetReference<TransformPtr>();
  465. auto prepare_result = PrepareTransformPair(*t0, *t1, element);
  466. if (prepare_result == PrepareTransformResult::Invalid)
  467. return false;
  468. bool changed_t0 = ((int)prepare_result & (int)PrepareTransformResult::ChangedT0);
  469. bool changed_t1 = ((int)prepare_result & (int)PrepareTransformResult::ChangedT1);
  470. dirty_list[i] = false;
  471. dirty_list[i - 1] = dirty_list[i - 1] || changed_t0;
  472. dirty_list[i + 1] = dirty_list[i + 1] || changed_t1;
  473. if (changed_t0 && i > 1)
  474. --i;
  475. else
  476. ++i;
  477. }
  478. // Something has probably gone wrong if we exceeded max_iterations, possibly a bug in PrepareTransformPair()
  479. return (count_iterations < max_iterations);
  480. }
  481. static void PrepareDecorator(AnimationKey& key)
  482. {
  483. Property& property = key.property;
  484. RMLUI_ASSERT(property.value.GetType() == Variant::DECORATORSPTR);
  485. if (!property.value.GetReference<DecoratorsPtr>())
  486. property.value = MakeShared<DecoratorDeclarationList>();
  487. }
  488. static void PrepareFilter(AnimationKey& key)
  489. {
  490. Property& property = key.property;
  491. RMLUI_ASSERT(property.value.GetType() == Variant::FILTERSPTR);
  492. if (!property.value.GetReference<FiltersPtr>())
  493. property.value = MakeShared<FilterDeclarationList>();
  494. }
  495. ElementAnimation::ElementAnimation(PropertyId property_id, ElementAnimationOrigin origin, const Property& current_value, Element& element,
  496. double start_world_time, float duration, int num_iterations, bool alternate_direction) :
  497. property_id(property_id),
  498. duration(duration), num_iterations(num_iterations), alternate_direction(alternate_direction), last_update_world_time(start_world_time),
  499. origin(origin)
  500. {
  501. if (!current_value.definition)
  502. {
  503. Log::Message(Log::LT_WARNING, "Property in animation key did not have a definition (while adding key '%s').",
  504. current_value.ToString().c_str());
  505. }
  506. InternalAddKey(0.0f, current_value, element, Tween{});
  507. }
  508. bool ElementAnimation::InternalAddKey(float time, const Property& in_property, Element& element, Tween tween)
  509. {
  510. const Units valid_units =
  511. (Unit::NUMBER_LENGTH_PERCENT | Unit::ANGLE | Unit::COLOUR | Unit::TRANSFORM | Unit::KEYWORD | Unit::DECORATOR | Unit::FILTER);
  512. if (!Any(in_property.unit & valid_units))
  513. {
  514. Log::Message(Log::LT_WARNING, "Property value '%s' is not a valid target for interpolation.", in_property.ToString().c_str());
  515. return false;
  516. }
  517. keys.emplace_back(time, in_property, tween);
  518. Property& property = keys.back().property;
  519. bool result = true;
  520. if (property.unit == Unit::TRANSFORM)
  521. {
  522. result = PrepareTransforms(keys, element, (int)keys.size() - 1);
  523. }
  524. else if (property.unit == Unit::DECORATOR)
  525. {
  526. PrepareDecorator(keys.back());
  527. }
  528. else if (property.unit == Unit::FILTER)
  529. {
  530. PrepareFilter(keys.back());
  531. }
  532. if (!result)
  533. {
  534. Log::Message(Log::LT_WARNING, "Could not add animation key with property '%s'.", in_property.ToString().c_str());
  535. keys.pop_back();
  536. }
  537. return result;
  538. }
  539. bool ElementAnimation::AddKey(float target_time, const Property& in_property, Element& element, Tween tween, bool extend_duration)
  540. {
  541. if (!IsInitalized())
  542. {
  543. Log::Message(Log::LT_WARNING, "Element animation was not initialized properly, can't add key.");
  544. return false;
  545. }
  546. if (!InternalAddKey(target_time, in_property, element, tween))
  547. {
  548. return false;
  549. }
  550. if (extend_duration)
  551. duration = target_time;
  552. return true;
  553. }
  554. float ElementAnimation::GetInterpolationFactorAndKeys(int* out_key0, int* out_key1) const
  555. {
  556. float t = time_since_iteration_start;
  557. if (reverse_direction)
  558. t = duration - t;
  559. int key0 = -1;
  560. int key1 = -1;
  561. {
  562. for (int i = 0; i < (int)keys.size(); i++)
  563. {
  564. if (keys[i].time >= t)
  565. {
  566. key1 = i;
  567. break;
  568. }
  569. }
  570. if (key1 < 0)
  571. key1 = (int)keys.size() - 1;
  572. key0 = (key1 == 0 ? 0 : key1 - 1);
  573. }
  574. RMLUI_ASSERT(key0 >= 0 && key0 < (int)keys.size() && key1 >= 0 && key1 < (int)keys.size());
  575. float alpha = 0.0f;
  576. {
  577. const float t0 = keys[key0].time;
  578. const float t1 = keys[key1].time;
  579. const float eps = 1e-3f;
  580. if (t1 - t0 > eps)
  581. alpha = (t - t0) / (t1 - t0);
  582. alpha = Math::Clamp(alpha, 0.0f, 1.0f);
  583. }
  584. alpha = keys[key1].tween(alpha);
  585. if (out_key0)
  586. *out_key0 = key0;
  587. if (out_key1)
  588. *out_key1 = key1;
  589. return alpha;
  590. }
  591. Property ElementAnimation::UpdateAndGetProperty(double world_time, Element& element)
  592. {
  593. float dt = float(world_time - last_update_world_time);
  594. if (keys.size() < 2 || animation_complete || dt <= 0.0f)
  595. return Property{};
  596. dt = Math::Min(dt, 0.1f);
  597. last_update_world_time = world_time;
  598. time_since_iteration_start += dt;
  599. if (time_since_iteration_start >= duration)
  600. {
  601. // Next iteration
  602. current_iteration += 1;
  603. if (num_iterations == -1 || (current_iteration >= 0 && current_iteration < num_iterations))
  604. {
  605. time_since_iteration_start -= duration;
  606. if (alternate_direction)
  607. reverse_direction = !reverse_direction;
  608. }
  609. else
  610. {
  611. animation_complete = true;
  612. time_since_iteration_start = duration;
  613. }
  614. }
  615. int key0 = -1;
  616. int key1 = -1;
  617. float alpha = GetInterpolationFactorAndKeys(&key0, &key1);
  618. Property result = InterpolateProperties(keys[key0].property, keys[key1].property, alpha, element, keys[0].property.definition);
  619. return result;
  620. }
  621. } // namespace Rml