
Shadoka
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!
Marked As Solved

jamis
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.
Popular Prag Prog topics










Other popular topics










Latest in PragProg
Latest (all)
Categories:
Popular Portals
- /elixir
- /opensuse
- /rust
- /kotlin
- /ruby
- /erlang
- /python
- /clojure
- /react
- /quarkus
- /go
- /vapor
- /v
- /react-native
- /wasm
- /django
- /security
- /nodejs
- /centos
- /rails
- /haskell
- /fable
- /gleam
- /js
- /swift
- /deno
- /assemblyscript
- /tailwind
- /laravel
- /symfony
- /phoenix
- /crystal
- /typescript
- /debian
- /adonisjs
- /julia
- /arch-linux
- /svelte
- /spring
- /flutter
- /preact
- /c-plus-plus
- /actix
- /java
- /angular
- /ocaml
- /zig
- /kubuntu
- /scala
- /zotonic
- /vim
- /rocky
- /lisp
- /keyboards
- /html
- /nim
- /emacs
- /vuejs
- /elm
- /nerves