PageRenderTime 29ms CodeModel.GetById 19ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/src/away3d/tools/utils/BaryCentricTest.as

http://github.com/away3d/away3d-core-fp11
ActionScript | 76 lines | 44 code | 13 blank | 19 comment | 8 complexity | cdf0258bacd7ca4d31040cf12849ccfb MD5 | raw file
 1package away3d.tools.utils
 2{
 3	import away3d.core.base.data.UV;
 4	import away3d.core.base.data.Vertex;
 5
 6	import flash.geom.Vector3D;
 7
 8	/**
 9	* Classe returns the uv's from a Vector3D on a triangle plane defined with Vertex objects. Null if outside the triangle definition
10	*/
11	//credits: http://www.blackpawn.com
12	
13	public class BaryCentricTest
14	{
15		private static var _bv:Vector.<Number>;
16		/**
17		 * Returns the uv's from a Vector3D on a triangle plane defined with Vertex objects. Null if outside the triangle definition
18		 *
19		 * @param	v0		Vertex. The face v0
20		 * @param	v1		Vertex. The face v1
21		 * @param	v2		Vertex. The face v2
22		 * @param	uv0	UV. The face UV uv0
23		 * @param	uv1	UV. The face UV uv1
24		 * @param	uv2	UV. The face UV uv2
25		 * @param	hit		Vector3D. The intersect point on triangle plane.
26		 * @param	uv		[optional] UV. To prevent generation of new UV object return. Optional uv object holder can be passed.
27		 */
28		 
29		public static  function getUVs(v0:Vertex, v1:Vertex, v2:Vertex, uv0:UV, uv1:UV, uv2:UV, hit:Vector3D, uv:UV = null):UV
30		{
31			if(_bv == null){
32				_bv = new Vector.<Number>();
33				//v0,v1,v2,dot00,dot01,dot02,dot11,dot12
34				for(var i:uint=0;i<14;++i){
35					_bv[i] = 0.0;
36				}
37			}
38
39			var nuv:UV = uv || new UV(0.0,0.0);
40			 
41			_bv[0] = v2.x - v0.x;
42			_bv[1] = v2.y - v0.y;
43			_bv[2] = v2.z - v0.z;
44			
45			_bv[3] = v1.x - v0.x;
46			_bv[4] = v1.y - v0.y;
47			_bv[5] = v1.z - v0.z;
48			
49			_bv[6] = hit.x - v0.x;
50			_bv[7] = hit.y - v0.y;
51			_bv[8] = hit.z - v0.z;
52			 
53			// Compute dot products
54			_bv[9] = _bv[0]*_bv[0]+_bv[1]*_bv[1]+_bv[2]*_bv[2];
55			_bv[10] = _bv[0]*_bv[3]+_bv[1]*_bv[4]+_bv[2]*_bv[5];
56			_bv[11] = _bv[0]*_bv[6]+_bv[1]*_bv[7]+_bv[2]*_bv[8];
57			_bv[12] = _bv[3]*_bv[3]+_bv[4]*_bv[4]+_bv[5]*_bv[5];
58			_bv[13] = _bv[3]*_bv[6]+_bv[4]*_bv[7]+_bv[5]*_bv[8];
59			
60			// Compute barycentric coordinates
61			var invDenom:Number = 1 / (_bv[9] * _bv[12] - _bv[10] * _bv[10]);
62			var s:Number = (_bv[12] * _bv[11] - _bv[10] * _bv[13]) * invDenom;
63			var t:Number = (_bv[9] * _bv[13] - _bv[10] * _bv[11]) * invDenom;
64			
65			if(s > 0.0 && t > 0.0 && (s + t) < 1.0){
66				nuv.u = uv0.u+s*(uv2.u-uv0.u)+t*(uv1.u-uv0.u);
67				nuv.v = uv0.v+s*(uv2.v-uv0.v)+t*(uv1.v-uv0.v);
68			} else {
69				return null;
70			}
71			
72			return nuv; 
73		}
74
75	}
76}