"""
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,floor
from primitives import Color, Ray
from cgkit import noise
from PIL import Image

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

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

    def getColor(self, object, normal, isect):
        """
        Get the color of the intersection point.
        """
        if self.shader is not None:
            color=self.shader.getColor(object, normal, isect)
            ambcolor=color
            diffcolor=color
            speccolor=color
        else:
            ambcolor=object.lighting.ambient
            diffcolor=object.lighting.diffuse
            speccolor=object.lighting.specular

        # There's a bit of ambient light
        ambient=object.lighting.ambientK * ambcolor * 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 * diffcolor
                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 * speccolor
                    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, shader=None):
        """
        The shader needs the scene to get light information.
        """
        self.scene=scene
        self.shader=shader

    def getColor(self, object, normal, isect):
        """
        Calculate the color of the intersection.
        """
        if self.shader is not None:
            color=self.shader.getColor(object, normal, isect)
            ambcolor=color
            diffcolor=color
            speccolor=color
        else:
            ambcolor=object.lighting.ambient
            diffcolor=object.lighting.diffuse
            speccolor=object.lighting.specular

        ambient=object.lighting.ambientK * ambcolor * 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 * diffcolor
                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 * speccolor
                    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

class NoiseShader:
    """
    A shader that uses the perlin noise function from cgkit.
    http://cgkit.sourceforge.net/doc2/module-cgkit.noise.html
    """

    def getColor(self, object, normal, isect):
        """
        Gets the color from the noise function.  Only uses isect.
        """
        return object.lighting.ambient*noise.noise(isect)

class TurbulenceShader:
    """
    A shader that uses the turbulence function from cgkit.
    The octaves parameter gets passed straight to the turbulence function.
    http://cgkit.sourceforge.net/doc2/module-cgkit.noise.html
    """
    def __init__(self, octaves):
        self.octaves=octaves

    def getColor(self, object, normal, isect):
        """
        Gets the color from the turbulence function.  Uses isect and octaves.
        """
        return object.lighting.ambient*noise.turbulence(isect, self.octaves)

class Texture:
    """
    A shader to texture map an object.
    """
    
    def __init__(self, texturefilename):
        """
        Creates the texture shader and loads the texture image.
        """
        im=Image.open(texturefilename)
        self.texture=list(im.getdata())
        self.texsize=im.size
    
    def getColor(self, object, normal, isect):
        """
        Retrieves the color from the texture image.
        """
        u,v=object.project(isect)
    
        r=int(floor(self.texsize[1]*v))#h
        c=int(floor(self.texsize[0]*u))#w
        idx=r*self.texsize[0]+c
    
        col=self.texture[idx]
        return Color(col[0]/255.0,col[1]/255.0,col[2]/255.0)
                

class CheckerBoardShader:
    """
    A procedural shadere that draws a checkerboard.
    Uses the project function in each primitive.
    """

    def __init__(self, scene, rfreq=2, cfreq=2, color1=None, color2=None):
        """
        Initializes the checkerboard with the given parameters.
        rfreq and cfreq determine how many rows and columns.
        color1 and color2 determine what color the squares will be.  If
        either are not given, the ambient color of the object is used.
        """
        self.scene=scene
        self.rfreq=rfreq
        self.cfreq=cfreq
        self.color1=color1
        self.color2=color2
        
    def getColor(self, object, normal, isect):
        """        
        Uses the project function of each primitive to determine where
        on a checkerboard the intersection lies.
        """
        u,v=object.project(isect)

        # Scale up by the frequency
        row = u*self.rfreq
        col = v*self.cfreq
        
        # Determine which color to use
        if (floor(row)%2 == floor(col)%2):
            if not self.color1:
                return object.lighting.ambient
            else:
                return self.color1
        else:
            if not self.color2:
                return object.lighting.ambient
            else:
                return self.color2

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()
