SICP: Centering Frames (Picture Language Bonus Exercise)
As an addition to my other picture language posts, this post shows you how to center arbitrary frames in the viewport (or actually, w.r.t. any other arbitrary frame).
Before I did this, my drawings sat inconveniently in the viewport window, uncentered:
Let us fix that.
In order to center a frame, all we need to do is place it in the right position, i.e. we simply need to manipulate it’s origin vector. Here is the important relation:
When the centers of the frame and reference-frame align,
vector(reference-frame's center)
= vector(origin) + relative_vector(frame's center)
Since the picture language already provides the capabilities to talk in terms of vectors, we can formulate the computation quite easily:
; to center a frame w.r.t another, we calculate it's origin
; vector based on the above relation.
(define (centered frame reference-frame)
(define (relative-center frame)
(add-vect (scale-vect 0.5 (edge1-frame frame))
(scale-vect 0.5 (edge2-frame frame))))
(let ((actual-center (add-vect (origin-frame reference-frame)
(relative-center reference-frame)))
(relative-center (relative-center frame)))
(make-frame (sub-vect actual-center relative-center)
(edge1-frame frame)
(edge2-frame frame))))
If you have followed along with the picture language section, you should understand what I mean by relative and absolute vector.
Now, we can easily center our frames like in the image below.
Above: An arbitrary frame centered w.r.t. the viewport frame.
P.S. It took me a while to discover the relation for arbitrary frames. Initially, I had only figured out how to center an arbitrary frame in a rectangular one. I struggled during the first attempt (trying to find a more generalisable solution). After a fews days’ gap, I sat down and the answer came almost immediately with almost no effort.
This is what draws me to problem solving and to software. The only limits are one’s own mind. With one perspective, we can generalize entire classes of ideas. With another, we can elaborate a single idea unto eternity. All in all, there is an element of creativity involved in these endeavours that I feel can be used to brings us closer to understanding creation, ourselves and the Intelligence behind it all.