Es/Phong materials

Con el lanzamiento de un número de mejoras se aplicaron a las iluminaciones del motor . Su énfasis se aplicó en la iluminación global para hacer más realista la presencia de los personajes, dependiendo del entorno en que se encuentren.
Una de estas mejoras fue el sombreado de Phong para jugadores con tarjetas gráficas ps_2_b o o posterior (en torno a un 70 % de todos los usuarios que jugaban a , según las estadísticas de Steam). Esta nueva característica da a los artistas de texturas la capacidad de incluir Phong, dirigidos por máscaras especulares y texturas exponenciales. Esto se integra con naturalidad con la iluminación existente y proporciona mayor definición, particularmente en personajes clave, como .
El sombreado de Phong puede incluir a «Fresnel» para favorecer a la iluminación en casos opuestos a especularidad general. En luces muy fuertes, la iluminación especular puede brillar lo suficiente como para deslumbrar como resultado de un posprocesado normal del motor Source.
==Una breve introducción al sombreado de Phong==
La siguiente breve introducción no es necesaria para saber utilizar el sombreado de Phong en Source, pero da alguna información técnica sobre cómo funciona y puede ser interesante.
En pocas palabras, el sombreado de Phong es una técnica gráfica 3D para dar mejor resolución a reflejos especulares. Fue desarrollada por Tường Phong el Dr. Bùi Tường Phong en la Universidad de Utah en 1973. Sus publicaciones combinaron la interpolación con la reflexión, dando lugar al término sombreado de Phong en la actualidad para referirse a dicha combinación entre ambos métodos.
===Modelo del reflejo de Phong===
El modelo del reflejo de Phong es básicamente un método simplificado de decidir las sombras de un punto específico en una superficie tridimensional.
*It doesn't take into account second-order reflections often found in raytraced or diffuse rendering. To compensate an extra ambient lighting term is added to the scene that is rendered.
*It divides the reflection from a surface into three subcomponents - specular reflection, diffuse reflection and ambient reflection.
Phong reflection is an empirical model based on informal observation. Dr. Phong observed that for very shiny surfaces the specular highlight was small and that the intensity fell off rapidly, while for duller surfaces it was larger and fell off more gradually.
===Interpolación de Phong===
Phong shading provides a better approximation to a per-pixel application of an underlying reflection model by assuming a smoothly varying surface normal vector. The Phong interpolation method works particularly well when applied to the Phong reflection model or to any reflection model that has small specular highlights.
In some modern hardware, variants of the interpolation algorithm are called "pixel shading" (this should not be confused with "pixel shaders"). Usually this means that the lighting calculations can be done per-pixel and include other lighting variables such as surface normals from a normal map which are interpolated across the polygon.
==Phong en el motor Source==
While the above gives a fairly basic explanation of Phong shading as a concept, the effect you see in Episode One is in fact the result of a number of combined lighting effects working together. An overview of these effects and how they are combined can be seen in the diagram of the episodic shader tree.
With model lighting, Source uses methods which combine spatially varying directional irradiance samples from the radiosity solution with local light sources and environment mapping. On graphics hardware that supports 2.0 pixel shaders and lower, Source computes diffuse illumination from up to two local light sources, either per pixel or per vertex. On newer graphics chips with longer pixel shaders, Source includes specular contributions with Fresnel terms as well as more custom effects.
Phong shading is part of these extended effects and can be seen in the path starting bottom left of the shader tree. Phong exponent, mask and Fresnel terms are combined to give a specular term which is combined with the diffuse solution in the final output.
The rest of this document will focus on the Phong part of the shading tree explaining how the components work and how to create them.
==Utilizando el sombreado de Phong==
To use Phong shading with your models, you need to add the directive $phong 1 into your material's VMT file. This tells the shader to include a Phong pass when executing the shader code. You then need to define a Phong mask in your normal maps alpha channel, a Phong exponent either as a texture or constant and finally, parameters for remapping the Fresnel output.
===Parámetros del sombreado de Phong===
A continuación se muestra una lista de parámetros VMT necesarios para activar el sombreado de Phong.
; <>
: Disable/enabled a Phong pass for this material.
; $phongexponenttexture path/to/vtf
: Filename of texture which defines Phong exponent per texel.
; $phongexponent 0..255
: Phong exponent for local specular lights. Overides $phongexponenttexture applying a defined constant exponent value over the whole texture. Default 5.0.
; $phongboost <>
: Phong overbrightening factor. The phong mask channel should be authored to account for this. Default 1.0.
; $phongfresnelranges "[n n n]"
: Parameters for remapping Fresnel output, Default [0 0.5 1].
; $basemapalphaphongmask <>
: Use the alpha channel of the $basetexture as Phong mask.
; $basemapluminancephongmask <>
: Use the luminance of the $basetexture as Phong mask.
===Ejemplos de VMT para Phong===
The following simplified example is taken from and comes from the file materials/models/Alyx/alyx_faceandhair.vmt which controls the texture on Alyx's face:
VertexLitGeneric
{
	$basetexture models/Alyx/alyx_faceandhair
	$bumpmap models/alyx/alyx_head_normal
	$halflambert 1
	$nodecal 1
	$model 1
	$phong 1
//	$phongexponent 33
	$phongexponenttexture models/Alyx/alyx_head_exponent
	$phongboost	6
	$phongfresnelranges	"[0.05 0.5 1]"
}
==Componentes y parámetros Phong detallados==
===Máscara de Phong y texturas exponenciales===
The Phong mask is a greyscale image stored in the alpha channel of the models (defined by $bumpmap). This mask defines on a per basis the intensity, or strength, of the Phong highlight for that texel. Black represents the lowest intensity and shows no Phong highlight at all (literally knocking it out), whereas white represents the brightest, or full intensity for that texel.
Instead of the normal map, the Phong mask can also be loaded from the alpha channel of the base texture, using the $basemapalphaphongmask 1 parameter. Alternatively, the luminance of the base texture can directly be used as the mask with $basemapluminancephongmask 1.
The Phong exponent defines the "tightness" of the highlight. A higher exponent results in a smaller, tighter highlight while a lower exponent results in a broader flatter one.
Different materials will exhibit highlights (tighter or broader) based upon their physical properties. A harder, smoother material such as a pool ball may have a very tight highlight while a softer, rougher material like a rubber tire may have a very broad specular highlight. In the Phong lighting equation, there is an exponent which mathematically controls the shape of the resulting highlight (tight or broad), hence the naming. 
The Phong exponent texture can be defined in one of two ways:
*$phongexponenttexture defines a texture which on a per texel bases defines the exponent value for a surface.
*$phongexponent overrides the exponent texture and is useful during development to get a quick overall specular term without painting a channel. It is then usually just commented out when a given texture map gets made and added to the mix for a given material.
The Phong exponent texture uses the red and green channels of the image for different purposes. The red channel defines the Phong exponent value and the green for albedo tinting. However, albedo tinting is a "work in progress" feature and currently un-supported in the current shader in some branches. For this reason, and the sake of simplicity, you should use greyscale for exponent textures.
Note: 05/2017 - *Albedo tinting through the green channel of the exponent texture does work in Source Filmmaker.
===Impulso de Phong===
El impulso de Phong es un valor de sobreiluminación aplicado en el canal de la máscara de Phong. El canal de la máscara de Phong debe ser autorizado para recibir un impulso de Phong. Los valores pueden ser tanto infinitos como negativos, por lo que pueden dar resultados sin valor.
===Rangos de Fresnel de Phong===
The Fresnel ranges values control the optional Fresnel term which is used to give rim lighting to a model. In short, this brightens those surfaces of the model that face away from the players viewpoint. The nearer their surface is to being parallel to the viewing angle, the brighter they become. These brighter surfaces are picked up by the pass giving them a bloomed effect.
To explain this in more detail, reflective surfaces increase in reflectivity as the angle of view approaches a grazing angle. Even a partially reflective surface theoretically becomes 100% reflective when the angle of view is parallel to the surface. This is called the Fresnel term. We can express how reflective a surface is using the symbol φ and with a value between 0 and 1. 
In the VMT the Frensel Terms are defined using the format $phongfresnelranges [φX φY φZ]. X represents how reflective the surface is when the view angle equals the surface normal. Z represents reflectivity when the view angle equals the grazing angle. Y represents reflectivity half-way between these two.
The default range values for Alyx's face are [0.05 0.5 1] which gives a linear brightening of the surfaces as they turn away from the player's view point. You can see how this looks in the visualisation of the Fresnel term included with this article.
Although we've used values between 0 and 1 so far, the actual values are unbound and you can use any number you like. For example, in values of [1 3 8] can be seen. This is useful when you are using no Phong boost and your Phong mask and exponent textures are very dark to give a minimal Phong highlight. The large Fresnel range values effectively boost the Fresnel term without effecting the Phong highlights of the model.
Estos códigos mostrarán cómo funciona el Fresnel:
//source engine fresnel Ranges
float Fresnel2( vec3 vNormal, vec3 vEyeDir )
{
	float fresnel = 1-saturate( dot( vNormal, vEyeDir ) );				// 1-(N.V) for Fresnel term
	return fresnel * fresnel;											// Square for a more subtle look
}
float Fresnel(vec3 vNormal, vec3 vEyeDir, vec3 vRanges)
{
	float result, f = Fresnel2( vNormal, vEyeDir );			// Traditional Fresnel
	if ( f > 0.5f )
		result = mix( vRanges.y, vRanges.z, (2*f)-1 );		// Blend between mid and high values
	else
 result = mix( vRanges.x, vRanges.y, 2*f );			// Blend between low and mid values
	return result;
}
==Notas==
Gracias a Jason Mitchell de Valve por la ayuda a la elaboración del artículo en inglés del que se ha traducido este en español, con imágenes de su presentación en SIGGRAPH 2006.
Anteriormente, las texturas exponenciales de Phong se mezclaban entre juegos, con un motor para la Orange Box (DOD:S y TF2 usaban los mismos modelos HWM). Valve corrigió esto el 25 de mayo de 2011.
== Véase también ==
* 
* (reflejos especulares)
* 
* 
==Enlaces externos==
Mitchell, Jason, Gary McTaggart y Chris Green (Valve), Shading in Valve's Source Engine. Curso 26: Renderizado avanzado en tiempo real en gráficos 3D y videojuegos. SIGGRAPH, en Boston (MA). Agosto de 2006:
*Notas (véase Capítulo 7) 
*Deslizantes
Ahora hay un sombreador de sustancia de pintura para el sombreado de Phong del motor Source (con más funciones), que permite editar fácilmente.
*Sombreador de Phong para motor Source