Good afternoon! Let's write a toy UI library. We begin by writing a few helper functions that will invariably prove useful to us later. We will be dealing with a lot of rectangular regions on the screen, so it makes sense to start by defining a rectangle structure and write some code to manipulate it. typedef struct Rectangle { int l, r, t, b; } Rectangle; My preferred method of encoding rectangles is as a quartet comprising the left, right, top and bottom sides. Here are the helper functions we'll implement that deal with rectangles. Rectangle RectangleMake(int l, int r, int t, int b); // Initialise a Rectangle structure with the provided values. bool RectangleValid(Rectangle a); // Returns true if the rectangle is 'valid', which I define to mean it has positive width and height. Rectangle RectangleIntersection(Rectangle a, Rectangle b); // Compute the intersection of the rectangles, i.e. the biggest rectangle that fits into both. If the rectangles don't overlap, an invalid rectangle is returned (as per RectangleValid). Rectangle RectangleBounding(Rectangle a, Rectangle b); // Compute the smallest rectangle containing both of the input rectangles. bool RectangleEquals(Rectangle a, Rectangle b); // Returns true if all sides are equal. bool RectangleContains(Rectangle a, int x, int y); // Returns true if the pixel with its top-left at the given coordinate is contained inside the rectangle. If you're following along with the tutorial, I recommend trying to implement these yourself, and then comparing with my implementation. Here's a few to get you started. Rectangle RectangleIntersection(Rectangle a, Rectangle b) { if (a.l < b.l) a.l = b.l; if (a.t < b.t) a.t = b.t; if (a.r > b.r) a.r = b.r; if (a.b > b.b) a.b = b.b; return a; } bool RectangleContains(Rectangle a, int x, int y) { // (x, y) gives the top-left corner of the pixel. // Therefore we use strict inequalities when comparing against the right and bottom sides of the rectangle. return a.l <= x && a.r > x && a.t...
First seen: 2025-12-22 19:35
Last seen: 2025-12-22 21:36