ElementAnimation.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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 "ElementStyle.h"
  30. #include "TransformUtilities.h"
  31. #include "../../Include/RmlUi/Core/Element.h"
  32. #include "../../Include/RmlUi/Core/PropertyDefinition.h"
  33. #include "../../Include/RmlUi/Core/StyleSheetSpecification.h"
  34. #include "../../Include/RmlUi/Core/Transform.h"
  35. #include "../../Include/RmlUi/Core/TransformPrimitive.h"
  36. namespace Rml {
  37. static Colourf ColourToLinearSpace(Colourb c)
  38. {
  39. Colourf result;
  40. // Approximate inverse sRGB function
  41. result.red = c.red / 255.f;
  42. result.red *= result.red;
  43. result.green = c.green / 255.f;
  44. result.green *= result.green;
  45. result.blue = c.blue / 255.f;
  46. result.blue *= result.blue;
  47. result.alpha = c.alpha / 255.f;
  48. return result;
  49. }
  50. static Colourb ColourFromLinearSpace(Colourf c)
  51. {
  52. Colourb result;
  53. result.red = (byte)Math::Clamp(Math::SquareRoot(c.red)*255.f, 0.0f, 255.f);
  54. result.green = (byte)Math::Clamp(Math::SquareRoot(c.green)*255.f, 0.0f, 255.f);
  55. result.blue = (byte)Math::Clamp(Math::SquareRoot(c.blue)*255.f, 0.0f, 255.f);
  56. result.alpha = (byte)Math::Clamp(c.alpha*255.f, 0.0f, 255.f);
  57. return result;
  58. }
  59. // Merges all the primitives to a single DecomposedMatrix4 primitive
  60. static bool CombineAndDecompose(Transform& t, Element& e)
  61. {
  62. Matrix4f m = Matrix4f::Identity();
  63. for (TransformPrimitive& primitive : t.GetPrimitives())
  64. {
  65. Matrix4f m_primitive = TransformUtilities::ResolveTransform(primitive, e);
  66. m *= m_primitive;
  67. }
  68. Transforms::DecomposedMatrix4 decomposed;
  69. if (!TransformUtilities::Decompose(decomposed, m))
  70. return false;
  71. t.ClearPrimitives();
  72. t.AddPrimitive(decomposed);
  73. return true;
  74. }
  75. static Property InterpolateProperties(const Property & p0, const Property& p1, float alpha, Element& element, const PropertyDefinition* definition)
  76. {
  77. if ((p0.unit & Property::NUMBER_LENGTH_PERCENT) && (p1.unit & Property::NUMBER_LENGTH_PERCENT))
  78. {
  79. if (p0.unit == p1.unit || !definition)
  80. {
  81. // If we have the same units, we can just interpolate regardless of what the value represents.
  82. // Or if we have distinct units but no definition, all bets are off. This shouldn't occur, just interpolate values.
  83. float f0 = p0.value.Get<float>();
  84. float f1 = p1.value.Get<float>();
  85. float f = (1.0f - alpha) * f0 + alpha * f1;
  86. return Property{ f, p0.unit };
  87. }
  88. else
  89. {
  90. // Otherwise, convert units to pixels.
  91. float f0 = element.GetStyle()->ResolveLength(&p0, definition->GetRelativeTarget());
  92. float f1 = element.GetStyle()->ResolveLength(&p1, definition->GetRelativeTarget());
  93. float f = (1.0f - alpha) * f0 + alpha * f1;
  94. return Property{ f, Property::PX };
  95. }
  96. }
  97. if (p0.unit == Property::KEYWORD && p1.unit == Property::KEYWORD)
  98. {
  99. // Discrete interpolation, swap at alpha = 0.5.
  100. // Special case for the 'visibility' property as in the CSS specs:
  101. // Apply the visible property if present during the entire transition period, ie. alpha (0,1).
  102. if (definition && definition->GetId() == PropertyId::Visibility)
  103. {
  104. if (p0.Get<int>() == (int)Style::Visibility::Visible)
  105. return alpha < 1.f ? p0 : p1;
  106. else if (p1.Get<int>() == (int)Style::Visibility::Visible)
  107. return alpha <= 0.f ? p0 : p1;
  108. }
  109. return alpha < 0.5f ? p0 : p1;
  110. }
  111. if (p0.unit == Property::COLOUR && p1.unit == Property::COLOUR)
  112. {
  113. Colourf c0 = ColourToLinearSpace(p0.value.Get<Colourb>());
  114. Colourf c1 = ColourToLinearSpace(p1.value.Get<Colourb>());
  115. Colourf c = c0 * (1.0f - alpha) + c1 * alpha;
  116. return Property{ ColourFromLinearSpace(c), Property::COLOUR };
  117. }
  118. if (p0.unit == Property::TRANSFORM && p1.unit == Property::TRANSFORM)
  119. {
  120. auto& t0 = p0.value.GetReference<TransformPtr>();
  121. auto& t1 = p1.value.GetReference<TransformPtr>();
  122. const auto& prim0 = t0->GetPrimitives();
  123. const auto& prim1 = t1->GetPrimitives();
  124. if (prim0.size() != prim1.size())
  125. {
  126. RMLUI_ERRORMSG("Transform primitives not of same size during interpolation. Were the transforms properly prepared for interpolation?");
  127. return Property{ t0, Property::TRANSFORM };
  128. }
  129. // Build the new, interpolating transform
  130. UniquePtr<Transform> t(new Transform);
  131. t->GetPrimitives().reserve(t0->GetPrimitives().size());
  132. for (size_t i = 0; i < prim0.size(); i++)
  133. {
  134. TransformPrimitive p = prim0[i];
  135. if (!TransformUtilities::InterpolateWith(p, prim1[i], alpha))
  136. {
  137. RMLUI_ERRORMSG("Transform primitives can not be interpolated. Were the transforms properly prepared for interpolation?");
  138. return Property{ t0, Property::TRANSFORM };
  139. }
  140. t->AddPrimitive(p);
  141. }
  142. return Property{ TransformPtr(std::move(t)), Property::TRANSFORM };
  143. }
  144. // Fall back to discrete interpolation for incompatible units.
  145. return alpha < 0.5f ? p0 : p1;
  146. }
  147. enum class PrepareTransformResult { Unchanged = 0, ChangedT0 = 1, ChangedT1 = 2, ChangedT0andT1 = 3, Invalid = 4 };
  148. static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, Element& element)
  149. {
  150. using namespace Transforms;
  151. // Insert or modify primitives such that the two transforms match exactly in both number of and types of primitives.
  152. // Based largely on https://drafts.csswg.org/css-transforms-1/#interpolation-of-transforms
  153. auto& prims0 = t0.GetPrimitives();
  154. auto& prims1 = t1.GetPrimitives();
  155. // Check for trivial case where they contain the same primitives
  156. if (prims0.size() == prims1.size())
  157. {
  158. PrepareTransformResult result = PrepareTransformResult::Unchanged;
  159. bool same_primitives = true;
  160. for (size_t i = 0; i < prims0.size(); i++)
  161. {
  162. auto p0_type = prims0[i].type;
  163. auto p1_type = prims1[i].type;
  164. // See if they are the same or can be converted to a matching generic type.
  165. if (TransformUtilities::TryConvertToMatchingGenericType(prims0[i], prims1[i]))
  166. {
  167. if (prims0[i].type != p0_type)
  168. result = PrepareTransformResult((int)result | (int)PrepareTransformResult::ChangedT0);
  169. if (prims1[i].type != p1_type)
  170. result = PrepareTransformResult((int)result | (int)PrepareTransformResult::ChangedT1);
  171. }
  172. else
  173. {
  174. same_primitives = false;
  175. break;
  176. }
  177. }
  178. if (same_primitives)
  179. return result;
  180. }
  181. if (prims0.size() != prims1.size())
  182. {
  183. // Try to match the smallest set of primitives to the larger set, set missing keys in the small set to identity.
  184. // Requirement: The small set must match types in the same order they appear in the big set.
  185. // Example: (letter indicates type, number represents values)
  186. // big: a0 b0 c0 b1
  187. // ^ ^
  188. // small: b2 b3
  189. // ^ ^
  190. // new small: a1 b2 c1 b3
  191. bool prims0_smallest = (prims0.size() < prims1.size());
  192. auto& small = (prims0_smallest ? prims0 : prims1);
  193. auto& big = (prims0_smallest ? prims1 : prims0);
  194. Vector<size_t> matching_indices; // Indices into 'big' for matching types
  195. matching_indices.reserve(small.size() + 1);
  196. size_t i_big = 0;
  197. bool match_success = true;
  198. bool changed_big = false;
  199. // Iterate through the small set to see if its types fit into the big set
  200. for (size_t i_small = 0; i_small < small.size(); i_small++)
  201. {
  202. match_success = false;
  203. for (; i_big < big.size(); i_big++)
  204. {
  205. auto big_type = big[i_big].type;
  206. if (TransformUtilities::TryConvertToMatchingGenericType(small[i_small], big[i_big]))
  207. {
  208. // They matched exactly or in their more generic form. One or both primitives may have been converted.
  209. match_success = true;
  210. if (big[i_big].type != big_type)
  211. changed_big = true;
  212. }
  213. if (match_success)
  214. {
  215. matching_indices.push_back(i_big);
  216. match_success = true;
  217. i_big += 1;
  218. break;
  219. }
  220. }
  221. if (!match_success)
  222. break;
  223. }
  224. if (match_success)
  225. {
  226. // Success, insert the missing primitives into the small set
  227. matching_indices.push_back(big.size()); // Needed to copy elements behind the last matching primitive
  228. small.reserve(big.size());
  229. size_t i0 = 0;
  230. for (size_t match_index : matching_indices)
  231. {
  232. for (size_t i = i0; i < match_index; i++)
  233. {
  234. TransformPrimitive p = big[i];
  235. TransformUtilities::SetIdentity(p);
  236. small.insert(small.begin() + i, p);
  237. }
  238. // Next value to copy is one-past the matching primitive
  239. i0 = match_index + 1;
  240. }
  241. // The small set has always been changed if we get here, but the big set is only changed
  242. // if one or more of its primitives were converted to a general form.
  243. if (changed_big)
  244. return PrepareTransformResult::ChangedT0andT1;
  245. return (prims0_smallest ? PrepareTransformResult::ChangedT0 : PrepareTransformResult::ChangedT1);
  246. }
  247. }
  248. // If we get here, things get tricky. Need to do full matrix interpolation.
  249. // In short, we decompose the Transforms into translation, rotation, scale, skew and perspective components.
  250. // Then, during update, interpolate these components and combine into a new transform matrix.
  251. if (!CombineAndDecompose(t0, element))
  252. return PrepareTransformResult::Invalid;
  253. if (!CombineAndDecompose(t1, element))
  254. return PrepareTransformResult::Invalid;
  255. return PrepareTransformResult::ChangedT0andT1;
  256. }
  257. static bool PrepareTransforms(Vector<AnimationKey>& keys, Element& element, int start_index)
  258. {
  259. bool result = true;
  260. // Prepare each transform individually.
  261. for (int i = start_index; i < (int)keys.size(); i++)
  262. {
  263. Property& property = keys[i].property;
  264. RMLUI_ASSERT(property.value.GetType() == Variant::TRANSFORMPTR);
  265. if (!property.value.GetReference<TransformPtr>())
  266. property.value = MakeShared<Transform>();
  267. bool must_decompose = false;
  268. Transform& transform = *property.value.GetReference<TransformPtr>();
  269. for (TransformPrimitive& primitive : transform.GetPrimitives())
  270. {
  271. if (!TransformUtilities::PrepareForInterpolation(primitive, element))
  272. {
  273. must_decompose = true;
  274. break;
  275. }
  276. }
  277. if (must_decompose)
  278. result &= CombineAndDecompose(transform, element);
  279. }
  280. if (!result)
  281. return false;
  282. // We don't need to prepare the transforms pairwise if we only have a single key added so far.
  283. if (keys.size() < 2 || start_index < 1)
  284. return true;
  285. // Now, prepare the transforms pair-wise so they can be interpolated.
  286. const int N = (int)keys.size();
  287. int count_iterations = -1;
  288. const int max_iterations = 3 * N;
  289. Vector<bool> dirty_list(N + 1, false);
  290. dirty_list[start_index] = true;
  291. // For each pair of keys, match the transform primitives such that they can be interpolated during animation update
  292. for (int i = start_index; i < N && count_iterations < max_iterations; count_iterations++)
  293. {
  294. if (!dirty_list[i])
  295. {
  296. ++i;
  297. continue;
  298. }
  299. auto& prop0 = keys[i - 1].property;
  300. auto& prop1 = keys[i].property;
  301. if(prop0.unit != Property::TRANSFORM || prop1.unit != Property::TRANSFORM)
  302. return false;
  303. auto& t0 = prop0.value.GetReference<TransformPtr>();
  304. auto& t1 = prop1.value.GetReference<TransformPtr>();
  305. auto prepare_result = PrepareTransformPair(*t0, *t1, element);
  306. if (prepare_result == PrepareTransformResult::Invalid)
  307. return false;
  308. bool changed_t0 = ((int)prepare_result & (int)PrepareTransformResult::ChangedT0);
  309. bool changed_t1 = ((int)prepare_result & (int)PrepareTransformResult::ChangedT1);
  310. dirty_list[i] = false;
  311. dirty_list[i - 1] = dirty_list[i - 1] || changed_t0;
  312. dirty_list[i + 1] = dirty_list[i + 1] || changed_t1;
  313. if (changed_t0 && i > 1)
  314. --i;
  315. else
  316. ++i;
  317. }
  318. // Something has probably gone wrong if we exceeded max_iterations, possibly a bug in PrepareTransformPair()
  319. return (count_iterations < max_iterations);
  320. }
  321. ElementAnimation::ElementAnimation(PropertyId property_id, ElementAnimationOrigin origin, const Property& current_value, Element& element,
  322. double start_world_time, float duration, int num_iterations, bool alternate_direction) :
  323. property_id(property_id),
  324. duration(duration), num_iterations(num_iterations), alternate_direction(alternate_direction), last_update_world_time(start_world_time),
  325. origin(origin)
  326. {
  327. if (!current_value.definition)
  328. {
  329. Log::Message(Log::LT_WARNING, "Property in animation key did not have a definition (while adding key '%s').", current_value.ToString().c_str());
  330. }
  331. InternalAddKey(0.0f, current_value, element, Tween{});
  332. }
  333. bool ElementAnimation::InternalAddKey(float time, const Property& in_property, Element& element, Tween tween)
  334. {
  335. int valid_properties = (Property::NUMBER_LENGTH_PERCENT | Property::ANGLE | Property::COLOUR | Property::TRANSFORM | Property::KEYWORD);
  336. if (!(in_property.unit & valid_properties))
  337. {
  338. Log::Message(Log::LT_WARNING, "Property value '%s' is not a valid target for interpolation.", in_property.ToString().c_str());
  339. return false;
  340. }
  341. keys.emplace_back(time, in_property, tween);
  342. bool result = true;
  343. if (keys.back().property.unit == Property::TRANSFORM)
  344. {
  345. result = PrepareTransforms(keys, element, (int)keys.size() - 1);
  346. }
  347. if (!result)
  348. {
  349. Log::Message(Log::LT_WARNING, "Could not add animation key with property '%s'.", in_property.ToString().c_str());
  350. keys.pop_back();
  351. }
  352. return result;
  353. }
  354. bool ElementAnimation::AddKey(float target_time, const Property & in_property, Element& element, Tween tween, bool extend_duration)
  355. {
  356. if (!IsInitalized())
  357. {
  358. Log::Message(Log::LT_WARNING, "Element animation was not initialized properly, can't add key.");
  359. return false;
  360. }
  361. if (!InternalAddKey(target_time, in_property, element, tween))
  362. {
  363. return false;
  364. }
  365. if (extend_duration)
  366. duration = target_time;
  367. return true;
  368. }
  369. float ElementAnimation::GetInterpolationFactorAndKeys(int* out_key0, int* out_key1) const
  370. {
  371. float t = time_since_iteration_start;
  372. if (reverse_direction)
  373. t = duration - t;
  374. int key0 = -1;
  375. int key1 = -1;
  376. {
  377. for (int i = 0; i < (int)keys.size(); i++)
  378. {
  379. if (keys[i].time >= t)
  380. {
  381. key1 = i;
  382. break;
  383. }
  384. }
  385. if (key1 < 0) key1 = (int)keys.size() - 1;
  386. key0 = (key1 == 0 ? 0 : key1 - 1);
  387. }
  388. RMLUI_ASSERT(key0 >= 0 && key0 < (int)keys.size() && key1 >= 0 && key1 < (int)keys.size());
  389. float alpha = 0.0f;
  390. {
  391. const float t0 = keys[key0].time;
  392. const float t1 = keys[key1].time;
  393. const float eps = 1e-3f;
  394. if (t1 - t0 > eps)
  395. alpha = (t - t0) / (t1 - t0);
  396. alpha = Math::Clamp(alpha, 0.0f, 1.0f);
  397. }
  398. alpha = keys[key1].tween(alpha);
  399. if (out_key0) *out_key0 = key0;
  400. if (out_key1) *out_key1 = key1;
  401. return alpha;
  402. }
  403. Property ElementAnimation::UpdateAndGetProperty(double world_time, Element& element)
  404. {
  405. float dt = float(world_time - last_update_world_time);
  406. if (keys.size() < 2 || animation_complete || dt <= 0.0f)
  407. return Property{};
  408. dt = Math::Min(dt, 0.1f);
  409. last_update_world_time = world_time;
  410. time_since_iteration_start += dt;
  411. if (time_since_iteration_start >= duration)
  412. {
  413. // Next iteration
  414. current_iteration += 1;
  415. if (num_iterations == -1 || (current_iteration >= 0 && current_iteration < num_iterations))
  416. {
  417. time_since_iteration_start -= duration;
  418. if (alternate_direction)
  419. reverse_direction = !reverse_direction;
  420. }
  421. else
  422. {
  423. animation_complete = true;
  424. time_since_iteration_start = duration;
  425. }
  426. }
  427. int key0 = -1;
  428. int key1 = -1;
  429. float alpha = GetInterpolationFactorAndKeys(&key0, &key1);
  430. Property result = InterpolateProperties(keys[key0].property, keys[key1].property, alpha, element, keys[0].property.definition);
  431. return result;
  432. }
  433. } // namespace Rml