I am back to writing a ray tracer in Swift for my own education. I just did a vec3 class. My current practice is directions, locations, and RGB colors are all vec3. This is mainly because I like that in glsl. I'm going with Double because I am not trying to be very fast here for now. Swift has nice syntax for this. All lines from the file are here. Any suggestions appreciated. Next on the list is a class for ray-intersectable surfaces.

// implicit type inference. Swift when in doubt assumes Double

struct vec3 {

var x = 0.0, y = 0.0, z = 0.0

}

func * (left: Double, right: vec3) -> vec3 {

return vec3(x: left * right.x, y: left * right.y, z: left * right.z)

}

func / (left: Double, right: vec3) -> vec3 {

return vec3(x: left / right.x, y: left / right.y, z: left / right.z)

}

func * (left: vec3, right: Double) -> vec3 {

return vec3(x: left.x * right, y: left.y * right, z: left.z * right)

}

func / (left: vec3, right: Double) -> vec3 {

return vec3(x: left.x / right, y: left.y / right, z: left.z / right)

}

func + (left: vec3, right: vec3) -> vec3 {

return vec3(x: left.x + right.x, y: left.y + right.y, z: left.z + right.z)

}

func - (left: vec3, right: vec3) -> vec3 {

return vec3(x: left.x - right.x, y: left.y - right.y, z: left.z - right.z)

}

func * (left: vec3, right: vec3) -> vec3 {

return vec3(x: left.x * right.x, y: left.y * right.y, z: left.z * right.z)

}

func / (left: vec3, right: vec3) -> vec3 {

return vec3(x: left.x / right.x, y: left.y / right.y, z: left.z / right.z)

}

func max(v: vec3) -> Double {

if v.x > v.y && v.x > v.z {

return v.x

}

else if v.y > v.x && v.y > v.z {

return v.y

}

else {

return v.z

}

}

func min(v: vec3) -> Double {

if v.x < v.y && v.x < v.z {

return v.x

}

else if v.y < v.x && v.y < v.z {

return v.y

}

else {

return v.z

}

}

func dot (left: vec3, right: vec3) -> Double {

return left.x * right.x + left.y * right.y + left.z * right.z

}

func cross (left: vec3, right: vec3) -> vec3 {

return vec3(x: left.y * right.z - left.z * right.y, y: left.z * right.x - left.z * right.x, z: left.x * right.y - left.y * right.x)

}

## No comments:

Post a Comment