chargedBlastRingsComponent.vue 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. <script setup lang="ts">
  2. import { useLoop } from '@tresjs/core'
  3. import * as THREE from 'three'
  4. import CustomShaderMaterial from 'three-custom-shader-material/vanilla'
  5. import {
  6. computed,
  7. onBeforeUnmount,
  8. shallowRef,
  9. watch,
  10. } from 'vue'
  11. import ringFragmentShader from '../shader/chargedBlastRingsComponent/ring.frag?raw'
  12. import ringVertexShader from '../shader/chargedBlastRingsComponent/ring.vert?raw'
  13. type RingCustomMaterial = CustomShaderMaterial<typeof THREE.MeshBasicMaterial>
  14. interface RingParticle {
  15. active: boolean
  16. life: number
  17. maxLife: number
  18. posY: number
  19. }
  20. const props = withDefaults(
  21. defineProps<{
  22. autoPlay?: boolean
  23. burstToken?: number
  24. carrierRadius?: number
  25. carrierTailLength?: number
  26. fireDirectionX?: number
  27. fireDirectionY?: number
  28. fireDirectionZ?: number
  29. fireSpeed?: number
  30. loopInterval?: number
  31. maxDistance?: number
  32. ringColorA?: string
  33. ringColorB?: string
  34. ringEmission?: number
  35. ringGradientAngle?: number
  36. ringInterval?: number
  37. ringLifetime?: number
  38. ringMaxCount?: number
  39. ringMaxRadius?: number
  40. ringPeakAt?: number
  41. ringSpeed?: number
  42. ringTubeRatio?: number
  43. }>(),
  44. {
  45. autoPlay: true,
  46. burstToken: 0,
  47. carrierRadius: 0.5,
  48. carrierTailLength: 1.2,
  49. fireDirectionX: 0,
  50. fireDirectionY: 0,
  51. fireDirectionZ: -1,
  52. fireSpeed: 11,
  53. loopInterval: 1.6,
  54. maxDistance: 60,
  55. ringColorA: '#a9ffff',
  56. ringColorB: '#03ffff',
  57. ringEmission: 4,
  58. ringGradientAngle: -30,
  59. ringInterval: 0.27,
  60. ringLifetime: 0.75,
  61. ringMaxCount: 2,
  62. ringMaxRadius: 0.6,
  63. ringPeakAt: 2.5,
  64. ringSpeed: 3.5,
  65. ringTubeRatio: 0.15,
  66. },
  67. )
  68. const DEG2RAD = Math.PI / 180
  69. const MAX_RINGS = 16
  70. const clampNumber = (value: number | undefined, min: number, max: number, fallback: number) => {
  71. if (!Number.isFinite(value)) {
  72. return fallback
  73. }
  74. return THREE.MathUtils.clamp(value as number, min, max)
  75. }
  76. const setMaterialColor = (uniform: THREE.IUniform<THREE.Color>, value: string | undefined, fallback: string) => {
  77. try {
  78. uniform.value.set(value ?? fallback)
  79. }
  80. catch {
  81. uniform.value.set(fallback)
  82. }
  83. }
  84. const safeCarrierRadius = computed(() => clampNumber(props.carrierRadius, 0.01, 2, 0.5))
  85. const safeCarrierTailLength = computed(() => clampNumber(props.carrierTailLength, 0.05, 4, 1.2))
  86. const safeFireSpeed = computed(() => clampNumber(props.fireSpeed, 0.1, 60, 11))
  87. const safeLoopInterval = computed(() => clampNumber(props.loopInterval, 0.2, 10, 1.6))
  88. const safeMaxDistance = computed(() => clampNumber(props.maxDistance, 0.5, 120, 60))
  89. const safeRingEmission = computed(() => clampNumber(props.ringEmission, 0, 20, 4))
  90. const safeRingGradientAngle = computed(() => clampNumber(props.ringGradientAngle, -180, 180, -30))
  91. const safeRingInterval = computed(() => clampNumber(props.ringInterval, 0.01, 2, 0.27))
  92. const safeRingLifetime = computed(() => clampNumber(props.ringLifetime, 0.05, 3, 0.75))
  93. const safeRingMaxCount = computed(() => Math.round(clampNumber(props.ringMaxCount, 1, MAX_RINGS, 2)))
  94. const safeRingMaxRadius = computed(() => clampNumber(props.ringMaxRadius, 0.01, 2, 0.6))
  95. const safeRingPeakAt = computed(() => clampNumber(props.ringPeakAt, 1, 8, 2.5))
  96. const safeRingSpeed = computed(() => clampNumber(props.ringSpeed, 0.1, 15, 3.5))
  97. const safeRingTubeRatio = computed(() => clampNumber(props.ringTubeRatio, 0.01, 0.3, 0.15))
  98. const safeDirection = computed(() => {
  99. const direction = new THREE.Vector3(
  100. clampNumber(props.fireDirectionX, -1, 1, 0),
  101. clampNumber(props.fireDirectionY, -1, 1, 0),
  102. clampNumber(props.fireDirectionZ, -1, 1, -1),
  103. )
  104. if (direction.lengthSq() < 0.0001) {
  105. direction.set(0, 0, -1)
  106. }
  107. return direction.normalize()
  108. })
  109. const rootGroup = shallowRef<THREE.Group | null>(null)
  110. const instancedMesh = shallowRef<THREE.InstancedMesh | null>(null)
  111. const ringGeometry = shallowRef<THREE.TorusGeometry | null>(null)
  112. const createRingMaterial = (): RingCustomMaterial => {
  113. return new CustomShaderMaterial({
  114. baseMaterial: THREE.MeshBasicMaterial,
  115. blending: THREE.AdditiveBlending,
  116. color: 0xFFFFFF,
  117. depthWrite: false,
  118. fragmentShader: ringFragmentShader,
  119. silent: true,
  120. toneMapped: false,
  121. transparent: true,
  122. uniforms: {
  123. uColorA: { value: new THREE.Color(props.ringColorA) },
  124. uColorB: { value: new THREE.Color(props.ringColorB) },
  125. uEmission: { value: safeRingEmission.value },
  126. uGradientAngle: { value: safeRingGradientAngle.value * DEG2RAD },
  127. uTubeRadius: { value: safeRingTubeRatio.value },
  128. },
  129. vertexShader: ringVertexShader,
  130. })
  131. }
  132. const ringMaterial = createRingMaterial()
  133. const rings = Array.from({ length: MAX_RINGS }, (): RingParticle => ({
  134. active: false,
  135. life: 0,
  136. maxLife: 0,
  137. posY: 0,
  138. }))
  139. const dummy = new THREE.Object3D()
  140. const upAxis = new THREE.Vector3(0, 1, 0)
  141. const orientation = new THREE.Quaternion()
  142. let activeBurst = false
  143. let ringSpawnTimer = safeRingInterval.value
  144. let replayTimer = 0
  145. let traveledDistance = 0
  146. let previousBurstToken = props.burstToken
  147. const createRingGeometry = (tubeRatio: number) => {
  148. const geometry = new THREE.TorusGeometry(1, Math.max(0.01, tubeRatio), 8, 48)
  149. geometry.rotateX(Math.PI / 2)
  150. return geometry
  151. }
  152. const resetInstances = () => {
  153. if (!instancedMesh.value) {
  154. return
  155. }
  156. dummy.scale.setScalar(0)
  157. dummy.updateMatrix()
  158. for (let index = 0; index < MAX_RINGS; index += 1) {
  159. rings[index].active = false
  160. rings[index].life = 0
  161. rings[index].maxLife = 0
  162. rings[index].posY = 0
  163. instancedMesh.value.setMatrixAt(index, dummy.matrix)
  164. }
  165. instancedMesh.value.instanceMatrix.needsUpdate = true
  166. }
  167. const applyOrientation = () => {
  168. if (!rootGroup.value) {
  169. return
  170. }
  171. orientation.setFromUnitVectors(upAxis, safeDirection.value)
  172. rootGroup.value.quaternion.copy(orientation)
  173. }
  174. const deactivateBurst = () => {
  175. activeBurst = false
  176. replayTimer = 0
  177. traveledDistance = 0
  178. ringSpawnTimer = safeRingInterval.value
  179. resetInstances()
  180. if (rootGroup.value) {
  181. rootGroup.value.visible = false
  182. rootGroup.value.position.set(0, 0, 0)
  183. }
  184. }
  185. const spawnBurst = () => {
  186. if (!rootGroup.value) {
  187. return
  188. }
  189. activeBurst = true
  190. replayTimer = 0
  191. traveledDistance = 0
  192. ringSpawnTimer = safeRingInterval.value
  193. resetInstances()
  194. rootGroup.value.visible = true
  195. rootGroup.value.position.set(0, 0, 0)
  196. applyOrientation()
  197. }
  198. const createRootGroup = () => {
  199. ringGeometry.value = createRingGeometry(safeRingTubeRatio.value)
  200. const mesh = new THREE.InstancedMesh(ringGeometry.value, ringMaterial, MAX_RINGS)
  201. mesh.frustumCulled = false
  202. mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage)
  203. const group = new THREE.Group()
  204. group.visible = false
  205. group.add(mesh)
  206. instancedMesh.value = mesh
  207. rootGroup.value = group
  208. resetInstances()
  209. if (props.autoPlay) {
  210. spawnBurst()
  211. }
  212. }
  213. const syncMaterialUniforms = () => {
  214. setMaterialColor(ringMaterial.uniforms.uColorA, props.ringColorA, '#a9ffff')
  215. setMaterialColor(ringMaterial.uniforms.uColorB, props.ringColorB, '#03ffff')
  216. ringMaterial.uniforms.uEmission.value = safeRingEmission.value
  217. ringMaterial.uniforms.uGradientAngle.value = safeRingGradientAngle.value * DEG2RAD
  218. ringMaterial.uniforms.uTubeRadius.value = safeRingTubeRatio.value
  219. }
  220. const refreshGeometry = () => {
  221. const nextGeometry = createRingGeometry(safeRingTubeRatio.value)
  222. const previousGeometry = ringGeometry.value
  223. ringGeometry.value = nextGeometry
  224. if (instancedMesh.value) {
  225. instancedMesh.value.geometry = nextGeometry
  226. }
  227. previousGeometry?.dispose()
  228. }
  229. createRootGroup()
  230. watch(
  231. [
  232. () => props.ringColorA,
  233. () => props.ringColorB,
  234. safeRingEmission,
  235. safeRingGradientAngle,
  236. safeRingTubeRatio,
  237. ],
  238. syncMaterialUniforms,
  239. { immediate: true },
  240. )
  241. watch(safeRingTubeRatio, refreshGeometry)
  242. watch(
  243. () => props.autoPlay,
  244. (autoPlay) => {
  245. if (autoPlay) {
  246. spawnBurst()
  247. }
  248. else {
  249. deactivateBurst()
  250. }
  251. },
  252. )
  253. watch(
  254. () => props.burstToken,
  255. (nextToken) => {
  256. if (props.autoPlay || nextToken === previousBurstToken) {
  257. previousBurstToken = nextToken
  258. return
  259. }
  260. previousBurstToken = nextToken
  261. spawnBurst()
  262. },
  263. )
  264. watch(safeDirection, applyOrientation)
  265. const { onBeforeRender } = useLoop()
  266. onBeforeRender(({ delta }) => {
  267. if (!rootGroup.value || !instancedMesh.value) {
  268. return
  269. }
  270. if (!activeBurst) {
  271. if (props.autoPlay) {
  272. replayTimer += delta
  273. if (replayTimer >= safeLoopInterval.value) {
  274. spawnBurst()
  275. }
  276. }
  277. return
  278. }
  279. applyOrientation()
  280. const step = safeFireSpeed.value * delta
  281. traveledDistance += step
  282. rootGroup.value.position.addScaledVector(safeDirection.value, step)
  283. if (traveledDistance >= safeMaxDistance.value) {
  284. deactivateBurst()
  285. return
  286. }
  287. ringSpawnTimer += delta
  288. if (ringSpawnTimer >= safeRingInterval.value) {
  289. ringSpawnTimer -= safeRingInterval.value
  290. const maxCount = Math.min(Math.max(1, safeRingMaxCount.value), MAX_RINGS)
  291. for (let index = 0; index < maxCount; index += 1) {
  292. if (!rings[index].active) {
  293. rings[index].active = true
  294. rings[index].life = 0
  295. rings[index].maxLife = safeRingLifetime.value
  296. rings[index].posY = safeCarrierRadius.value
  297. break
  298. }
  299. }
  300. }
  301. for (let index = 0; index < MAX_RINGS; index += 1) {
  302. const ring = rings[index]
  303. if (!ring.active) {
  304. dummy.scale.setScalar(0)
  305. dummy.updateMatrix()
  306. instancedMesh.value.setMatrixAt(index, dummy.matrix)
  307. continue
  308. }
  309. ring.life += delta
  310. ring.posY -= safeRingSpeed.value * delta
  311. if (ring.life >= ring.maxLife || ring.posY < -safeCarrierTailLength.value) {
  312. ring.active = false
  313. dummy.scale.setScalar(0)
  314. dummy.updateMatrix()
  315. instancedMesh.value.setMatrixAt(index, dummy.matrix)
  316. continue
  317. }
  318. const progress = ring.life / ring.maxLife
  319. const skewedProgress = 1 - (1 - progress) ** safeRingPeakAt.value
  320. const scale = Math.sin(skewedProgress * Math.PI) * safeRingMaxRadius.value
  321. dummy.position.set(0, ring.posY, 0)
  322. dummy.rotation.set(0, 0, 0)
  323. dummy.scale.setScalar(Math.max(0, scale))
  324. dummy.updateMatrix()
  325. instancedMesh.value.setMatrixAt(index, dummy.matrix)
  326. }
  327. instancedMesh.value.instanceMatrix.needsUpdate = true
  328. })
  329. onBeforeUnmount(() => {
  330. rootGroup.value?.removeFromParent()
  331. rootGroup.value = null
  332. instancedMesh.value = null
  333. ringGeometry.value?.dispose()
  334. ringGeometry.value = null
  335. ringMaterial.dispose()
  336. })
  337. </script>
  338. <template>
  339. <primitive
  340. v-if="rootGroup"
  341. :object="rootGroup"
  342. />
  343. </template>