LineDashedShaderMaterial.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * LineDashedShaderMaterial
  3. *
  4. * @author rabbib76, realor
  5. */
  6. import * as THREE from '../lib/three.module.js'
  7. class LineDashedShaderMaterial extends THREE.ShaderMaterial {
  8. static VERTEX_SHADER = `
  9. flat out vec3 startPos;
  10. out vec3 vertPos;
  11. void main()
  12. {
  13. vec4 pos = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
  14. gl_Position = pos;
  15. vertPos = pos.xyz / pos.w;
  16. startPos = vertPos;
  17. }
  18. `
  19. static FRAGMENT_SHADER = `
  20. precision highp float;
  21. flat in vec3 startPos;
  22. in vec3 vertPos;
  23. uniform vec3 u_color;
  24. uniform vec2 u_resolution;
  25. uniform float u_dashSize;
  26. uniform float u_gapSize;
  27. void main()
  28. {
  29. vec2 dir = (vertPos.xy - startPos.xy) * u_resolution / 2.0;
  30. float dist = length(dir);
  31. float dashGapSize = u_dashSize + u_gapSize;
  32. if (fract(dist / dashGapSize) > u_dashSize / dashGapSize)
  33. discard;
  34. gl_FragColor = vec4(u_color.rgb, 1.0);
  35. }
  36. `
  37. constructor(options = {}) {
  38. const color = options.color || new THREE.Color(0, 0, 0)
  39. const dashSize = options.dashSize || 4
  40. const gapSize = options.gapSize || 4
  41. const uniforms = {
  42. u_color: { type: 'v3', value: { x: color.r, y: color.g, z: color.b } },
  43. u_resolution: { type: 'v2', value: { x: 1600, y: 1000 } },
  44. u_dashSize: { type: 'f', value: dashSize },
  45. u_gapSize: { type: 'f', value: gapSize }
  46. }
  47. super({
  48. uniforms: uniforms,
  49. vertexShader: LineDashedShaderMaterial.VERTEX_SHADER,
  50. fragmentShader: LineDashedShaderMaterial.FRAGMENT_SHADER,
  51. depthTest: options.depthTest === undefined ? true : options.depthTest,
  52. depthWrite: options.depthWrite === undefined ? true : options.depthWrite
  53. })
  54. }
  55. }
  56. export { LineDashedShaderMaterial }