SVGRenderer.js 12 KB

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