// --------------------------------------------------------------------
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// --------------------------------------------------------------------

package tinylib.shaders;

import flash.geom.Vector3D;
import flash.geom.Matrix3D;
import flash.display3D.textures.Texture;

/**
  Phong Shader using texture
**/

class PhongShaderUV extends hxsl.Shader {
  static public var id:String = "PhongShaderUV";
  static var SRC = {
    include( 'tinylib/shaders/srcWithUV.hxsl' );
    var position:Float3;
    var normal:Float3;
    var tuv:Float2;
    include( 'tinylib/shaders/vertexPhongUV.hxsl' );
    function fragment( tex:Texture,
                       light:Float3,
                       cpos:Float3,
                       ambient:Float,
                       diffuse:Float,
                       specular:Float,
                       gloss:Float,
                       alpha:Float ) {
      var tnorm = normalize( normal );
      var lpow = diffuse * max( 0, dot( light, tnorm ) ) + ambient;
      // specular using half vector
      var view = normalize( sub( cpos, position ));
      var half_tnorm = dot( tnorm, normalize( add( light, view ) ) );
      var spow = ( half_tnorm >= 0.0 ) * specular * pow( max( 0, half_tnorm ), gloss );
      var t = tex.get( tuv ) * lpow + spow;
      out = [ t.x, t.y, t.z, alpha ];
    }
  };
  public function setShaderVariables( mp:Matrix3D,
                                      mpro:Matrix3D,
                                      vo:Vector3D,
                                      lt:Vector3D,
                                      cp:Vector3D,
                                      am:Float,
                                      df:Float,
                                      sp:Float,
                                      gl:Float,
                                      texture:Texture,
                                      a:Float ) {
    this.mpos = mp;
    this.mproj = mpro;
    this.offset = vo;
    this.light = lt;
    this.cpos = cp;
    this.ambient = am;
    this.diffuse = df;
    this.specular = sp;
    this.gloss = gl;
    this.tex = texture;
    this.alpha = a;
  }
}
