ElementAnimation.cpp 21 KB

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