ElementAnimation.cpp 16 KB

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