Use basegfx to convert angle unit – EasyHack
What is basegfx?
First, what is basegfx, how it is used for converting angle units, and why we should care?
If you look at the list of LibreOffice modules in docs.libreoffice.org, you will see that basegfx is one of the LibreOffice modules. It contains the “algorithms and data types for graphics“, and it provides useful functions for LibreOffice graphics code. We care because using these functions helps us write cleaner code using well tested methods.
In the LibreOffice code related to angles, there are many instances of angle unit conversion. For instance, conversion from radians (rad) to degrees (deg) or vice versa is common. However, currently some of these unit conversions directly divide or multiply the angle values by or in π/180.
Alternatively, a better approach would be using basegfx fTools methods. If you look at include/basegfx/numeric/ftools.hxx in the LibreOffice source code, you will find these methods among others:
deg2rad(). The usage is obvious as the names imply: converting from radians (rad) to degrees (deg), and vice versa.
Consider this expression that converts
fAngle from degrees to radians:
A more understandable form is:
In addition, if you look closely to the function declaration, it is visible that you can pass a multiplier named
template <int DegMultiple=1> constexpr double deg2rad(double v)
To illustrate the usage, there are many interesting applications of this function in the current code with this extra parameter. Consider this old usage of
double fRad = basegfx::deg2rad(nMSORotationAngle / 60000.0)
Now, the new simplified code is:
double fRad = basegfx::deg2rad<60000>(nMSORotationAngle);
You can see some example commits around this idea:
- Use basegfx::deg2rad instead of *0.01745329251994
- Use more basegfx::deg2rad<N> and basegfx::rad2deg<N>
Finding instances for change
This grep search provides some instances of the issue, although not all of the results are related:
git grep -F 3.14 *.cxx
A more restricted search can be:
git grep -F 3.14 *.cxx | grep 180
You can also take a look at EasyHack tdf#145759: Use symbolic constants instead of magic numerical constants.
EasyHacks are a good start for newcomers. This specific improvement is filed as tdf#146479.
Of course, the basegfx module has more interesting classes and functions for doing things beyond the simple angle unit conversion. I will write more about some of other classes and functions inside this LibreOffice module. These are the source folders inside
basegfx/src, which show the different applications of this module:
color numeric polygon raster tuple curve matrix point range tools vector
In the end, if you want to contribute to LibreOffice code by working on this improvement, but you need to know how to get started with LibreOffice development, I suggest you to see our video tutorial: