ElementAnimation.cpp 21 KB

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