"""
Edward Dale
2005-12-19
Computer Graphics 2
Ray Tracer
Copyright (c) 2005, Edward DaleAll rights reserved.Redistribution and use in source and binary forms, with or without modification,are permitted provided that the following conditions are met:* Redistributions of source code must retain the above copyright notice, this  list of conditions and the following disclaimer.* Redistributions in binary form must reproduce the above copyright notice,  this list of conditions and the following disclaimer in the documentation  and/or other materials provided with the distribution.* Neither the name of Edward Dale nor the names of its contributors  may be used to endorse or promote products derived from this software  without specific prior written permission.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ANDCONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OFMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORSBE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, ORCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENTOF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; ORBUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OFLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDINGNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."""

from math import pi
from primitives import Color, Ray

class PhongShader:
    """
    A phong shader.
    """

    def __init__(self, scene):
        """
        Give the shader a copy of the scene to get lighting information.
        """
        self.scene=scene

    def getColor(self, object, normal, isect):
        """
        Get the color of the intersection point.
        """
        # There's a bit of ambient light
        ambient=object.lighting.ambientK * object.lighting.ambient * self.scene.ambient.ambient

        # Get the diffuse and specular components from each light.        
        diffsum = Color(0,0,0)
        specsum = Color(0,0,0)
        for light in self.scene.lights:
            lightV = light.pos-isect
            lightDist = abs(lightV)
            S = lightV.normalize()

            shadowRay =  Ray(origin=isect, direction=lightV)
            shadow = self.scene.fireRay( shadowRay, object )

            # Only count the light if it can be seen
            if S.angle(normal) < pi and (shadow == None ):
                diffdot = S * normal
                diffillum = light.lighting.diffuse * object.lighting.diffuse
                diffsum += diffillum * diffdot
    
                V = (self.scene.eye-isect).normalize()
                R = S.reflect(normal)
                if V.angle(R) < pi:
                    specdot = R * V
                    specillum = light.lighting.specular * object.lighting.specular
                    specsum += specillum * specdot**object.lighting.exponent

        sum = ambient+object.lighting.diffuseK*diffsum + object.lighting.diffuseK*specsum
        return sum

class PhongBlinnShader:
    """
    A phong-blinn shader.
    """
    
    def __init__(self, scene):
        """
        The shader needs the scene to get light information.
        """
        self.scene=scene

    def getColor(self, object, normal, isect):
        """
        Calculate the color of the intersection.
        """
        ambient=object.lighting.ambientK * object.lighting.ambient * self.scene.ambient.ambient
        
        diffsum = Color(0,0,0)
        specsum = Color(0,0,0)
        for light in self.scene.lights:
            lightV = light.pos-isect
            lightDist = abs(lightV)
            S = lightV.normalize()

            shadowRay =  Ray(origin=isect, direction=lightV)
            shadow = self.scene.fireRay( shadowRay, object )

            # Only count the light if it can be seen
            if S.angle(normal) < pi and (shadow == None ):
                diffdot = S * normal
                diffillum = light.lighting.diffuse * object.lighting.diffuse
                diffsum += diffillum * diffdot

                # Use the halfway vector for the blinn calculation.
                V = (self.scene.eye-isect).normalize()
                H = ((V+S)/2).normalize()
                
                if H.angle(normal) < pi:
                    specdot = H * normal
                    specillum = light.lighting.specular * object.lighting.specular
                    specsum += specillum * specdot**object.lighting.exponent

        sum = ambient+object.lighting.diffuseK*diffsum + object.lighting.diffuseK*specsum
        return sum

class FlatShader:
    """
    A simple flat shader.  Uses only ambient color.
    """
    
    def getColor(self, object, normal, isect):
        """
        Return the ambient color of the object.
        """
        return object.lighting.ambient

def getShader(name, scene):
    """
    A factory method to get a shader from a string.
    
    >>> scene = None
    >>> shader = getShader("flat", scene)
    >>> isinstance(shader, FlatShader)
    True
    >>> shader = getShader("phong", scene)
    >>> isinstance(shader, PhongShader)
    True
    >>> shader = getShader("blinn", scene)
    >>> isinstance(shader, PhongBlinnShader)
    True
    """
    if name == "flat":
        return FlatShader()
    elif name == "phong":
        return PhongShader(scene)
    elif name == "blinn":
        return PhongBlinnShader(scene)

def _test():
    """
    Run the unit tests for each method using the doctest module.
    """
    import doctest
    doctest.testmod()

# If the module's being run directly, then run the unit tests.
if __name__ == "__main__":
    _test()
