--- This is how we do a 'for' loop in Haskell.
--- No, seriously.
-cubes :: Grid -> [[[Cube]]]
-cubes g
- | fvs == [[[]]] = [[[]]]
- | head fvs == [[]] = [[[]]]
- | otherwise =
- [[[ Cube (h g) i j k (make_values fvs i j k) | i <- [0..xsize]]
- | j <- [0..ysize]]
- | k <- [0..zsize]]
+
+-- | Takes a grid and a position as an argument and returns the cube
+-- centered on that position. If there is no cube there (i.e. the
+-- position is outside of the grid), it will throw an error.
+cube_at :: Grid -> Int -> Int -> Int -> Cube
+cube_at g i j k
+ | i < 0 = error "i < 0 in cube_at"
+ | i >= xsize = error "i >= xsize in cube_at"
+ | j < 0 = error "j < 0 in cube_at"
+ | j >= ysize = error "j >= ysize in cube_at"
+ | k < 0 = error "k < 0 in cube_at"
+ | k >= zsize = error "k >= zsize in cube_at"
+ | otherwise = (cube_grid g) ! (i,j,k)
+ where
+ fvs = function_values g
+ (xsize, ysize, zsize) = dims fvs
+
+-- The first cube along any axis covers (-h/2, h/2). The second
+-- covers (h/2, 3h/2). The third, (3h/2, 5h/2), and so on.
+--
+-- We translate the (x,y,z) coordinates forward by 'h/2' so that the
+-- first covers (0, h), the second covers (h, 2h), etc. This makes
+-- it easy to figure out which cube contains the given point.
+calculate_containing_cube_coordinate :: Grid -> Double -> Int
+calculate_containing_cube_coordinate g coord
+ -- Don't use a cube on the boundary if we can help it. This
+ -- returns cube #1 if we would have returned cube #0 and cube #1
+ -- exists.
+ | coord < offset = 0
+ | coord == offset && (xsize > 1 && ysize > 1 && zsize > 1) = 1
+ | otherwise = (ceiling ( (coord + offset) / cube_width )) - 1