Browse Source

Math: Add SnapToPixelGrid

Michael Ragazzon 5 years ago
parent
commit
a13e54cf1b
2 changed files with 27 additions and 0 deletions
  1. 12 0
      Include/RmlUi/Core/Math.h
  2. 15 0
      Source/Core/Math.cpp

+ 12 - 0
Include/RmlUi/Core/Math.h

@@ -33,6 +33,9 @@
 
 namespace Rml {
 
+template <typename Type> class Vector2;
+using Vector2f = Vector2< float >;
+
 namespace Math {
 
 // The constant PI.
@@ -164,6 +167,15 @@ RMLUICORE_API int RoundDownToInteger(float value);
 /// @return The truncated value as a signed integer.
 RMLUICORE_API int RealToInteger(float value);
 
+/// Round the position and width of a line segment to the pixel grid while minimizing movement of the edges.
+/// @param[inout] x The position, which will use normal rounding.
+/// @param[inout] width The width, which is rounded such that movement of the right edge is minimized.
+RMLUICORE_API void SnapToPixelGrid(float& x, float& width);
+/// Round the position and size of a rectangle to the pixel grid while minimizing movement of the edges.
+/// @param[inout] position The position, which will use normal rounding.
+/// @param[inout] size The size, which is rounded such that movement of the right and bottom edges is minimized.
+RMLUICORE_API void SnapToPixelGrid(Vector2f& position, Vector2f& size);
+
 /// Converts a number to the nearest power of two, rounding up if necessary.
 /// @param[in] value The value to convert to a power-of-two.
 /// @return The smallest power of two that is as least as big as the input value.

+ 15 - 0
Source/Core/Math.cpp

@@ -27,6 +27,7 @@
  */
 
 #include "../../Include/RmlUi/Core/Math.h"
+#include "../../Include/RmlUi/Core/Types.h"
 #include <time.h>
 #include <math.h>
 #include <stdlib.h>
@@ -163,6 +164,20 @@ RMLUICORE_API int RealToInteger(float value)
 	return int(value);
 }
 
+RMLUICORE_API void SnapToPixelGrid(float& offset, float& width)
+{
+	const float rounded_offset = Math::RoundFloat(offset);
+	width = Math::RoundFloat(offset + width) - rounded_offset;
+	offset = rounded_offset;
+}
+
+RMLUICORE_API void SnapToPixelGrid(Vector2f& position, Vector2f& size)
+{
+	const Vector2f rounded_position = position.Round();
+	size = (position + size).Round() - rounded_position;
+	position = rounded_position;
+}
+
 // Converts the given number to a power of two, rounding up if necessary.
 RMLUICORE_API int ToPowerOfTwo(int number)
 {