ElementAnimation.cpp 25 KB

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