Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ rendering, and every optimization has its own switch.
- Live geometry: supported Item Display models, including ModelEngine models built
from them, keep their meshes on the GPU and draw together; each frame sends
only poses, lighting and tint.
- Parts of these models outside the camera view are skipped for the frame; their
ticks and animation keep running.
- A model cache reuses prepared model layers and refreshes them within a CPU budget.

**Players**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ public enum Target {
PLAYER_ARMOR,
PLAYER_ITEMS,
PLAYER_BODY,
LIVE_CULLING,
BATCHING;

String id() {
Expand All @@ -52,6 +53,7 @@ void apply(boolean on) {
case PLAYER_ARMOR -> c.playerArmorGeometry = on;
case PLAYER_ITEMS -> c.playerItemGeometry = on;
case PLAYER_BODY -> c.playerBodyGeometry = on;
case LIVE_CULLING -> c.liveViewCulling = on;
case BATCHING -> c.featureBatching = on;
}
}
Expand All @@ -61,7 +63,8 @@ boolean unavailable() {
|| (this == BATCHING
|| this == PLAYER_ARMOR
|| this == PLAYER_ITEMS
|| this == PLAYER_BODY)
|| this == PLAYER_BODY
|| this == LIVE_CULLING)
&& ru.wilyfox.drawless.compat.IrisShaders.packInUse()
|| this == PLAYER_BODY && RenderModSupport.PLAYER_MODEL_MODS
|| (this == PARTICLES || this == PARTICLE_LIGHT || this == PARTICLE_COLLISION)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public final class DrawLessConfig {
public boolean adaptiveDisplayModelBudget = true;
public ExtremeDisplayMode extremeDisplayMode = ExtremeDisplayMode.LIVE_CACHE;
public boolean extremeAllItemDisplays = true;
public boolean liveViewCulling = true;
public boolean modelEngineNpcBudget = false;
public int npcGroupsPerFrame = 2;
public boolean adaptiveNpcBudget = true;
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/ru/wilyfox/drawless/gui/SettingsCatalog.java
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,12 @@ static List<Option> create() {
0,
0,
0));
options.add(
toggle(
"live_view_culling",
Page.RENDERING,
() -> c().liveViewCulling,
v -> c().liveViewCulling = v));
options.add(
toggle(
"model_cache",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import ru.wilyfox.drawless.performance.ExtremeDisplayPerformance;
import ru.wilyfox.drawless.performance.LiveDisplayGeometry;

@Mixin(LevelExtractor.class)
public class ExtremeDisplayVisibilityMixin {
Expand All @@ -27,8 +28,8 @@ public class ExtremeDisplayVisibilityMixin {
double z,
Operation<Boolean> original) {
boolean visible = original.call(extractor, entity, frustum, x, y, z);
return ExtremeDisplayPerformance.staticCache()
? ExtremeDisplayPerformance.staticVisibility(entity, visible)
: visible;
if (ExtremeDisplayPerformance.staticCache())
return ExtremeDisplayPerformance.staticVisibility(entity, visible);
return visible && !LiveDisplayGeometry.outsideView(entity, frustum);
}
}
22 changes: 19 additions & 3 deletions src/main/java/ru/wilyfox/drawless/performance/ItemMeshes.java
Original file line number Diff line number Diff line change
Expand Up @@ -274,12 +274,22 @@ private static Geometry build(QuadKey key, List<BakedQuad> quads, List<BakedQuad
for (var entry : grouped.entrySet()) {
int offset = buffer.vertices();
Set<TextureAtlasSprite> sprites = Collections.newSetFromMap(new IdentityHashMap<>());
float[] bounds = {
Float.MAX_VALUE, Float.MAX_VALUE, Float.MAX_VALUE,
-Float.MAX_VALUE, -Float.MAX_VALUE, -Float.MAX_VALUE
};
for (var quad : entry.getValue()) {
var n = quad.direction().getUnitVec3f();
if (quad.materialInfo().sprite().isAnimated()) sprites.add(quad.materialInfo().sprite());
for (int v = 0; v < 4; v++) {
var p = quad.position(v);
long uv = quad.packedUV(v);
bounds[0] = Math.min(bounds[0], p.x());
bounds[1] = Math.min(bounds[1], p.y());
bounds[2] = Math.min(bounds[2], p.z());
bounds[3] = Math.max(bounds[3], p.x());
bounds[4] = Math.max(bounds[4], p.y());
bounds[5] = Math.max(bounds[5], p.z());
buffer.vertex(
p.x(), p.y(), p.z(), UVPair.unpackU(uv), n.x(), n.y(), n.z(), UVPair.unpackV(uv));
}
Expand All @@ -291,7 +301,8 @@ private static Geometry build(QuadKey key, List<BakedQuad> quads, List<BakedQuad
buffer.vertices() - offset,
entry.getKey().tint,
entry.getKey().emission,
List.copyOf(sprites)));
List.copyOf(sprites),
bounds));
meshCount++;
meshBuilds++;
}
Expand Down Expand Up @@ -427,6 +438,9 @@ static final class Mesh implements RetainedMesh {
final int firstVertex, vertexCount, tint, emission;
final List<TextureAtlasSprite> sprites;

/** Local bounds: min x, y, z, then max x, y, z. */
final float[] bounds;

/**
* Per-mesh state owned by the Live Item Display consumer; it validates the value against its
* own generation before use, since consumers clear independently of the store.
Expand All @@ -439,18 +453,20 @@ static final class Mesh implements RetainedMesh {
int vertexCount,
int tint,
int emission,
List<TextureAtlasSprite> sprites) {
List<TextureAtlasSprite> sprites,
float[] bounds) {
this.type = type;
this.firstVertex = firstVertex;
this.vertexCount = vertexCount;
this.tint = tint;
this.emission = emission;
this.sprites = sprites;
this.bounds = bounds;
}

/** The same material at another place in the buffer, as a new object. */
Mesh at(int first) {
return new Mesh(type, first, vertexCount, tint, emission, sprites);
return new Mesh(type, first, vertexCount, tint, emission, sprites, bounds);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.renderer.SubmitNodeStorage;
import net.minecraft.client.renderer.culling.Frustum;
import net.minecraft.client.renderer.entity.DisplayRenderer;
import net.minecraft.client.renderer.entity.state.EntityRenderState;
import net.minecraft.client.renderer.entity.state.ItemDisplayEntityRenderState;
Expand All @@ -23,6 +24,7 @@
import net.minecraft.world.entity.Display;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.phys.AABB;
import ru.wilyfox.drawless.DrawLess;
import ru.wilyfox.drawless.compat.IrisShaders;
import ru.wilyfox.drawless.compat.RenderModSupport;
Expand Down Expand Up @@ -68,6 +70,10 @@ public final class LiveDisplayGeometry {
private static int visibleMeshCount;
private static long poseReused, poseSubmitted, poseReusedTotal, poseSubmittedTotal;
private static long entityLoopStarted, entityLoopNanos, entityLoopTotal, entityLoopFrames;
private static final long MOVING_REFRESH = 50_000_000L, STABLE_REFRESH = 1_000_000_000L;
private static final double MOVING_MARGIN = 1, STABLE_MARGIN = 0.5;
private static int culled;
private static long culledTotal;

private LiveDisplayGeometry() {}

Expand Down Expand Up @@ -118,6 +124,8 @@ public static void clear() {
visibleMeshCount = 0;
poseReused = poseSubmitted = poseReusedTotal = poseSubmittedTotal = 0;
entityLoopStarted = entityLoopNanos = entityLoopTotal = entityLoopFrames = 0;
culled = 0;
culledTotal = 0;
pose = new PoseStack();
}

Expand Down Expand Up @@ -159,7 +167,7 @@ public static void beginFrame(Minecraft client) {
for (var batch : type.chunks) batch.used = 0;
}
Arrays.fill(reasons, 0);
instances = quads = fallbacks = indexBytes = captureNanos = uploadNanos = 0;
instances = quads = fallbacks = indexBytes = captureNanos = uploadNanos = culled = 0;
frame++;
frameNow = System.nanoTime();
enabled = false;
Expand All @@ -174,6 +182,41 @@ public static void beginFrame(Minecraft client) {
parts.entrySet().removeIf(e -> e.getKey().isRemoved() || frame - e.getValue().seen > 120);
}

/**
* True when a part's last pose lies outside this frame's view, so nothing of it is needed now.
* Only parts already on the GPU qualify; a changed display, or bounds not refreshed for a while,
* take the ordinary path. Ticks and animation are not affected.
*/
public static boolean outsideView(Entity entity, Frustum frustum) {
if (!enabled
|| !DrawLessConfig.get().liveViewCulling
|| !(entity instanceof Display.ItemDisplay item)) return false;
var part = parts.get(item);
if (part == null
|| part.reason != Reason.READY
|| part.used == 0
|| part.render != item.renderState()
|| frameNow - part.boundsChecked > (part.moving ? MOVING_REFRESH : STABLE_REFRESH))
return false;
double margin = part.moving ? MOVING_MARGIN : STABLE_MARGIN;
double x = item.getX(), y = item.getY(), z = item.getZ();
double mx = margin + Math.abs(x - item.xo);
double my = margin + Math.abs(y - item.yo);
double mz = margin + Math.abs(z - item.zo);
if (frustum.isVisible(
new AABB(
x + part.minX - mx,
y + part.minY - my,
z + part.minZ - mz,
x + part.maxX + mx,
y + part.maxY + my,
z + part.maxZ + mz))) return false;
part.seen = frame;
culled++;
culledTotal++;
return true;
}

public static void recordState(Entity entity, EntityRenderState state) {
if (enabled
&& entity instanceof Display.ItemDisplay item
Expand Down Expand Up @@ -218,6 +261,7 @@ public static void finishFrame(Minecraft client, LevelRenderState state) {
else {
stage = sample ? System.nanoTime() : 0;
part.seen = frame;
part.boundsChecked = frameNow;
if (part.matches(item)) {
reason = part.reason;
poseReused++;
Expand Down Expand Up @@ -408,7 +452,7 @@ public static String diagnostic() {
if (reasons[r.ordinal()] > 0) reasonsText.add(r.label + ":" + reasons[r.ordinal()]);
return String.format(
Locale.ROOT,
"%s; status=%s; meshes=%d; quadSets=%d; aliases=%d; parts=%d; interpolatingParts=%d; visibleMeshes=%d; visibleVertices=%d; instances=%d; quads=%d; draws=%d; fallback=%d; localBytes=%d; indexBytes=%d; meshBuilds=%d; indexRebuilds=%d; geometryUploads=%d; geometryUploadedBytes=%d; instanceUploadedBytes=%d; animatedSprites=%d; poseReused=%d; poseSubmitted=%d; poseReusedTotal=%d; poseSubmittedTotal=%d; capture=%.3fms; upload=%.3fms; drawCpu=%.3fms; framesTotal=%d; captureTotalMs=%.3f; uploadTotalMs=%.3f; drawTotalMs=%.3f; admission=%s",
"%s; status=%s; meshes=%d; quadSets=%d; aliases=%d; parts=%d; interpolatingParts=%d; visibleMeshes=%d; visibleVertices=%d; instances=%d; culled=%d; culledTotal=%d; quads=%d; draws=%d; fallback=%d; localBytes=%d; indexBytes=%d; meshBuilds=%d; indexRebuilds=%d; geometryUploads=%d; geometryUploadedBytes=%d; instanceUploadedBytes=%d; animatedSprites=%d; poseReused=%d; poseSubmitted=%d; poseReusedTotal=%d; poseSubmittedTotal=%d; capture=%.3fms; upload=%.3fms; drawCpu=%.3fms; framesTotal=%d; captureTotalMs=%.3f; uploadTotalMs=%.3f; drawTotalMs=%.3f; admission=%s",
liveMode == null ? DrawLessConfig.get().extremeDisplayMode : liveMode,
enabled
? "on"
Expand All @@ -423,6 +467,8 @@ public static String diagnostic() {
visibleMeshCount,
visibleVertices,
instances,
culled,
culledTotal,
quads,
draws,
fallbacks,
Expand Down Expand Up @@ -498,6 +544,13 @@ private static final class Part {
final ArrayList<Instance> instances = new ArrayList<>();
int used, seen;
long indexBytes;

/** Bounds around the entity origin at the last pose, and when they were last confirmed. */
float minX, minY, minZ, maxX, maxY, maxZ;

long boundsChecked;
boolean moving;

ItemStackRenderState layers;
Display.RenderState render;
float interpolation, yRot, xRot, cameraXRot, cameraYRot;
Expand Down Expand Up @@ -535,9 +588,48 @@ void remember(ItemDisplayEntityRenderState state, Reason reason, boolean replaya
this.reason = reason;
this.replayable = replayable;
indexBytes = 0;
if (reason == Reason.READY)
if (reason == Reason.READY) {
for (int i = 0; i < used; i++)
indexBytes += (long) instances.get(i).item.vertexCount / 4 * 6 * 4;
measure(state);
}
}

private void measure(ItemDisplayEntityRenderState state) {
moving = state.interpolationProgress < 1;
minX = minY = minZ = Float.MAX_VALUE;
maxX = maxY = maxZ = -Float.MAX_VALUE;
for (int i = 0; i < used; i++) {
var instance = instances.get(i);
var bounds = instance.item.bounds;
var m = instance.transform;
for (int corner = 0; corner < 8; corner++) {
float cx = bounds[(corner & 1) == 0 ? 0 : 3];
float cy = bounds[(corner & 2) == 0 ? 1 : 4];
float cz = bounds[(corner & 4) == 0 ? 2 : 5];
float x = m.m00() * cx + m.m10() * cy + m.m20() * cz + instance.localX;
float y = m.m01() * cx + m.m11() * cy + m.m21() * cz + instance.localY;
float z = m.m02() * cx + m.m12() * cy + m.m22() * cz + instance.localZ;
minX = Math.min(minX, x);
minY = Math.min(minY, y);
minZ = Math.min(minZ, z);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
maxZ = Math.max(maxZ, z);
}
}
// A billboard turns with the camera, which may move while the part is culled.
if (state.renderState.billboardConstraints() != Display.BillboardConstraints.FIXED) {
float radius =
Math.max(
Math.max(Math.abs(minX), Math.abs(maxX)),
Math.max(
Math.max(Math.abs(minY), Math.abs(maxY)),
Math.max(Math.abs(minZ), Math.abs(maxZ))));
radius *= (float) Math.sqrt(3);
minX = minY = minZ = -radius;
maxX = maxY = maxZ = radius;
}
}
}

Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/assets/drawless/lang/en_us.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
"drawless.setting.batching.description": "Expanded combines more draws but can change overlapping layers. Choose Limited or Off if layers look wrong.",
"drawless.setting.text_reuse": "Text buffer reuse",
"drawless.setting.text_reuse.description": "Experimental. Reuses the current text/name-tag buffer within a preparation pass. Off by default.",
"drawless.setting.live_view_culling": "Skip displays outside the view",
"drawless.setting.live_view_culling.description": "Item Displays on the GPU that are outside the camera view are skipped for the frame. Ticks and animation keep running. A part moving very quickly into view may appear a moment late.",
"drawless.setting.model_cache": "Display model cache",
"drawless.setting.model_cache.description": "Reuses Item Display model layers and refreshes them within a bounded CPU budget.",
"drawless.setting.adaptive_budget": "Adaptive model budget",
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/assets/drawless/lang/ru_ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
"drawless.setting.batching.description": "Расширенный режим объединяет больше отрисовок, но может менять наложение слоёв. При артефактах выберите ограниченный режим или выключите функцию.",
"drawless.setting.text_reuse": "Буферы текста",
"drawless.setting.text_reuse.description": "Экспериментально. Переиспользует текущий буфер текста и имён в пределах прохода подготовки. По умолчанию выключено.",
"drawless.setting.live_view_culling": "Пропускать дисплеи вне экрана",
"drawless.setting.live_view_culling.description": "Item Display на видеокарте, которые не попадают в обзор камеры, пропускаются в этом кадре. Тики и анимация продолжают работать. Часть, очень быстро влетающая в кадр, может появиться с небольшой задержкой.",
"drawless.setting.model_cache": "Кеш моделей Display",
"drawless.setting.model_cache.description": "Переиспользует слои моделей Item Display и обновляет их в пределах бюджета CPU.",
"drawless.setting.adaptive_budget": "Адаптивный бюджет",
Expand Down
Loading