/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

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