2016-03-30 Turtle uncloaking

I know, I know. I was supposed to write something about the horizontal layout. But this will have to wait, since I have a sexier thing to talk about. After some hiatus from Logeox, my turtle is finally visible! And here’s the proof:

turtle-screenshot-01.png

I’m so excited that it works!

Not so much about how it worked, though. Turns out that I really, deeply suck at geometry. Like, I’d probably fail any reasonable test in analytical geometry. (School tests aren’t reasonable – after all, I passed most of them in my life, though not as well as I’d wish. I mean a real test, like writing a simple turtle graphic program in whatever language on whatever platform…)

Here’s the synopsis of what I did.

  1. First, I made the bitmap. It is ugly as I don’t know what, but it has one big advantage: it’s simple, and making it (in TikZ, of course;-)) took me a few minutes.
  2. And the thing is, the ugliness does not matter at all, since it is easily replaceable – it is saved in res/drawable.
  3. To dig it from there, I needed a Bitmap variable, and a BitmapFactory which took the png from resources and made it into a bitmap object. (Just like in a Java joke – good!)
  4. Putting it on a canvas is also easy – just do canvas.drawBitmap. The tricky part (and the one I messed up a few times) is putting it in the right place.
  5. You won’t believe it, but the thing used to putting a bitmap in the right spot on the canvas is a Matrix. You want to know what it is? Morpheus cannot tell you, but any decent book on linear algebra can. A matrix is a special kind of geometrical transformation. Nothing less, nothing more.
  6. And here’s the tricky part: composing transformations (even linear ones) in a wrong order won’t work. IOW, multiplying matrices is not commutative. So you have to get it right. There’s more than one way to get it right. The one I used (after a couple of wrong attempts) is this: first translate so that the midpoint is in the origin, then rotate, then translate to the turtle’s position. Fortunately, after my code finally stopped crashing (say hello to our good ol’friend NullPointerException!), figuring this out took me mere minutes. Maybe I suck at geometrical intuition, but I know how math works, and you can’t beat that.
  7. The next ingredient for today’s success was realizing that now I have to drawingView.invalidate() not only after moving the turtle, but also after turning it.
  8. And the last thing was a small touch: changing the line cap style, so that joining line endpoints looks good.

OK, so what’s next? If you look at the current state of the code, you’ll notice that I’ll need to move paint to the turtle object (probably). Then I’ll probably think a bit about that horizontal layout, and add some controls (e.g. for the penup/pendown operations). And then we’ll see.

CategoryEnglish, CategoryBlog, CategoryMakeYourselfKnown