| 1 | package net.minecraft.util.profiling;
|
| 2 |
|
| 3 | import com.mojang.jtracy.TracyClient;
|
| 4 | import java.util.Objects;
|
| 5 | import java.util.concurrent.atomic.AtomicInteger;
|
| 6 | import org.jspecify.annotations.Nullable;
|
| 7 |
|
| 8 | public final class Profiler {
|
| 9 | private static final ThreadLocal<TracyZoneFiller> TRACY_FILLER = ThreadLocal.withInitial(TracyZoneFiller::new);
|
| 10 | private static final ThreadLocal<@Nullable ProfilerFiller> ACTIVE = new ThreadLocal<>();
|
| 11 | private static final AtomicInteger ACTIVE_COUNT = new AtomicInteger();
|
| 12 |
|
| 13 | private Profiler() {
|
| 14 | }
|
| 15 |
|
| 16 | public static Profiler.Scope use(final ProfilerFiller filler) {
|
| 17 | if (filler instanceof InactiveProfiler) {
|
| 18 | return () -> {};
|
| 19 | }
|
| 20 |
|
| 21 | startUsing(filler);
|
| 22 | return Profiler::stopUsing;
|
| 23 | }
|
| 24 |
|
| 25 | private static void startUsing(final ProfilerFiller filler) {
|
| 26 | if (ACTIVE.get() != null) {
|
| 27 | throw new IllegalStateException("Profiler is already active");
|
| 28 | }
|
| 29 |
|
| 30 | ProfilerFiller active = decorateFiller(filler);
|
| 31 | ACTIVE.set(active);
|
| 32 | ACTIVE_COUNT.incrementAndGet();
|
| 33 | active.startTick();
|
| 34 | }
|
| 35 |
|
| 36 | private static void stopUsing() {
|
| 37 | ProfilerFiller active = ACTIVE.get();
|
| 38 | if (active == null) {
|
| 39 | throw new IllegalStateException("Profiler was not active");
|
| 40 | }
|
| 41 |
|
| 42 | ACTIVE.remove();
|
| 43 | ACTIVE_COUNT.decrementAndGet();
|
| 44 | active.endTick();
|
| 45 | }
|
| 46 |
|
| 47 | private static ProfilerFiller decorateFiller(final ProfilerFiller filler) {
|
| 48 | return ProfilerFiller.combine(getDefaultFiller(), filler);
|
| 49 | }
|
| 50 |
|
| 51 | public static ProfilerFiller get() {
|
| 52 | return ACTIVE_COUNT.get() == 0 ? getDefaultFiller() : Objects.requireNonNullElseGet(ACTIVE.get(), Profiler::getDefaultFiller);
|
| 53 | }
|
| 54 |
|
| 55 | private static ProfilerFiller getDefaultFiller() {
|
| 56 | return TracyClient.isAvailable() ? TRACY_FILLER.get() : InactiveProfiler.INSTANCE;
|
| 57 | }
|
| 58 |
|
| 59 | public interface Scope extends AutoCloseable {
|
| 60 | @Override
|
| 61 | void close();
|
| 62 | }
|
| 63 | }
|
| 64 |
|