| | 1 | | using System.Threading.Tasks; |
| | 2 | | using GLTFast; |
| | 3 | | using UnityEngine; |
| | 4 | |
|
| | 5 | | namespace DCL.GLTFast.Wrappers |
| | 6 | | { |
| | 7 | | // Note (Kinerius) This is a straight up copy of TimeBudgetPerFrameDeferAgent but it reacts to the renderer being in |
| | 8 | | [DefaultExecutionOrder(-10)] |
| | 9 | | public class GltFastDeferAgent : MonoBehaviour, IDeferAgent |
| | 10 | | { |
| | 11 | | [SerializeField] |
| | 12 | | [Range(.01f, 5f)] |
| | 13 | | [Tooltip("Per-frame time budget as fraction of the targeted frame time. Keep it well below 0.5, so there's enoug |
| 1 | 14 | | private float frameBudget = .5f; |
| | 15 | |
|
| | 16 | | private float lastTime; |
| 1 | 17 | | private float timeBudget = .5f / 30; |
| | 18 | | private bool isRendererActive; |
| | 19 | |
|
| | 20 | | private void Start() |
| | 21 | | { |
| 1 | 22 | | CommonScriptableObjects.rendererState.OnChange += OnRenderStateChanged; |
| 1 | 23 | | OnRenderStateChanged(CommonScriptableObjects.rendererState.Get(), false); |
| 1 | 24 | | } |
| | 25 | |
|
| | 26 | | private void OnRenderStateChanged(bool current, bool previous) |
| | 27 | | { |
| 2 | 28 | | isRendererActive = current; |
| 2 | 29 | | UpdateTimeBudget(); |
| 2 | 30 | | } |
| | 31 | |
|
| | 32 | | private void UpdateTimeBudget() |
| | 33 | | { |
| 3 | 34 | | float targetFrameRate = Application.targetFrameRate; |
| | 35 | |
|
| 3 | 36 | | if (targetFrameRate < 0) |
| 3 | 37 | | targetFrameRate = 30; |
| | 38 | |
|
| 3 | 39 | | timeBudget = isRendererActive ? frameBudget / targetFrameRate : float.MaxValue; |
| 3 | 40 | | ResetLastTime(); |
| 3 | 41 | | } |
| | 42 | |
|
| | 43 | | private void Awake() |
| | 44 | | { |
| 1 | 45 | | UpdateTimeBudget(); |
| 1 | 46 | | } |
| | 47 | |
|
| | 48 | | private void Update() |
| | 49 | | { |
| 9 | 50 | | ResetLastTime(); |
| 9 | 51 | | } |
| | 52 | |
|
| | 53 | | private void ResetLastTime() |
| | 54 | | { |
| 12 | 55 | | lastTime = Time.realtimeSinceStartup; |
| 12 | 56 | | } |
| | 57 | |
|
| | 58 | | public bool ShouldDefer() => |
| 5991 | 59 | | !FitsInCurrentFrame(0); |
| | 60 | |
|
| | 61 | | public bool ShouldDefer(float duration) => |
| 616 | 62 | | !FitsInCurrentFrame(duration); |
| | 63 | |
|
| | 64 | | private bool FitsInCurrentFrame(float duration) => |
| 6607 | 65 | | duration <= timeBudget - (Time.realtimeSinceStartup - lastTime); |
| | 66 | |
|
| | 67 | | public async Task BreakPoint() |
| | 68 | | { |
| 5991 | 69 | | if (ShouldDefer()) |
| 6 | 70 | | await Task.Yield(); |
| 5991 | 71 | | } |
| | 72 | |
|
| | 73 | | public async Task BreakPoint(float duration) |
| | 74 | | { |
| 351 | 75 | | if (ShouldDefer(duration)) |
| 0 | 76 | | await Task.Yield(); |
| 351 | 77 | | } |
| | 78 | | } |
| | 79 | | } |