UVsDebug.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. /*
  2. * @author zz85 / http://github.com/zz85
  3. * @author WestLangley / http://github.com/WestLangley
  4. *
  5. * tool for "unwrapping" and debugging three.js
  6. * geometries UV mapping
  7. *
  8. * Sample usage:
  9. * document.body.appendChild( THREE.UVsDebug( new THREE.SphereGeometry( 10, 10, 10, 10 ) );
  10. *
  11. */
  12. THREE.UVsDebug = function( geometry, size ) {
  13. // handles wrapping of uv.x > 1 only
  14. var abc = 'abc';
  15. var uv, u, ax, ay;
  16. var i, il, j, jl;
  17. var vnum;
  18. var a = new THREE.Vector2();
  19. var b = new THREE.Vector2();
  20. var geo = ( geometry instanceof THREE.BufferGeometry ) ? new THREE.Geometry().fromBufferGeometry( geometry ) : geometry;
  21. var faces = geo.faces;
  22. var uvs = geo.faceVertexUvs[ 0 ];
  23. var canvas = document.createElement( 'canvas' );
  24. var width = size || 1024; // power of 2 required for wrapping
  25. var height = size || 1024;
  26. canvas.width = width;
  27. canvas.height = height;
  28. var ctx = canvas.getContext( '2d' );
  29. ctx.lineWidth = 2;
  30. ctx.strokeStyle = 'rgba( 0, 0, 0, 1.0 )';
  31. ctx.textAlign = 'center';
  32. // paint background white
  33. ctx.fillStyle = 'rgba( 255, 255, 255, 1.0 )';
  34. ctx.fillRect( 0, 0, width, height );
  35. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  36. uv = uvs[ i ];
  37. // draw lines
  38. ctx.beginPath();
  39. a.set( 0, 0 );
  40. for ( j = 0, jl = uv.length; j < jl; j ++ ) {
  41. u = uv[ j ];
  42. a.x += u.x;
  43. a.y += u.y;
  44. if ( j == 0 ) {
  45. ctx.moveTo( u.x * width, ( 1 - u.y ) * height );
  46. } else {
  47. ctx.lineTo( u.x * width, ( 1 - u.y ) * height );
  48. }
  49. }
  50. ctx.closePath();
  51. ctx.stroke();
  52. a.divideScalar( jl );
  53. // label the face number
  54. ctx.font = "12pt Arial bold";
  55. ctx.fillStyle = 'rgba( 0, 0, 0, 1.0 )';
  56. ctx.fillText( i, a.x * width, ( 1 - a.y ) * height );
  57. if ( a.x > 0.95 ) {
  58. // wrap x // 0.95 is arbitrary
  59. ctx.fillText( i, ( a.x % 1 ) * width, ( 1 - a.y ) * height );
  60. }
  61. ctx.font = "8pt Arial bold";
  62. ctx.fillStyle = 'rgba( 0, 0, 0, 1.0 )';
  63. // label uv edge orders
  64. for ( j = 0, jl = uv.length; j < jl; j ++ ) {
  65. u = uv[ j ];
  66. b.addVectors( a, u ).divideScalar( 2 );
  67. vnum = faces[ i ][ abc[ j ] ];
  68. ctx.fillText( abc[ j ] + vnum, b.x * width, ( 1 - b.y ) * height );
  69. if ( b.x > 0.95 ) {
  70. // wrap x
  71. ctx.fillText( abc[ j ] + vnum, ( b.x % 1 ) * width, ( 1 - b.y ) * height );
  72. }
  73. }
  74. }
  75. return canvas;
  76. };