ElementAnimation.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /*
  2. * This source file is part of libRocket, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://www.librocket.com
  5. *
  6. * Copyright (c) 2018 Michael Ragazzon
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. *
  26. */
  27. #include "precompiled.h"
  28. #include "ElementAnimation.h"
  29. #include "../../Include/Rocket/Core/TransformPrimitive.h"
  30. namespace Rocket {
  31. namespace Core {
  32. static Colourf ColourToLinearSpace(Colourb c)
  33. {
  34. Colourf result;
  35. // Approximate inverse sRGB function
  36. result.red = Math::SquareRoot((float)c.red / 255.f);
  37. result.green = Math::SquareRoot((float)c.green / 255.f);
  38. result.blue = Math::SquareRoot((float)c.blue / 255.f);
  39. result.alpha = (float)c.alpha / 255.f;
  40. return result;
  41. }
  42. static Colourb ColourFromLinearSpace(Colourf c)
  43. {
  44. Colourb result;
  45. result.red = (Rocket::Core::byte)Math::Clamp(c.red*c.red*255.f, 0.0f, 255.f);
  46. result.green = (Rocket::Core::byte)Math::Clamp(c.green*c.green*255.f, 0.0f, 255.f);
  47. result.blue = (Rocket::Core::byte)Math::Clamp(c.blue*c.blue*255.f, 0.0f, 255.f);
  48. result.alpha = (Rocket::Core::byte)Math::Clamp(c.alpha*255.f, 0.0f, 255.f);
  49. return result;
  50. }
  51. static Variant InterpolateValues(const Variant & v0, const Variant & v1, float alpha)
  52. {
  53. auto type0 = v0.GetType();
  54. auto type1 = v1.GetType();
  55. if (type0 != type1)
  56. {
  57. Log::Message(Log::LT_WARNING, "Interpolating properties must be of same unit. Got types: '%c' and '%c'.", type0, type1);
  58. return v0;
  59. }
  60. switch (type0)
  61. {
  62. case Variant::FLOAT:
  63. {
  64. float f0 = v0.Get<float>();
  65. float f1 = v1.Get<float>();
  66. float f = (1.0f - alpha) * f0 + alpha * f1;
  67. return Variant(f);
  68. }
  69. case Variant::COLOURB:
  70. {
  71. Colourf c0 = ColourToLinearSpace(v0.Get<Colourb>());
  72. Colourf c1 = ColourToLinearSpace(v1.Get<Colourb>());
  73. Colourf c = c0 * (1.0f - alpha) + c1 * alpha;
  74. return Variant(ColourFromLinearSpace(c));
  75. }
  76. case Variant::TRANSFORMREF:
  77. {
  78. using namespace Rocket::Core::Transforms;
  79. // Build the new, interpolating transform
  80. auto t = TransformRef{ new Transform };
  81. auto t0 = v0.Get<TransformRef>();
  82. auto t1 = v1.Get<TransformRef>();
  83. const auto& p0 = t0->GetPrimitives();
  84. const auto& p1 = t1->GetPrimitives();
  85. if (p0.size() != p1.size())
  86. {
  87. Log::Message(Log::LT_WARNING, "Transform primitives not of same size during interpolation.");
  88. return Variant{ t0 };
  89. }
  90. for (size_t i = 0; i < p0.size(); i++)
  91. {
  92. Primitive p = p0[i];
  93. if (!p.InterpolateWith(p1[i], alpha))
  94. {
  95. Log::Message(Log::LT_WARNING, "Transform primitives not of same type during interpolation.");
  96. return Variant{ t0 };
  97. }
  98. t->AddPrimitive(p);
  99. }
  100. return Variant(t);
  101. Log::Message(Log::LT_WARNING, "Could not decode transform for interpolation.");
  102. }
  103. }
  104. Log::Message(Log::LT_WARNING, "Currently, only float and color values can be interpolated. Got types of: '%c'.", type0);
  105. return v0;
  106. }
  107. enum class PrepareTransformResult { Unchanged = 0, ChangedT0 = 1, ChangedT1 = 2, ChangedT0andT1 = 3, Invalid = 4 };
  108. static PrepareTransformResult PrepareTransformPair(Transform& t0, Transform& t1, Element& element)
  109. {
  110. using namespace Transforms;
  111. // Insert missing primitives into transform
  112. // See e.g. https://drafts.csswg.org/css-transforms-1/#interpolation-of-transforms for inspiration
  113. auto& prims0 = t0.GetPrimitives();
  114. auto& prims1 = t1.GetPrimitives();
  115. // Check for trivial case where they contain the same primitives
  116. if (prims0.size() == prims1.size())
  117. {
  118. bool same_primitives = true;
  119. for (size_t i = 0; i < prims0.size(); i++)
  120. {
  121. if (prims0[i].primitive.index() != prims1[i].primitive.index())
  122. {
  123. // They are not the same, but see if we can convert them to their more generic form
  124. if(!Primitive::TryConvertToMatchingGenericType(prims0[i], prims1[i]))
  125. {
  126. same_primitives = false;
  127. break;
  128. }
  129. }
  130. }
  131. if (same_primitives)
  132. return PrepareTransformResult::Unchanged;
  133. }
  134. if (prims0.size() != prims1.size())
  135. {
  136. // Try to match the smallest set of primitives to the larger set, set missing keys in the small set to identity.
  137. // Requirement: The small set must match types in the same order they appear in the big set.
  138. // Example: (letter indicates type, number represent values)
  139. // big: a0 b0 c0 b1
  140. // ^ ^
  141. // small: b2 b3
  142. // ^ ^
  143. // new small: a1 b2 c1 b3
  144. bool prims0_smallest = (prims0.size() < prims1.size());
  145. auto& small = (prims0_smallest ? prims0 : prims1);
  146. auto& big = (prims0_smallest ? prims1 : prims0);
  147. std::vector<size_t> matching_indices; // Indices into 'big' for matching types
  148. matching_indices.reserve(small.size() + 1);
  149. size_t i_big = 0;
  150. bool match_success = true;
  151. bool changed_big = false;
  152. // Iterate through the small set to see if its types fit into the big set
  153. for (size_t i_small = 0; i_small < small.size(); i_small++)
  154. {
  155. match_success = false;
  156. auto small_type = small[i_small].primitive.index();
  157. for (; i_big < big.size(); i_big++)
  158. {
  159. auto big_type = big[i_big].primitive.index();
  160. if (small_type == big_type)
  161. {
  162. // Exact match
  163. match_success = true;
  164. }
  165. else if (Primitive::TryConvertToMatchingGenericType(small[i_small], big[i_big]))
  166. {
  167. // They matched in their more generic form, one or both primitives converted
  168. match_success = true;
  169. if (big[i_big].primitive.index() != big_type)
  170. changed_big = true;
  171. }
  172. if (match_success)
  173. {
  174. matching_indices.push_back(i_big);
  175. match_success = true;
  176. i_big += 1;
  177. break;
  178. }
  179. }
  180. if (!match_success)
  181. break;
  182. }
  183. if (match_success)
  184. {
  185. // Success, insert the missing primitives into the small set
  186. matching_indices.push_back(big.size()); // Needed to copy elements behind the last matching primitive
  187. small.reserve(big.size());
  188. size_t i0 = 0;
  189. for (size_t match_index : matching_indices)
  190. {
  191. for (size_t i = i0; i < match_index; i++)
  192. {
  193. Primitive p = big[i];
  194. p.SetIdentity();
  195. small.insert(small.begin() + i, p);
  196. }
  197. // Next value to copy is one-past the matching primitive
  198. i0 = match_index + 1;
  199. }
  200. // The small set has always been changed if we get here, but the big set is only changed
  201. // if one or more of its primitives were converted to a general form.
  202. if (changed_big)
  203. return PrepareTransformResult::ChangedT0andT1;
  204. return (prims0_smallest ? PrepareTransformResult::ChangedT0 : PrepareTransformResult::ChangedT1);
  205. }
  206. }
  207. // If we get here, things get tricky. Need to do full matrix interpolation.
  208. // We resolve the full transform here. This is not entirely correct if the elements box size changes
  209. // during the animation. Ideally, we would resolve it during each iteration.
  210. // For performance: We could also consider breaking up the transforms into their interpolating primitives (translate, rotate, skew, scale) here,
  211. // instead of doing this every animation tick.
  212. for(Transform* t : {&t0, &t1})
  213. {
  214. Matrix4f transform_value = Matrix4f::Identity();
  215. for (const auto& primitive : t->GetPrimitives())
  216. {
  217. Matrix4f m;
  218. if (primitive.ResolveTransform(m, element))
  219. transform_value *= m;
  220. }
  221. t->ClearPrimitives();
  222. t->AddPrimitive({ Matrix3D{transform_value} });
  223. }
  224. return PrepareTransformResult::ChangedT0andT1;
  225. }
  226. static bool PrepareTransforms(std::vector<AnimationKey>& keys, Element& element)
  227. {
  228. for (int i = 1; i < (int)keys.size();)
  229. {
  230. auto& ref0 = keys[i - 1].value.Get<TransformRef>();
  231. auto& ref1 = keys[i].value.Get<TransformRef>();
  232. auto result = PrepareTransformPair(*ref0, *ref1, element);
  233. bool changed_t0 = (result == PrepareTransformResult::ChangedT0 || result == PrepareTransformResult::ChangedT0andT1);
  234. if (changed_t0 && i > 1)
  235. --i;
  236. else
  237. ++i;
  238. }
  239. return true;
  240. }
  241. static bool TryMakeUnitValid(Variant& value)
  242. {
  243. bool result = true;
  244. switch (value.GetType())
  245. {
  246. case Variant::FLOAT:
  247. case Variant::COLOURB:
  248. case Variant::TRANSFORMREF:
  249. break;
  250. default:
  251. {
  252. // Try to convert types to float so they can be interpolated
  253. float f = 0.0f;
  254. result = value.GetInto(f);
  255. if (result) value.Reset(f);
  256. break;
  257. }
  258. }
  259. return result;
  260. }
  261. ElementAnimation::ElementAnimation(const String& property_name, const Property& current_value, float start_world_time, float duration, int num_iterations, bool alternate_direction)
  262. : property_name(property_name), property_unit(current_value.unit), property_specificity(current_value.specificity),
  263. duration(duration), num_iterations(num_iterations), alternate_direction(alternate_direction),
  264. keys({ AnimationKey{0.0f, current_value.value, Tween{}} }),
  265. last_update_world_time(start_world_time), time_since_iteration_start(0.0f), current_iteration(0), reverse_direction(false), animation_complete(false)
  266. {
  267. valid = TryMakeUnitValid(keys.back().value);
  268. }
  269. bool ElementAnimation::AddKey(float time, const Property & property, Element& element, Tween tween)
  270. {
  271. if (property.unit != property_unit || !valid)
  272. return false;
  273. bool result = true;
  274. keys.push_back({ time, property.value, tween });
  275. result = TryMakeUnitValid(keys.back().value);
  276. if (result && property.unit == Property::TRANSFORM)
  277. {
  278. for (auto& primitive : property.value.Get<TransformRef>()->GetPrimitives())
  279. {
  280. if (!primitive.ResolveUnits(element))
  281. result = false;
  282. }
  283. if (result)
  284. result = PrepareTransforms(keys, element);
  285. }
  286. if (!result)
  287. keys.pop_back();
  288. return result;
  289. }
  290. Property ElementAnimation::UpdateAndGetProperty(float world_time)
  291. {
  292. Property result;
  293. //Log::Message(Log::LT_INFO, "Animation it = %d, t_it = %f, rev = %d, dt = %f", current_iteration, time_since_iteration_start, (int)reverse_direction, time - last_update_time);
  294. if (animation_complete || !valid || world_time - last_update_world_time <= 0.0f)
  295. return result;
  296. const float dt = world_time - last_update_world_time;
  297. last_update_world_time = world_time;
  298. time_since_iteration_start += dt;
  299. if (time_since_iteration_start >= duration)
  300. {
  301. // Next iteration
  302. current_iteration += 1;
  303. if (current_iteration < num_iterations || num_iterations == -1)
  304. {
  305. time_since_iteration_start = 0.0f;
  306. if (alternate_direction)
  307. reverse_direction = !reverse_direction;
  308. }
  309. else
  310. {
  311. animation_complete = true;
  312. time_since_iteration_start = duration;
  313. }
  314. }
  315. float t = time_since_iteration_start;
  316. if (reverse_direction)
  317. t = duration - t;
  318. int key0 = -1;
  319. int key1 = -1;
  320. {
  321. for (int i = 0; i < (int)keys.size(); i++)
  322. {
  323. if (keys[i].time >= t)
  324. {
  325. key1 = i;
  326. break;
  327. }
  328. }
  329. if (key1 < 0) key1 = (int)keys.size() - 1;
  330. key0 = (key1 == 0 ? 0 : key1 - 1 );
  331. }
  332. ROCKET_ASSERT(key0 >= 0 && key0 < (int)keys.size() && key1 >= 0 && key1 < (int)keys.size());
  333. float alpha = 0.0f;
  334. {
  335. const float t0 = keys[key0].time;
  336. const float t1 = keys[key1].time;
  337. const float eps = 1e-3f;
  338. if (t1 - t0 > eps)
  339. alpha = (t - t0) / (t1 - t0);
  340. }
  341. alpha = keys[key1].tween(alpha);
  342. result.unit = property_unit;
  343. result.specificity = property_specificity;
  344. result.value = InterpolateValues(keys[key0].value, keys[key1].value, alpha);
  345. return result;
  346. }
  347. }
  348. }