LineSegments2.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import {
  2. Box3,
  3. InstancedInterleavedBuffer,
  4. InterleavedBufferAttribute,
  5. Line3,
  6. MathUtils,
  7. Matrix4,
  8. Mesh,
  9. Sphere,
  10. Vector3,
  11. Vector4,
  12. Line2NodeMaterial,
  13. Vector2
  14. } from 'three/webgpu';
  15. import { LineSegmentsGeometry } from '../../lines/LineSegmentsGeometry.js';
  16. const _start = new Vector3();
  17. const _end = new Vector3();
  18. const _start4 = new Vector4();
  19. const _end4 = new Vector4();
  20. const _ssOrigin = new Vector4();
  21. const _ssOrigin3 = new Vector3();
  22. const _mvMatrix = new Matrix4();
  23. const _line = new Line3();
  24. const _closestPoint = new Vector3();
  25. const _box = new Box3();
  26. const _sphere = new Sphere();
  27. const _clipToWorldVector = new Vector4();
  28. const _viewport = new Vector4();
  29. let _ray, _lineWidth;
  30. // Returns the margin required to expand by in world space given the distance from the camera,
  31. // line width, resolution, and camera projection
  32. function getWorldSpaceHalfWidth( camera, distance, resolution ) {
  33. // transform into clip space, adjust the x and y values by the pixel width offset, then
  34. // transform back into world space to get world offset. Note clip space is [-1, 1] so full
  35. // width does not need to be halved.
  36. _clipToWorldVector.set( 0, 0, - distance, 1.0 ).applyMatrix4( camera.projectionMatrix );
  37. _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
  38. _clipToWorldVector.x = _lineWidth / resolution.width;
  39. _clipToWorldVector.y = _lineWidth / resolution.height;
  40. _clipToWorldVector.applyMatrix4( camera.projectionMatrixInverse );
  41. _clipToWorldVector.multiplyScalar( 1.0 / _clipToWorldVector.w );
  42. return Math.abs( Math.max( _clipToWorldVector.x, _clipToWorldVector.y ) );
  43. }
  44. function raycastWorldUnits( lineSegments, intersects ) {
  45. const matrixWorld = lineSegments.matrixWorld;
  46. const geometry = lineSegments.geometry;
  47. const instanceStart = geometry.attributes.instanceStart;
  48. const instanceEnd = geometry.attributes.instanceEnd;
  49. const segmentCount = Math.min( geometry.instanceCount, instanceStart.count );
  50. for ( let i = 0, l = segmentCount; i < l; i ++ ) {
  51. _line.start.fromBufferAttribute( instanceStart, i );
  52. _line.end.fromBufferAttribute( instanceEnd, i );
  53. _line.applyMatrix4( matrixWorld );
  54. const pointOnLine = new Vector3();
  55. const point = new Vector3();
  56. _ray.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
  57. const isInside = point.distanceTo( pointOnLine ) < _lineWidth * 0.5;
  58. if ( isInside ) {
  59. intersects.push( {
  60. point,
  61. pointOnLine,
  62. distance: _ray.origin.distanceTo( point ),
  63. object: lineSegments,
  64. face: null,
  65. faceIndex: i,
  66. uv: null,
  67. uv1: null,
  68. } );
  69. }
  70. }
  71. }
  72. function raycastScreenSpace( lineSegments, camera, intersects ) {
  73. const projectionMatrix = camera.projectionMatrix;
  74. const matrixWorld = lineSegments.matrixWorld;
  75. const resolution = lineSegments._resolution;
  76. const geometry = lineSegments.geometry;
  77. const instanceStart = geometry.attributes.instanceStart;
  78. const instanceEnd = geometry.attributes.instanceEnd;
  79. const segmentCount = Math.min( geometry.instanceCount, instanceStart.count );
  80. const near = - camera.near;
  81. //
  82. // pick a point 1 unit out along the ray to avoid the ray origin
  83. // sitting at the camera origin which will cause "w" to be 0 when
  84. // applying the projection matrix.
  85. _ray.at( 1, _ssOrigin );
  86. // ndc space [ - 1.0, 1.0 ]
  87. _ssOrigin.w = 1;
  88. _ssOrigin.applyMatrix4( camera.matrixWorldInverse );
  89. _ssOrigin.applyMatrix4( projectionMatrix );
  90. _ssOrigin.multiplyScalar( 1 / _ssOrigin.w );
  91. // screen space
  92. _ssOrigin.x *= resolution.x / 2;
  93. _ssOrigin.y *= resolution.y / 2;
  94. _ssOrigin.z = 0;
  95. _ssOrigin3.copy( _ssOrigin );
  96. _mvMatrix.multiplyMatrices( camera.matrixWorldInverse, matrixWorld );
  97. for ( let i = 0, l = segmentCount; i < l; i ++ ) {
  98. _start4.fromBufferAttribute( instanceStart, i );
  99. _end4.fromBufferAttribute( instanceEnd, i );
  100. _start4.w = 1;
  101. _end4.w = 1;
  102. // camera space
  103. _start4.applyMatrix4( _mvMatrix );
  104. _end4.applyMatrix4( _mvMatrix );
  105. // skip the segment if it's entirely behind the camera
  106. const isBehindCameraNear = _start4.z > near && _end4.z > near;
  107. if ( isBehindCameraNear ) {
  108. continue;
  109. }
  110. // trim the segment if it extends behind camera near
  111. if ( _start4.z > near ) {
  112. const deltaDist = _start4.z - _end4.z;
  113. const t = ( _start4.z - near ) / deltaDist;
  114. _start4.lerp( _end4, t );
  115. } else if ( _end4.z > near ) {
  116. const deltaDist = _end4.z - _start4.z;
  117. const t = ( _end4.z - near ) / deltaDist;
  118. _end4.lerp( _start4, t );
  119. }
  120. // clip space
  121. _start4.applyMatrix4( projectionMatrix );
  122. _end4.applyMatrix4( projectionMatrix );
  123. // ndc space [ - 1.0, 1.0 ]
  124. _start4.multiplyScalar( 1 / _start4.w );
  125. _end4.multiplyScalar( 1 / _end4.w );
  126. // screen space
  127. _start4.x *= resolution.x / 2;
  128. _start4.y *= resolution.y / 2;
  129. _end4.x *= resolution.x / 2;
  130. _end4.y *= resolution.y / 2;
  131. // create 2d segment
  132. _line.start.copy( _start4 );
  133. _line.start.z = 0;
  134. _line.end.copy( _end4 );
  135. _line.end.z = 0;
  136. // get closest point on ray to segment
  137. const param = _line.closestPointToPointParameter( _ssOrigin3, true );
  138. _line.at( param, _closestPoint );
  139. // check if the intersection point is within clip space
  140. const zPos = MathUtils.lerp( _start4.z, _end4.z, param );
  141. const isInClipSpace = zPos >= - 1 && zPos <= 1;
  142. const isInside = _ssOrigin3.distanceTo( _closestPoint ) < _lineWidth * 0.5;
  143. if ( isInClipSpace && isInside ) {
  144. _line.start.fromBufferAttribute( instanceStart, i );
  145. _line.end.fromBufferAttribute( instanceEnd, i );
  146. _line.start.applyMatrix4( matrixWorld );
  147. _line.end.applyMatrix4( matrixWorld );
  148. const pointOnLine = new Vector3();
  149. const point = new Vector3();
  150. _ray.distanceSqToSegment( _line.start, _line.end, point, pointOnLine );
  151. intersects.push( {
  152. point: point,
  153. pointOnLine: pointOnLine,
  154. distance: _ray.origin.distanceTo( point ),
  155. object: lineSegments,
  156. face: null,
  157. faceIndex: i,
  158. uv: null,
  159. uv1: null,
  160. } );
  161. }
  162. }
  163. }
  164. /**
  165. * A series of lines drawn between pairs of vertices.
  166. *
  167. * This adds functionality beyond {@link LineSegments}, like arbitrary line width and changing width
  168. * to be in world units. {@link Line2} extends this object, forming a polyline instead of individual
  169. * segments.
  170. *
  171. * This module can only be used with {@link WebGPURenderer}. When using {@link WebGLRenderer},
  172. * import the class from `lines/LineSegments2.js`.
  173. *
  174. * @augments Mesh
  175. * @three_import import { LineSegments2 } from 'three/addons/lines/webgpu/LineSegments2.js';
  176. */
  177. class LineSegments2 extends Mesh {
  178. /**
  179. * Constructs a new wide line.
  180. *
  181. * @param {LineSegmentsGeometry} [geometry] - The line geometry.
  182. * @param {Line2NodeMaterial} [material] - The line material.
  183. */
  184. constructor( geometry = new LineSegmentsGeometry(), material = new Line2NodeMaterial( { color: Math.random() * 0xffffff } ) ) {
  185. super( geometry, material );
  186. /**
  187. * This flag can be used for type testing.
  188. *
  189. * @type {boolean}
  190. * @readonly
  191. * @default true
  192. */
  193. this.isLineSegments2 = true;
  194. this.type = 'LineSegments2';
  195. this._resolution = new Vector2();
  196. }
  197. /**
  198. * Computes an array of distance values which are necessary for rendering dashed lines.
  199. * For each vertex in the geometry, the method calculates the cumulative length from the
  200. * current point to the very beginning of the line.
  201. *
  202. * @return {LineSegments2} A reference to this instance.
  203. */
  204. computeLineDistances() {
  205. // for backwards-compatibility, but could be a method of LineSegmentsGeometry...
  206. const geometry = this.geometry;
  207. const instanceStart = geometry.attributes.instanceStart;
  208. const instanceEnd = geometry.attributes.instanceEnd;
  209. const lineDistances = new Float32Array( 2 * instanceStart.count );
  210. for ( let i = 0, j = 0, l = instanceStart.count; i < l; i ++, j += 2 ) {
  211. _start.fromBufferAttribute( instanceStart, i );
  212. _end.fromBufferAttribute( instanceEnd, i );
  213. lineDistances[ j ] = ( j === 0 ) ? 0 : lineDistances[ j - 1 ];
  214. lineDistances[ j + 1 ] = lineDistances[ j ] + _start.distanceTo( _end );
  215. }
  216. const instanceDistanceBuffer = new InstancedInterleavedBuffer( lineDistances, 2, 1 ); // d0, d1
  217. geometry.setAttribute( 'instanceDistanceStart', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 0 ) ); // d0
  218. geometry.setAttribute( 'instanceDistanceEnd', new InterleavedBufferAttribute( instanceDistanceBuffer, 1, 1 ) ); // d1
  219. return this;
  220. }
  221. onBeforeRender( renderer ) {
  222. renderer.getViewport( _viewport );
  223. this._resolution.set( _viewport.z, _viewport.w );
  224. }
  225. /**
  226. * Computes intersection points between a casted ray and this instance.
  227. *
  228. * @param {Raycaster} raycaster - The raycaster.
  229. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  230. */
  231. raycast( raycaster, intersects ) {
  232. const worldUnits = this.material.worldUnits;
  233. const camera = raycaster.camera;
  234. if ( camera === null && ! worldUnits ) {
  235. console.error( 'LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.' );
  236. }
  237. const threshold = ( raycaster.params.Line2 !== undefined ) ? raycaster.params.Line2.threshold || 0 : 0;
  238. _ray = raycaster.ray;
  239. const matrixWorld = this.matrixWorld;
  240. const geometry = this.geometry;
  241. const material = this.material;
  242. _lineWidth = material.linewidth + threshold;
  243. // check if we intersect the sphere bounds
  244. if ( geometry.boundingSphere === null ) {
  245. geometry.computeBoundingSphere();
  246. }
  247. _sphere.copy( geometry.boundingSphere ).applyMatrix4( matrixWorld );
  248. // increase the sphere bounds by the worst case line screen space width
  249. let sphereMargin;
  250. if ( worldUnits ) {
  251. sphereMargin = _lineWidth * 0.5;
  252. } else {
  253. const distanceToSphere = Math.max( camera.near, _sphere.distanceToPoint( _ray.origin ) );
  254. sphereMargin = getWorldSpaceHalfWidth( camera, distanceToSphere, this._resolution );
  255. }
  256. _sphere.radius += sphereMargin;
  257. if ( _ray.intersectsSphere( _sphere ) === false ) {
  258. return;
  259. }
  260. // check if we intersect the box bounds
  261. if ( geometry.boundingBox === null ) {
  262. geometry.computeBoundingBox();
  263. }
  264. _box.copy( geometry.boundingBox ).applyMatrix4( matrixWorld );
  265. // increase the box bounds by the worst case line width
  266. let boxMargin;
  267. if ( worldUnits ) {
  268. boxMargin = _lineWidth * 0.5;
  269. } else {
  270. const distanceToBox = Math.max( camera.near, _box.distanceToPoint( _ray.origin ) );
  271. boxMargin = getWorldSpaceHalfWidth( camera, distanceToBox, this._resolution );
  272. }
  273. _box.expandByScalar( boxMargin );
  274. if ( _ray.intersectsBox( _box ) === false ) {
  275. return;
  276. }
  277. if ( worldUnits ) {
  278. raycastWorldUnits( this, intersects );
  279. } else {
  280. raycastScreenSpace( this, camera, intersects );
  281. }
  282. }
  283. }
  284. export { LineSegments2 };