|
| 1 | +import { Injector, effect, inject, runInInjectionContext, untracked } from '@angular/core'; |
| 2 | +import { RayMode, RayOptions, RayhitEvent } from '@pmndrs/cannon-worker-api'; |
| 3 | +import { NgtAnyRecord, assertInjectionContext, makeId } from 'angular-three'; |
| 4 | +import { NGTC_PHYSICS_API } from 'angular-three-cannon'; |
| 5 | + |
| 6 | +export interface NgtcRayOptions { |
| 7 | + options: () => RayOptions; |
| 8 | + callback: (e: RayhitEvent) => void; |
| 9 | + injector?: Injector; |
| 10 | + deps?: () => NgtAnyRecord; |
| 11 | +} |
| 12 | + |
| 13 | +export function injectRaycastClosest(opts: NgtcRayOptions) { |
| 14 | + return injectRay('Closest', opts); |
| 15 | +} |
| 16 | + |
| 17 | +export function injectRaycastAny(opts: NgtcRayOptions) { |
| 18 | + return injectRay('Any', opts); |
| 19 | +} |
| 20 | + |
| 21 | +export function useRaycastAll(opts: NgtcRayOptions) { |
| 22 | + return injectRay('All', opts); |
| 23 | +} |
| 24 | + |
| 25 | +function injectRay(mode: RayMode, { options, callback, deps = () => ({}), injector }: NgtcRayOptions) { |
| 26 | + injector = assertInjectionContext(injectRay, injector); |
| 27 | + return runInInjectionContext(injector, () => { |
| 28 | + const physicsApi = inject(NGTC_PHYSICS_API); |
| 29 | + const { worker, events } = physicsApi(); |
| 30 | + const uuid = makeId(); |
| 31 | + |
| 32 | + effect((onCleanup) => { |
| 33 | + deps(); |
| 34 | + events[uuid] = { rayhit: callback }; |
| 35 | + worker.addRay({ props: { ...untracked(options), mode }, uuid }); |
| 36 | + onCleanup(() => { |
| 37 | + worker.removeRay({ uuid }); |
| 38 | + delete events[uuid]; |
| 39 | + }); |
| 40 | + }); |
| 41 | + }); |
| 42 | +} |
0 commit comments