Discussing the article: "Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 6): Curves and Adaptive Flattening"

Check out the new article: Creating a Cairo-Inspired Graphics Library for MetaTrader 5 (Part 6): Curves and Adaptive Flattening.

This part introduces cubic Bézier curves and a quadratic verb, flattened on append by recursive midpoint splitting (De Casteljau). A conservative flatness test sums distances of control points to the chord and stops within a pixel-based tolerance, adapting detail to curvature. The design keeps downstream code intact while giving you efficient, scale-independent curve quality.

A vector graphics library that can only draw straight lines has a fundamental limitation: no matter how capable its rasterizer is, every curved shape must first be approximated by a polygon. A circle becomes a collection of short segments, and its apparent smoothness depends entirely on how many segments were chosen.

By the end of Part 5, our engine could fill any outline it was given. Edges were smooth at any angle, alpha compositing was correct, and two fill rules allowed shapes to contain holes. That is a capable renderer, but it still cannot draw a curve.

Every "circle" in the last three demos was a polygon whose vertices the demo computed by hand. That made a useful point at the time — the rasterizer cannot tell a 96-sided polygon from a circle, and does not want to — but it is not a library feature. You cannot ask this library for a curve. You can only ask it for a great many short straight lines and hope you asked for the right number of them.

In this part, we add the real thing: CurveTo, the cubic Bézier. The curve itself is four points and some averaging, and on its own it would be a short article. What makes it a long one is the question every vector renderer has to answer, and which has no obvious right answer:

A curve is smooth and infinitely detailed. Our rasterizer eats straight segments. How many segments, and where?

Too few and a circle looks like a stop sign. Too many and you spend time on detail that does not survive being drawn. Pick a number in the middle and you are wrong in both directions at once, because the same number has to serve a four-pixel corner radius and a four-hundred-pixel arc in the same window.

The answer is one of the most satisfying algorithms in computer graphics. It is about thirty lines long and decades old: Paul de Casteljau developed the underlying subdivision method while working at Citroën in 1959, and its central idea remains just as useful today.

Author: Sandro Begashvili