The Ray Tracer Challenge: Gradient pattern is not a gradient

Hello @jamis and everyone,

I’ve implemented the gradient pattern as described in the book and it gives me this output:

The code for pattern_at (I’ve renamed it to ColorAt) is the following:

func (gp *GradientPattern) ColorAt(point math.Point) math.Color {
	distance := gp.ColorB.Subtract(gp.ColorA)
	fraction := point.X - gomath.Floor(point.X)

	return gp.ColorA.Add(distance.Mul(fraction))
}

As you can see it is not exactly a gradient, but the output makes sense to me.
Our spheres are centered at 0, 0, 0 in object space and at x = 0 the fraction evaluates to 0, which in turn means that we just return colorA.

But I highly suspect that this function is supposed to return an image of a smooth gradient from A to B.
I’m going mildly insane about this issue and if anyone got any advice I would greatly appreciate that.

Thanks! :slight_smile:

The issue here is that your pattern space needs to be translated and scaled so that the [0,1] range fits the object you’re applying it to. If your sphere has radius 1, and is centered at (0,0), then the pattern (by default) will be covering [-1, 1] (from -x to +x), which means the gradient will be doubled (running once from [-1,0] and again from [0,1]). If you scale the pattern space by 2 (so the gradient runs from [0,2]) and then translate it by -x (so it runs from [-1,1]), it should look more like what you’re expecting.

Hopefully that helps! If you’d like me to restate/clarify anything, let me know.

1 Like

Thank you so much, that indeed fixes it!

I am facepalming really hard right now, because I already tried scaling by 2 and translating by -1, but I never thought of having to combine those two…

Thanks again for your help and for writing that book, having a blast with it!

1 Like