Line2NodeMaterial.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. import NodeMaterial from './NodeMaterial.js';
  2. import { dashSize, diffuseColor, gapSize, varyingProperty } from '../../nodes/core/PropertyNode.js';
  3. import { attribute } from '../../nodes/core/AttributeNode.js';
  4. import { cameraProjectionMatrix } from '../../nodes/accessors/Camera.js';
  5. import { materialLineScale, materialLineDashSize, materialLineGapSize, materialLineDashOffset, materialLineWidth } from '../../nodes/accessors/MaterialNode.js';
  6. import { modelViewMatrix } from '../../nodes/accessors/ModelNode.js';
  7. import { positionGeometry } from '../../nodes/accessors/Position.js';
  8. import { mix, smoothstep } from '../../nodes/math/MathNode.js';
  9. import { Fn, float, vec2, vec3, vec4, If } from '../../nodes/tsl/TSLBase.js';
  10. import { uv } from '../../nodes/accessors/UV.js';
  11. import { screenDPR, viewport } from '../../nodes/display/ScreenNode.js';
  12. import { viewportOpaqueMipTexture } from '../../nodes/display/ViewportTextureNode.js';
  13. import { LineDashedMaterial } from '../LineDashedMaterial.js';
  14. import { NoBlending } from '../../constants.js';
  15. import { warnOnce } from '../../utils.js';
  16. const _defaultValues = /*@__PURE__*/ new LineDashedMaterial();
  17. /**
  18. * Varying node representing the world position of the segment start in view space.
  19. * Used for distance and coordinate calculations across the fragment shader.
  20. * @type {VaryingNode<vec3>}
  21. */
  22. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  23. /**
  24. * Varying node representing the world position of the segment end in view space.
  25. * Used for distance and coordinate calculations across the fragment shader.
  26. * @type {VaryingNode<vec3>}
  27. */
  28. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  29. /**
  30. * Varying node representing the accumulated distance along the line.
  31. * Crucial for correctly computing dashed line intervals in fragment stage.
  32. * @type {VaryingNode<float>}
  33. */
  34. const lineDistance = varyingProperty( 'float', 'lineDistance' );
  35. /**
  36. * Varying node representing the interpolated world/view position of the current fragment.
  37. * Used for line/ray distance checks under perspective projection.
  38. * @type {VaryingNode<vec4>}
  39. */
  40. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  41. /**
  42. * Trims the line segment to avoid rendering behind the camera near plane.
  43. * Computes an interpolation factor (alpha) to clamp the segment's coordinate.
  44. *
  45. * @param {Object} inputs
  46. * @param {Node<vec4>} inputs.start - Segment start position in view space.
  47. * @param {Node<vec4>} inputs.end - Segment end position in view space.
  48. * @returns {Node<float>} The interpolation factor (alpha) to trim the segment.
  49. */
  50. const trimSegmentAlpha = Fn( ( { start, end } ) => {
  51. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  52. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  53. // we need different nearEstimate formula for reversed and default depth buffer
  54. // a is positive with a reversed depth buffer so it can be used for controlling the code flow
  55. const nearEstimate = a.greaterThan( 0 ).select( b.negate().div( a.add( 1 ) ), b.mul( - 0.5 ).div( a ) );
  56. return nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  57. }, { start: 'vec4', end: 'vec4', return: 'float' } );
  58. /**
  59. * Calculates the closest points on two 3D lines.
  60. * Used for perspective-correct line rendering and coordinates interpolation.
  61. *
  62. * @param {Object} inputs
  63. * @param {Node<vec3>} inputs.p1 - Start of line 1.
  64. * @param {Node<vec3>} inputs.p2 - End of line 1.
  65. * @param {Node<vec3>} inputs.p3 - Start of line 2.
  66. * @param {Node<vec3>} inputs.p4 - End of line 2.
  67. * @returns {Node<vec2>} A vec2 containing the parametric coordinates (mua, mub) of the closest points on line 1 and line 2.
  68. */
  69. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  70. const p13 = p1.sub( p3 );
  71. const p43 = p4.sub( p3 );
  72. const p21 = p2.sub( p1 );
  73. const d1343 = p13.dot( p43 );
  74. const d4321 = p43.dot( p21 );
  75. const d1321 = p13.dot( p21 );
  76. const d4343 = p43.dot( p43 );
  77. const d2121 = p21.dot( p21 );
  78. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  79. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  80. const mua = numer.div( denom ).clamp();
  81. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  82. return vec2( mua, mub );
  83. }, { p1: 'vec3', p2: 'vec3', p3: 'vec3', p4: 'vec3', return: 'vec2' } );
  84. /**
  85. * TSL node acting as a custom Model-View-Projection (MVP) for fat lines,
  86. * expanding 3D segments into screen/world-facing ribbons of a specified width.
  87. *
  88. * @tsl
  89. * @type {Node<vec4>}
  90. */
  91. const mvpLine = Fn( ( { material } ) => {
  92. const useDash = material._useDash;
  93. const useWorldUnits = material._useWorldUnits;
  94. const instanceStart = attribute( 'instanceStart' );
  95. const instanceEnd = attribute( 'instanceEnd' );
  96. // camera space
  97. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  98. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  99. let distanceStart, distanceEnd;
  100. if ( useDash ) {
  101. distanceStart = float( attribute( 'instanceDistanceStart' ) ).toVar( 'distanceStart' );
  102. distanceEnd = float( attribute( 'instanceDistanceEnd' ) ).toVar( 'distanceEnd' );
  103. }
  104. if ( useWorldUnits ) {
  105. worldStart.assign( start.xyz );
  106. worldEnd.assign( end.xyz );
  107. }
  108. const aspect = viewport.z.div( viewport.w );
  109. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  110. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  111. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  112. // perhaps there is a more elegant solution -- WestLangley
  113. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  114. If( perspective, () => {
  115. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  116. const alpha = trimSegmentAlpha( { start, end } );
  117. end.assign( vec4( mix( start.xyz, end.xyz, alpha ), end.w ) );
  118. if ( useDash ) {
  119. distanceEnd.assign( mix( distanceStart, distanceEnd, alpha ) );
  120. }
  121. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  122. const alpha = trimSegmentAlpha( { start: end, end: start } );
  123. start.assign( vec4( mix( end.xyz, start.xyz, alpha ), start.w ) );
  124. if ( useDash ) {
  125. distanceStart.assign( mix( distanceEnd, distanceStart, alpha ) );
  126. }
  127. } );
  128. } );
  129. if ( useDash ) {
  130. const dashScaleNode = material.dashScaleNode ? float( material.dashScaleNode ) : materialLineScale;
  131. const offsetNode = material.offsetNode ? float( material.offsetNode ) : materialLineDashOffset;
  132. let lineDist = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( distanceStart ), dashScaleNode.mul( distanceEnd ) );
  133. lineDist = lineDist.add( offsetNode );
  134. lineDistance.assign( lineDist );
  135. }
  136. // clip space
  137. const clipStart = cameraProjectionMatrix.mul( start );
  138. const clipEnd = cameraProjectionMatrix.mul( end );
  139. // ndc space
  140. const ndcStart = clipStart.xyz.div( clipStart.w );
  141. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  142. // direction
  143. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  144. // account for clip-space aspect ratio
  145. dir.x.assign( dir.x.mul( aspect ) );
  146. dir.assign( dir.normalize() );
  147. const clip = vec4().toVar();
  148. if ( useWorldUnits ) {
  149. // get the offset direction as perpendicular to the view vector
  150. const worldDir = end.xyz.sub( start.xyz ).normalize();
  151. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  152. const worldUp = worldDir.cross( tmpFwd ).normalize();
  153. const worldFwd = worldDir.cross( worldUp );
  154. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  155. // height offset
  156. const hw = materialLineWidth.mul( 0.5 );
  157. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  158. // don't extend the line if we're rendering dashes because we
  159. // won't be rendering the endcaps
  160. if ( ! useDash ) {
  161. // cap extension
  162. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  163. // add width to the box
  164. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  165. // endcaps
  166. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  167. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  168. } );
  169. }
  170. // project the worldpos
  171. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  172. // shift the depth of the projected points so the line
  173. // segments overlap neatly
  174. const clipPose = vec3().toVar();
  175. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  176. clip.z.assign( clipPose.z.mul( clip.w ) );
  177. } else {
  178. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  179. // undo aspect ratio adjustment
  180. dir.x.assign( dir.x.div( aspect ) );
  181. offset.x.assign( offset.x.div( aspect ) );
  182. // sign flip
  183. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  184. // endcaps
  185. If( positionGeometry.y.lessThan( 0.0 ), () => {
  186. offset.assign( offset.sub( dir ) );
  187. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  188. offset.assign( offset.add( dir ) );
  189. } );
  190. // adjust for linewidth
  191. offset.assign( offset.mul( materialLineWidth ) );
  192. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  193. offset.assign( offset.div( viewport.w.div( screenDPR ) ) );
  194. // select end
  195. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  196. // back to clip space
  197. offset.assign( offset.mul( clip.w ) );
  198. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  199. }
  200. return clip;
  201. } )();
  202. /**
  203. * TSL fragment node that computes the shape/coverage (alpha) of the fat line segment.
  204. * Handles dash/gap generation, alpha-to-coverage rendering, and round endcaps.
  205. *
  206. * @tsl
  207. * @type {Node<float>}
  208. */
  209. const alphaLine = Fn( ( { material, renderer } ) => {
  210. const useAlphaToCoverage = material._useAlphaToCoverage;
  211. const useDash = material._useDash;
  212. const useWorldUnits = material._useWorldUnits;
  213. const vUv = uv();
  214. if ( useDash ) {
  215. const dashSizeNode = material.dashSizeNode ? float( material.dashSizeNode ) : materialLineDashSize;
  216. const gapSizeNode = material.gapSizeNode ? float( material.gapSizeNode ) : materialLineGapSize;
  217. dashSize.assign( dashSizeNode );
  218. gapSize.assign( gapSizeNode );
  219. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  220. lineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  221. }
  222. const alpha = float( 1 ).toVar( 'alpha' );
  223. if ( useWorldUnits ) {
  224. // Find the closest points on the view ray and the line segment
  225. const rayEnd = worldPos.xyz.normalize().mul( 1e5 );
  226. const lineDir = worldEnd.sub( worldStart );
  227. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  228. const p1 = worldStart.add( lineDir.mul( params.x ) );
  229. const p2 = rayEnd.mul( params.y );
  230. const delta = p1.sub( p2 );
  231. const len = delta.length();
  232. const norm = len.div( materialLineWidth );
  233. if ( ! useDash ) {
  234. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  235. const dnorm = norm.fwidth();
  236. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  237. } else {
  238. norm.greaterThan( 0.5 ).discard();
  239. }
  240. }
  241. } else {
  242. // round endcaps
  243. if ( useAlphaToCoverage && renderer.currentSamples > 0 ) {
  244. const a = vUv.x;
  245. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  246. const len2 = a.mul( a ).add( b.mul( b ) );
  247. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  248. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  249. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  250. } );
  251. } else {
  252. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  253. const a = vUv.x;
  254. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  255. const len2 = a.mul( a ).add( b.mul( b ) );
  256. len2.greaterThan( 1.0 ).discard();
  257. } );
  258. }
  259. }
  260. return alpha;
  261. } )();
  262. /**
  263. * This node material can be used to render lines with a size larger than one
  264. * by representing them as instanced meshes.
  265. *
  266. * @augments NodeMaterial
  267. */
  268. class Line2NodeMaterial extends NodeMaterial {
  269. static get type() {
  270. return 'Line2NodeMaterial';
  271. }
  272. /**
  273. * Constructs a new node material for wide line rendering.
  274. *
  275. * @param {Object} [parameters={}] - The configuration parameter.
  276. */
  277. constructor( parameters = {} ) {
  278. super();
  279. /**
  280. * This flag can be used for type testing.
  281. *
  282. * @type {boolean}
  283. * @readonly
  284. * @default true
  285. */
  286. this.isLine2NodeMaterial = true;
  287. this.setDefaultValues( _defaultValues );
  288. /**
  289. * Whether vertex colors should be used or not.
  290. *
  291. * @type {boolean}
  292. * @default false
  293. */
  294. this.vertexColors = parameters.vertexColors;
  295. /**
  296. * The dash offset.
  297. *
  298. * @type {number}
  299. * @default 0
  300. */
  301. this.dashOffset = 0;
  302. /**
  303. * Defines the offset.
  304. *
  305. * @type {?Node<float>}
  306. * @default null
  307. */
  308. this.offsetNode = null;
  309. /**
  310. * Defines the dash scale.
  311. *
  312. * @type {?Node<float>}
  313. * @default null
  314. */
  315. this.dashScaleNode = null;
  316. /**
  317. * Defines the dash size.
  318. *
  319. * @type {?Node<float>}
  320. * @default null
  321. */
  322. this.dashSizeNode = null;
  323. /**
  324. * Defines the gap size.
  325. *
  326. * @type {?Node<float>}
  327. * @default null
  328. */
  329. this.gapSizeNode = null;
  330. /**
  331. * Blending is set to `NoBlending` since transparency
  332. * is not supported, yet.
  333. *
  334. * @type {number}
  335. * @default 0
  336. */
  337. this.blending = NoBlending;
  338. this._useDash = parameters.dashed;
  339. this._useAlphaToCoverage = true;
  340. this._useWorldUnits = false;
  341. this.setValues( parameters );
  342. }
  343. /**
  344. * Setups the diffuse color of the line material in the fragment stage.
  345. * Overrides the base setup to incorporate line/dash rendering and blending.
  346. *
  347. * @param {NodeBuilder} builder - The current node builder.
  348. */
  349. setupDiffuseColor( builder ) {
  350. super.setupDiffuseColor( builder );
  351. diffuseColor.a.mulAssign( alphaLine );
  352. if ( this.vertexColors === true && builder.geometry.hasAttribute( 'instanceColorStart' ) ) {
  353. const instanceColorStart = attribute( 'instanceColorStart' );
  354. const instanceColorEnd = attribute( 'instanceColorEnd' );
  355. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  356. diffuseColor.rgb.mulAssign( instanceColor );
  357. }
  358. if ( this.transparent ) {
  359. diffuseColor.rgb.assign( diffuseColor.rgb.mul( diffuseColor.a ).add( viewportOpaqueMipTexture().rgb.mul( diffuseColor.a.oneMinus() ) ) );
  360. }
  361. }
  362. /**
  363. * Setups the position in clip space for the vertex stage of the fat line.
  364. * Overrides the default model-view-projection to return the expanded fat line vertex coordinates.
  365. *
  366. * @param {NodeBuilder} builder - The current node builder.
  367. * @return {Node<vec4>} The position of the fat line vertex in clip space.
  368. */
  369. setupModelViewProjection( /*builder*/ ) {
  370. return mvpLine;
  371. }
  372. /**
  373. * Defines the lines color.
  374. *
  375. * @deprecated since r185. Use {@link NodeMaterial#colorNode} instead.
  376. * @type {?Node<vec3>}
  377. */
  378. get lineColorNode() {
  379. return this.colorNode;
  380. }
  381. set lineColorNode( value ) {
  382. warnOnce( 'Line2NodeMaterial: "lineColorNode" has been deprecated. Use "colorNode" instead.' ); // @deprecated r185
  383. this.colorNode = value;
  384. }
  385. /**
  386. * Whether the lines should sized in world units or not.
  387. * When set to `false` the unit is pixel.
  388. *
  389. * @type {boolean}
  390. * @default false
  391. */
  392. get worldUnits() {
  393. return this._useWorldUnits;
  394. }
  395. set worldUnits( value ) {
  396. if ( this._useWorldUnits !== value ) {
  397. this._useWorldUnits = value;
  398. this.needsUpdate = true;
  399. }
  400. }
  401. /**
  402. * Whether the lines should be dashed or not.
  403. *
  404. * @type {boolean}
  405. * @default false
  406. */
  407. get dashed() {
  408. return this._useDash;
  409. }
  410. set dashed( value ) {
  411. if ( this._useDash !== value ) {
  412. this._useDash = value;
  413. this.needsUpdate = true;
  414. }
  415. }
  416. /**
  417. * Whether alpha to coverage should be used or not.
  418. *
  419. * @type {boolean}
  420. * @default true
  421. */
  422. get alphaToCoverage() {
  423. return this._useAlphaToCoverage;
  424. }
  425. set alphaToCoverage( value ) {
  426. if ( this._useAlphaToCoverage !== value ) {
  427. this._useAlphaToCoverage = value;
  428. this.needsUpdate = true;
  429. }
  430. }
  431. }
  432. export default Line2NodeMaterial;
粤ICP备19079148号