The site uses cookies that you may not want. Continued use means acceptance. For more information see our privacy policy.

Fun with Context Free

Math is a tool that creates order and chaos in equal (or was it inequal?) measure.

Context Free Art is a simple art-generation context-free language that uses recursion (among other things) to generate images (and videos). I recently saw a post about it, and I decided to try it out. Then I found a folder in my files from 2013 where I had previously come across it and forgotten all about it.

While more suited to the abstract, it’s possible to create more traditional art with it, as seen in two of the four examples at the bottom.

Here is a sample input to the program:

// Sample input
// two slashes make a comment

// command to build:
// cfdg -s 1920x1080 -m 1000000 sample.cfdg sample.png

// cfdg the command
// -s set size to 1080p
// -m set the maximum number of shapes; helps in case of too much recursion
// [file].cfdg the input file
// [file].png the output image

// Required to kick things off.
startshape Sample

// Make a default background color (random)
CF::Background = [b rand(-0.5,-0.25) sat rand(0.25,0.75) h randint(360)]
// b is brightness; sat is saturation; h is hue

shape Sample {
    SQUARE [s 100 x -200]
    CIRCLE [s 100]
    TRIANGLE [s 100 x 200]

// s is size; x is horizontal position

There are three basic shapes available. Can you guess what they are?

From left, on a pink background: a black square, a black circle, and a black triangle.

And you can make your own shapes, using path declarations:

path ZA {
    MOVETO(-0.5, 0)
    LINETO(0, 1)
    LINETO(0.5, 0)
    ARCTO(-0.5, 0, -1)
    // STROKE()[]
    FILL() []

This example path creates a piece of pizza! Notice it has STROKE commented out. If you want, you can make outlined shapes using that.

From left, on a brown background: a white pizza slice shape, a black pizza slice outline, and a white pizza slice shape with a black outline.

Github: MtnViewJohn: context-free: Wiki has most of the details on how to use the tool, though you can also look at the gallery of the official website (linked above), where users have provided samples that include their source code.

Anyway, just a short writeup. Here’s some pictures I made with it:

On a green background, a cone-looking tornado kind of thing with colors shifting from green to yellow to pink to purple.
A misshapen earth-like figure with water, land, and clouds, seen on a space-like background.
A sky with clouds and sun above dirt filled with plants and a few trees.
A psychedelic swirl of green, yellow, orange, red, pink, purple, and blue.

Messing with Godot

My early experience in working on a toy platformer game.

I recently downloaded Godot, a game engine and game development environment. I never did much with games, so I figured I might mess about. So far I’ve been playing around with the 2D stuff, something that could be a platformer-style game.

Godot does a decent job of making concepts clear, though as with any new effort, searching is your friend. Most hurdles have been in figuring out the math to use for custom physics, and even there the engine provides a lot of the basics.

One of the hardest challenges in any program is keeping organized and picking up the right way to implement things. There are places I know I should use custom signals, but I don’t quite understand exactly how to wire them up the right way, so I’m relying on direct calls. My tile map places overlapping tiles. Or places where I know I should be processing velocity changes in the frame process function, but I’m modifying the velocity directly, which means I have to make sure it doesn’t get eaten by a collision.

Eaten by a collision? If you run into a wall, that wall eats your velocity in the direction it opposes. Godot provides collision checking which you can use in custom physics, but it’s up to you to decide how to handle collisions because you might want to bounce, or some collisions might break blocks or teleport you or whatever you want them to do. In my case, the collisions should eat the velocity:

func collide_normal(vel, nnorm):
    var out_vel = Vector2(vel.x, vel.y)
    var dot_product = vel.x * nnorm.x + vel.y * nnorm.y
    if sign(vel.x) != sign(nnorm.x):
        out_vel.x -= dot_product * nnorm.x
    if sign(vel.y) != sign(nnorm.y):
        out_vel.y -= dot_product * nnorm.y

    return out_vel

This function takes a velocity (with an X component and a Y component for how much the object moves frame-to-frame, which together also tells you what direction, like the slope of a line) and a normal vector. A normal vector also has an X and a Y, but if you remember the unit circle from trigonometry, it’s normalized so that it has a length of one, and it points away from the face of an object.

Given those two components, the function negates the velocity that is pointed against the given normal vector. In my case it also has two conditional checks that are used in case either of the components happen to agree in sign (same as direction). Without those, the function would just as happily negate the part of a velocity that points the same way as the normal vector.

But that’s the kind of thing you have to do if you’re poking around and not taking time to do it properly inside the frame process function. Otherwise the bouncy spring you added will sometimes behave like a wall, if the signal of your collision with it happens to come right before the frame process checks if you collided with anything and decides to cancel the bounce.

One of the other things I’m considering is experimenting with a “ghost” player. Godot has its own built-in physics, which is usually applied to inanimate objects, but not to controlled objects and, depending, on animate enemies. But it looks like there are times that it might be handy to ride on the built-in physics, so I believe I can create an invisible player surrogate that will respond to the built-in physics, and for limited uses that might save some code and allow for cool things with limited effort.

I haven’t tried to do any fancy graphics yet (e.g., animations and particles), nor tried anything in 3D, but it’s still fun to mess around with my bouncy springs and gravity fields.

Numerical Step Function in Python

Technical article about creating an interval/range in Python.

The classic range() (and in 2.* series, xrange()) is useful for getting an iterator of numbers. Its full signature is: range(start, stop[, step]).

So you can do, e.g., range(5, 10) = [5, 6, 7, 8, 9].

Or you can do, e.g., range(6, 13, 3) = [6, 9, 12].

But as far as I know there’s not an easy, built-in way to iterate over a range-like set of integers defined both by the range and a number of parts desired.

An example: you want five evenly-distributed numbers starting with 1 and ending with 10. So something like [3, 5, 6, 8, 10].

In my case, I had two similar use-cases. The first was the example above: a semi-arbitrary set of values in a range. I didn’t need to strictly include the endpoints in the values, but wanted a decent distribution of the values between start and end.

The second case was a little different, in that I wanted the range to always include the ends (it was a case of covering a whole range), but I also wanted to know how much each “step” over the range amounted to.

In the naïve version of this case, you don’t need the magnitude, as you could cheat and throw an extra piece in to account for slight differences (e.g., 11 / 3 => 1, 4, 7, 10 with the last piece being 10 through 11).

But there’s a nice way to evenly distribute the extra pieces: using rounding of the fractional value to distribute the extras.


10 / 4 = 2.5
0 * 2.5 = 0.0
1 * 2.5 = 2.5; round(2.5) = 2
2 * 2.5 = 5.0
3 * 2.5 = 7.5; round(7.5) = 8
[0, 2, 5, 8]

(In Python, round(number[, ndigits]) of n.5 goes to the even side (when using ndigits=0 or with a single argument).)

In this case, the caller could buffer the previous value and calculate the gap/step itself, but this is Python, so we might as well give it a mode to get that itself.

Without further ado, this is what I came up with:

def equal_parts(start, end, parts, include_step=False):
    part_size = (end - start) / float(parts)
    for i in range(parts):
        part = start + round(part_size * i)
        step = start + round(part_size * (i + 1)) - part
        if include_step:
            yield (part, step)
            yield chunk

It’s messier than it needs to be, due to its dual-use nature. It’s arguably cleaner to have a second function that would handle the include_step=False case:

def equal_parts_only(start, end, parts):
    for part, step in equal_parts(start, end, parts):
        yield step + part

That function would remove the conditional business at the end of the original equal_parts:

def equal_parts(start, end, parts):
    part_size = (end - start) / float(parts)
    for i in range(parts):
        part = start + round(part_size * i)
        step = start + round(part_size * (i + 1)) - part
        yield (part, step)

In the stepless version, it’s got another nice property: what if you do equal_parts(0, 10, 11)? You get: [1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 10]. That’s a nice property: getting more parts than integers in the range.

I wrote a GIMP plugin to create stepped (or random) gaussian blurs on an image. The stepless version lets me create the set of blur levels, while the step-including version lets me properly select (mostly-)even parts of the image.

Here’s an image that used this plugin containing a dual use of this function: Sample image of gaussian blur in sections

If anyone wants a copy of the plugin, let me know and I’ll put it on Github or such.