SVGRenderer.js 12 KB

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