SVGRenderer.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. import {
  5. Box2,
  6. Camera,
  7. Color,
  8. Matrix3,
  9. Matrix4,
  10. Object3D,
  11. Vector3
  12. } from "../../../build/three.module.js";
  13. import { Projector } from "../renderers/Projector.js";
  14. import { RenderableFace } from "../renderers/Projector.js";
  15. import { RenderableLine } from "../renderers/Projector.js";
  16. import { RenderableSprite } from "../renderers/Projector.js";
  17. var SVGObject = function ( node ) {
  18. Object3D.call( this );
  19. this.node = node;
  20. };
  21. SVGObject.prototype = Object.create( Object3D.prototype );
  22. SVGObject.prototype.constructor = SVGObject;
  23. var SVGRenderer = function () {
  24. var _this = this,
  25. _renderData, _elements, _lights,
  26. _projector = new Projector(),
  27. _svg = document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' ),
  28. _svgWidth, _svgHeight, _svgWidthHalf, _svgHeightHalf,
  29. _v1, _v2, _v3,
  30. _clipBox = new Box2(),
  31. _elemBox = new Box2(),
  32. _color = new Color(),
  33. _diffuseColor = new Color(),
  34. _ambientLight = new Color(),
  35. _directionalLights = new Color(),
  36. _pointLights = new Color(),
  37. _clearColor = new Color(),
  38. _vector3 = new Vector3(), // Needed for PointLight
  39. _centroid = new Vector3(),
  40. _normal = new Vector3(),
  41. _normalViewMatrix = new Matrix3(),
  42. _viewMatrix = new Matrix4(),
  43. _viewProjectionMatrix = new Matrix4(),
  44. _svgPathPool = [],
  45. _svgNode, _pathCount = 0,
  46. _currentPath, _currentStyle,
  47. _quality = 1, _precision = null;
  48. this.domElement = _svg;
  49. this.autoClear = true;
  50. this.sortObjects = true;
  51. this.sortElements = true;
  52. this.overdraw = 0.5;
  53. this.info = {
  54. render: {
  55. vertices: 0,
  56. faces: 0
  57. }
  58. };
  59. this.setQuality = function ( quality ) {
  60. switch ( quality ) {
  61. case "high": _quality = 1; break;
  62. case "low": _quality = 0; break;
  63. }
  64. };
  65. this.setClearColor = function ( color ) {
  66. _clearColor.set( color );
  67. };
  68. this.setPixelRatio = function () {};
  69. this.setSize = function ( width, height ) {
  70. _svgWidth = width; _svgHeight = height;
  71. _svgWidthHalf = _svgWidth / 2; _svgHeightHalf = _svgHeight / 2;
  72. _svg.setAttribute( 'viewBox', ( - _svgWidthHalf ) + ' ' + ( - _svgHeightHalf ) + ' ' + _svgWidth + ' ' + _svgHeight );
  73. _svg.setAttribute( 'width', _svgWidth );
  74. _svg.setAttribute( 'height', _svgHeight );
  75. _clipBox.min.set( - _svgWidthHalf, - _svgHeightHalf );
  76. _clipBox.max.set( _svgWidthHalf, _svgHeightHalf );
  77. };
  78. this.setPrecision = function ( precision ) {
  79. _precision = precision;
  80. };
  81. function removeChildNodes() {
  82. _pathCount = 0;
  83. while ( _svg.childNodes.length > 0 ) {
  84. _svg.removeChild( _svg.childNodes[ 0 ] );
  85. }
  86. }
  87. function convert( c ) {
  88. return _precision !== null ? c.toFixed( _precision ) : c;
  89. }
  90. this.clear = function () {
  91. removeChildNodes();
  92. _svg.style.backgroundColor = _clearColor.getStyle();
  93. };
  94. this.render = function ( scene, camera ) {
  95. if ( camera instanceof Camera === false ) {
  96. console.error( 'THREE.SVGRenderer.render: camera is not an instance of Camera.' );
  97. return;
  98. }
  99. var background = scene.background;
  100. if ( background && background.isColor ) {
  101. removeChildNodes();
  102. _svg.style.backgroundColor = background.getStyle();
  103. } else if ( this.autoClear === true ) {
  104. this.clear();
  105. }
  106. _this.info.render.vertices = 0;
  107. _this.info.render.faces = 0;
  108. _viewMatrix.copy( camera.matrixWorldInverse );
  109. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  110. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  111. _elements = _renderData.elements;
  112. _lights = _renderData.lights;
  113. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  114. calculateLights( _lights );
  115. // reset accumulated path
  116. _currentPath = '';
  117. _currentStyle = '';
  118. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  119. var element = _elements[ e ];
  120. var material = element.material;
  121. if ( material === undefined || material.opacity === 0 ) continue;
  122. _elemBox.makeEmpty();
  123. if ( element instanceof RenderableSprite ) {
  124. _v1 = element;
  125. _v1.x *= _svgWidthHalf; _v1.y *= - _svgHeightHalf;
  126. renderSprite( _v1, element, material );
  127. } else if ( element instanceof RenderableLine ) {
  128. _v1 = element.v1; _v2 = element.v2;
  129. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  130. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  131. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  132. if ( _clipBox.intersectsBox( _elemBox ) === true ) {
  133. renderLine( _v1, _v2, element, material );
  134. }
  135. } else if ( element instanceof RenderableFace ) {
  136. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  137. if ( _v1.positionScreen.z < - 1 || _v1.positionScreen.z > 1 ) continue;
  138. if ( _v2.positionScreen.z < - 1 || _v2.positionScreen.z > 1 ) continue;
  139. if ( _v3.positionScreen.z < - 1 || _v3.positionScreen.z > 1 ) continue;
  140. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  141. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  142. _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= - _svgHeightHalf;
  143. if ( this.overdraw > 0 ) {
  144. expand( _v1.positionScreen, _v2.positionScreen, this.overdraw );
  145. expand( _v2.positionScreen, _v3.positionScreen, this.overdraw );
  146. expand( _v3.positionScreen, _v1.positionScreen, this.overdraw );
  147. }
  148. _elemBox.setFromPoints( [
  149. _v1.positionScreen,
  150. _v2.positionScreen,
  151. _v3.positionScreen
  152. ] );
  153. if ( _clipBox.intersectsBox( _elemBox ) === true ) {
  154. renderFace3( _v1, _v2, _v3, element, material );
  155. }
  156. }
  157. }
  158. flushPath(); // just to flush last svg:path
  159. scene.traverseVisible( function ( object ) {
  160. if ( object instanceof SVGObject ) {
  161. _vector3.setFromMatrixPosition( object.matrixWorld );
  162. _vector3.applyMatrix4( _viewProjectionMatrix );
  163. if ( _vector3.z < - 1 || _vector3.z > 1 ) return;
  164. var x = _vector3.x * _svgWidthHalf;
  165. var y = - _vector3.y * _svgHeightHalf;
  166. var node = object.node;
  167. node.setAttribute( 'transform', 'translate(' + x + ',' + y + ')' );
  168. _svg.appendChild( node );
  169. }
  170. } );
  171. };
  172. function calculateLights( lights ) {
  173. _ambientLight.setRGB( 0, 0, 0 );
  174. _directionalLights.setRGB( 0, 0, 0 );
  175. _pointLights.setRGB( 0, 0, 0 );
  176. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  177. var light = lights[ l ];
  178. var lightColor = light.color;
  179. if ( light.isAmbientLight ) {
  180. _ambientLight.r += lightColor.r;
  181. _ambientLight.g += lightColor.g;
  182. _ambientLight.b += lightColor.b;
  183. } else if ( light.isDirectionalLight ) {
  184. _directionalLights.r += lightColor.r;
  185. _directionalLights.g += lightColor.g;
  186. _directionalLights.b += lightColor.b;
  187. } else if ( light.isPointLight ) {
  188. _pointLights.r += lightColor.r;
  189. _pointLights.g += lightColor.g;
  190. _pointLights.b += lightColor.b;
  191. }
  192. }
  193. }
  194. function calculateLight( lights, position, normal, color ) {
  195. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  196. var light = lights[ l ];
  197. var lightColor = light.color;
  198. if ( light.isDirectionalLight ) {
  199. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  200. var amount = normal.dot( lightPosition );
  201. if ( amount <= 0 ) continue;
  202. amount *= light.intensity;
  203. color.r += lightColor.r * amount;
  204. color.g += lightColor.g * amount;
  205. color.b += lightColor.b * amount;
  206. } else if ( light.isPointLight ) {
  207. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  208. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  209. if ( amount <= 0 ) continue;
  210. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  211. if ( amount == 0 ) continue;
  212. amount *= light.intensity;
  213. color.r += lightColor.r * amount;
  214. color.g += lightColor.g * amount;
  215. color.b += lightColor.b * amount;
  216. }
  217. }
  218. }
  219. function renderSprite( v1, element, material ) {
  220. var scaleX = element.scale.x * _svgWidthHalf;
  221. var scaleY = element.scale.y * _svgHeightHalf;
  222. if ( material.isPointsMaterial ) {
  223. scaleX *= material.size;
  224. scaleY *= material.size;
  225. }
  226. var path = 'M' + convert( v1.x - scaleX * 0.5 ) + ',' + convert( v1.y - scaleY * 0.5 ) + 'h' + convert( scaleX ) + 'v' + convert( scaleY ) + 'h' + convert( - scaleX ) + 'z';
  227. var style = "";
  228. if ( material.isSpriteMaterial || material.isPointsMaterial ) {
  229. style = 'fill:' + material.color.getStyle() + ';fill-opacity:' + material.opacity;
  230. }
  231. addPath( style, path );
  232. }
  233. function renderLine( v1, v2, element, material ) {
  234. var path = 'M' + convert( v1.positionScreen.x ) + ',' + convert( v1.positionScreen.y ) + 'L' + convert( v2.positionScreen.x ) + ',' + convert( v2.positionScreen.y );
  235. if ( material.isLineBasicMaterial ) {
  236. var style = 'fill:none;stroke:' + material.color.getStyle() + ';stroke-opacity:' + material.opacity + ';stroke-width:' + material.linewidth + ';stroke-linecap:' + material.linecap;
  237. if ( material.isLineDashedMaterial ) {
  238. style = style + ';stroke-dasharray:' + material.dashSize + "," + material.gapSize;
  239. }
  240. addPath( style, path );
  241. }
  242. }
  243. function renderFace3( v1, v2, v3, element, material ) {
  244. _this.info.render.vertices += 3;
  245. _this.info.render.faces ++;
  246. var path = 'M' + convert( v1.positionScreen.x ) + ',' + convert( v1.positionScreen.y ) + 'L' + convert( v2.positionScreen.x ) + ',' + convert( v2.positionScreen.y ) + 'L' + convert( v3.positionScreen.x ) + ',' + convert( v3.positionScreen.y ) + 'z';
  247. var style = '';
  248. if ( material.isMeshBasicMaterial ) {
  249. _color.copy( material.color );
  250. if ( material.vertexColors ) {
  251. _color.multiply( element.color );
  252. }
  253. } else if ( material.isMeshLambertMaterial || material.isMeshPhongMaterial || material.isMeshStandardMaterial ) {
  254. _diffuseColor.copy( material.color );
  255. if ( material.vertexColors ) {
  256. _diffuseColor.multiply( element.color );
  257. }
  258. _color.copy( _ambientLight );
  259. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  260. calculateLight( _lights, _centroid, element.normalModel, _color );
  261. _color.multiply( _diffuseColor ).add( material.emissive );
  262. } else if ( material.isMeshNormalMaterial ) {
  263. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix ).normalize();
  264. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  265. }
  266. if ( material.wireframe ) {
  267. style = 'fill:none;stroke:' + _color.getStyle() + ';stroke-opacity:' + material.opacity + ';stroke-width:' + material.wireframeLinewidth + ';stroke-linecap:' + material.wireframeLinecap + ';stroke-linejoin:' + material.wireframeLinejoin;
  268. } else {
  269. style = 'fill:' + _color.getStyle() + ';fill-opacity:' + material.opacity;
  270. }
  271. addPath( style, path );
  272. }
  273. // Hide anti-alias gaps
  274. function expand( v1, v2, pixels ) {
  275. var x = v2.x - v1.x, y = v2.y - v1.y,
  276. det = x * x + y * y, idet;
  277. if ( det === 0 ) return;
  278. idet = pixels / Math.sqrt( det );
  279. x *= idet; y *= idet;
  280. v2.x += x; v2.y += y;
  281. v1.x -= x; v1.y -= y;
  282. }
  283. function addPath( style, path ) {
  284. if ( _currentStyle === style ) {
  285. _currentPath += path;
  286. } else {
  287. flushPath();
  288. _currentStyle = style;
  289. _currentPath = path;
  290. }
  291. }
  292. function flushPath() {
  293. if ( _currentPath ) {
  294. _svgNode = getPathNode( _pathCount ++ );
  295. _svgNode.setAttribute( 'd', _currentPath );
  296. _svgNode.setAttribute( 'style', _currentStyle );
  297. _svg.appendChild( _svgNode );
  298. }
  299. _currentPath = '';
  300. _currentStyle = '';
  301. }
  302. function getPathNode( id ) {
  303. if ( _svgPathPool[ id ] == null ) {
  304. _svgPathPool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
  305. if ( _quality == 0 ) {
  306. _svgPathPool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  307. }
  308. return _svgPathPool[ id ];
  309. }
  310. return _svgPathPool[ id ];
  311. }
  312. };
  313. export { SVGObject, SVGRenderer };