diff --git a/Tools/Dev/build.gradle b/Tools/Dev/build.gradle index 9ffeac8..89ff387 100644 --- a/Tools/Dev/build.gradle +++ b/Tools/Dev/build.gradle @@ -24,6 +24,12 @@ sourceSets.test.runtimeClasspath += sourceSets.developer.output def lwjglVersion = '3.3.2' dependencies { + add('developerImplementation', 'net.runelite:cache:1.13.+') { + exclude group: 'org.slf4j', module: 'slf4j-simple' + } + + add('developerImplementation', 'org.mockito:mockito-core:5.14.2') + add('developerImplementation', platform("org.lwjgl:lwjgl-bom:$lwjglVersion")) add('developerImplementation', "org.lwjgl:lwjgl") add('developerImplementation', "org.lwjgl:lwjgl-assimp") @@ -41,6 +47,30 @@ tasks.named('processDeveloperResources') { } } +tasks.register('simulatedRender', JavaExec) { + group = 'application' + description = 'Draws a cache scene with the real 117 HD renderer, without RuneLite' + dependsOn tasks.named('classes'), tasks.named('developerClasses') + classpath = sourceSets.developer.runtimeClasspath + mainClass = 'rs117.hd.dev.sceneloader.standalone.ui.HdPreview' + workingDir = project.rootProject.projectDir + jvmArgs '-ea', '-Xmx2G' + if (project.hasProperty('simArgs')) + args project.property('simArgs').toString().split('\\s+') +} + +tasks.register('benchmark', JavaExec) { + group = 'verification' + description = 'Times 117 HD drawing a cache scene, and writes the frame timers to a CSV' + dependsOn tasks.named('classes'), tasks.named('developerClasses') + classpath = sourceSets.developer.runtimeClasspath + mainClass = 'rs117.hd.dev.sceneloader.standalone.headless.HdBenchmark' + workingDir = project.rootProject.projectDir + jvmArgs '-ea', '-Xmx2G' + if (project.hasProperty('simArgs')) + args project.property('simArgs').toString().split('\\s+') +} + tasks.register('developerJar', Jar) { dependsOn tasks.named('classes'), tasks.named('developerClasses'), tasks.named('processDeveloperResources') from sourceSets.developer.output diff --git a/Tools/Dev/java/rs117/hd/DeveloperConfig.java b/Tools/Dev/java/rs117/hd/DeveloperConfig.java index 60213ba..b83bddd 100644 --- a/Tools/Dev/java/rs117/hd/DeveloperConfig.java +++ b/Tools/Dev/java/rs117/hd/DeveloperConfig.java @@ -2,8 +2,20 @@ import net.runelite.client.config.Config; import net.runelite.client.config.ConfigGroup; +import net.runelite.client.config.ConfigItem; @ConfigGroup("117hd-developer") public interface DeveloperConfig extends Config { String CONFIG_GROUP = "117hd-developer"; + + String KEY_CACHE_SCENE = "cacheScene"; + @ConfigItem( + keyName = KEY_CACHE_SCENE, + name = "Cache Scene", + description = "Add the 117 HD Cache Scene sidebar, for loading any region straight from the cache without travelling there", + position = 1 + ) + default boolean cacheScene() { + return true; + } } diff --git a/Tools/Dev/java/rs117/hd/DeveloperPlugin.java b/Tools/Dev/java/rs117/hd/DeveloperPlugin.java index c784576..4f026a4 100644 --- a/Tools/Dev/java/rs117/hd/DeveloperPlugin.java +++ b/Tools/Dev/java/rs117/hd/DeveloperPlugin.java @@ -1,15 +1,18 @@ package rs117.hd; import com.google.inject.Provides; +import javax.annotation.Nullable; import javax.inject.Inject; -import javax.inject.Provider; import javax.inject.Singleton; import lombok.extern.slf4j.Slf4j; import net.runelite.client.callback.ClientThread; import net.runelite.client.config.ConfigManager; +import net.runelite.client.eventbus.Subscribe; +import net.runelite.client.events.ConfigChanged; import net.runelite.client.plugins.Plugin; import net.runelite.client.plugins.PluginDescriptor; import net.runelite.client.plugins.PluginManager; +import rs117.hd.dev.sceneloader.SceneLoader; import rs117.hd.model.ModelExporter; import rs117.hd.model.ModelImporter; import rs117.hd.utils.Props; @@ -34,9 +37,16 @@ public class DeveloperPlugin extends Plugin { @Inject private PluginManager pluginManager; + @Inject + private DeveloperConfig config; + private ModelExporter modelExporter; private ModelImporter modelImporter; + // From 117 HD's injector, so it works with the running 117 HD's renderer, scene & managers + @Nullable + private volatile SceneLoader sceneLoader; + @Provides DeveloperConfig provideConfig(ConfigManager configManager) { return configManager.getConfig(DeveloperConfig.class); @@ -57,12 +67,22 @@ protected void startUp() { modelExporter = injector.getInstance(ModelExporter.class); modelImporter = injector.getInstance(ModelImporter.class); + var loader = injector.getInstance(SceneLoader.class); + sceneLoader = loader; + if (config.cacheScene()) + loader.startUp(); + return true; }); } @Override protected void shutDown() { + var loader = sceneLoader; + sceneLoader = null; + if (loader != null) + loader.shutDown(); + clientThread.invoke(() -> { if (modelImporter != null) modelImporter.close(); @@ -72,4 +92,21 @@ protected void shutDown() { modelExporter = null; }); } + + @Subscribe + public void onConfigChanged(ConfigChanged event) { + if (!event.getGroup().equals(DeveloperConfig.CONFIG_GROUP)) + return; + + if (event.getKey().equals(DeveloperConfig.KEY_CACHE_SCENE)) { + var loader = sceneLoader; + if (loader == null) + return; + if (config.cacheScene()) { + loader.startUp(); + } else { + loader.shutDown(); + } + } + } } diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/FreeCamera.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/FreeCamera.java new file mode 100644 index 0000000..198b882 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/FreeCamera.java @@ -0,0 +1,445 @@ +package rs117.hd.dev.sceneloader; + +import java.awt.KeyEventDispatcher; +import java.awt.KeyboardFocusManager; +import java.awt.event.KeyEvent; +import java.awt.event.MouseEvent; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import javax.swing.SwingUtilities; +import javax.swing.text.JTextComponent; +import javax.inject.Inject; +import javax.inject.Singleton; +import lombok.extern.slf4j.Slf4j; +import net.runelite.api.Client; +import net.runelite.api.Scene; +import net.runelite.api.WorldView; +import net.runelite.api.events.BeforeRender; +import net.runelite.client.eventbus.EventBus; +import net.runelite.client.eventbus.Subscribe; +import net.runelite.client.input.MouseAdapter; +import net.runelite.client.input.MouseManager; + +@Slf4j +@Singleton +public class FreeCamera { + private static final int ANGLE_UNITS = 16384; + private static final float RADIANS_PER_UNIT = (float) (2 * Math.PI / ANGLE_UNITS); + private static final int QUARTER_TURN = ANGLE_UNITS / 4; + + private static final float CLIENT_FRAMES_PER_SECOND = 50; + + private static final int NORMAL_SPEED = 12; + private static final int SLOW_SPEED = 6; + private static final int SPEED_FRACTION = 16; + private static final float SPEED_GAINED_PER_FRAME = 1 / 8f; + private static final float SPEED_KEPT_PER_FRAME = 0.9f; + + private static final float MIN_PITCH = 1 * RADIANS_PER_UNIT; + private static final float MAX_PITCH = 4160 * RADIANS_PER_UNIT; + + private static final int YAW_TURN_UNITS = 24 << 3; + private static final int PITCH_TURN_UNITS = 12 << 3; + private static final float TURN_GAP_CLOSED_PER_FRAME = 0.5f; + + private static final float DRAG_UNITS_PER_PIXEL = 8; + + private static final float MAX_STEP_SECONDS = 0.1f; + + @Inject + private Client client; + + @Inject + private MouseManager mouseManager; + + @Inject + private EventBus eventBus; + + private boolean started; + private volatile boolean enabled; + private volatile float speed = 1; + + private final float[] position = new float[3]; + private volatile float yaw, pitch; + + private final float[] gamePosition = new float[3]; + private volatile float gameYaw, gamePitch; + private volatile boolean placed; + + private final Set heldKeys = ConcurrentHashMap.newKeySet(); + private long lastMoveNanos; + + private float travelSpeed; + private int travelHeading = -1; + private int travelVertical; + private float yawSpeed, pitchSpeed; + private boolean relaxedPitch; + + private static final float VIEWING_DISTANCE = 6 * 128; + private static final float AIM_ABOVE_GROUND = 128; + + private final KeyEventDispatcher keys = this::dispatchKey; + + private volatile boolean dragging; + private volatile int dragX, dragY; + + private final MouseAdapter lookAround = new MouseAdapter() { + @Override + public MouseEvent mousePressed(MouseEvent event) { + if (enabled && SwingUtilities.isMiddleMouseButton(event)) { + dragging = true; + dragX = event.getX(); + dragY = event.getY(); + event.consume(); + } + return event; + } + + @Override + public MouseEvent mouseDragged(MouseEvent event) { + if (!dragging || !enabled) + return event; + + int x = event.getX(); + int y = event.getY(); + turnUnits(-(x - dragX) * DRAG_UNITS_PER_PIXEL, (y - dragY) * DRAG_UNITS_PER_PIXEL); + dragX = x; + dragY = y; + event.consume(); + return event; + } + + @Override + public MouseEvent mouseReleased(MouseEvent event) { + if (dragging && SwingUtilities.isMiddleMouseButton(event)) { + dragging = false; + event.consume(); + } + return event; + } + }; + + public void startUp() { + if (started) + return; + started = true; + eventBus.register(this); + KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keys); + mouseManager.registerMouseListener(lookAround); + } + + public void shutDown() { + if (!started) + return; + started = false; + eventBus.unregister(this); + KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(keys); + mouseManager.unregisterMouseListener(lookAround); + setEnabled(false); + restoreGameCamera(); + } + + private void restoreGameCamera() { + if (!relaxedPitch) + return; + relaxedPitch = false; + client.setCameraPitchRelaxerEnabled(false); + } + + public boolean isEnabled() { + return enabled; + } + + public void setSpeed(float speed) { + this.speed = speed; + } + + public void setEnabled(boolean enabled) { + if (this.enabled == enabled) + return; + + heldKeys.clear(); + lastMoveNanos = 0; + dragging = false; + travelSpeed = 0; + travelHeading = -1; + travelVertical = 0; + yawSpeed = 0; + pitchSpeed = 0; + + this.enabled = enabled; + if (enabled) { + placed = false; + takeKeyboardFocus(); + } + } + + public void goTo(float x, float y, float z) { + if (!enabled) + setEnabled(true); + + float cosPitch = (float) Math.cos(pitch); + float forwardX = -(float) Math.sin(yaw) * cosPitch; + float forwardZ = (float) Math.cos(yaw) * cosPitch; + float forwardY = (float) Math.sin(pitch); + + float aimY = y - AIM_ABOVE_GROUND; + position[0] = x - forwardX * VIEWING_DISTANCE; + position[1] = aimY - forwardY * VIEWING_DISTANCE; + position[2] = z - forwardZ * VIEWING_DISTANCE; + + placed = true; + travelSpeed = 0; + travelHeading = -1; + travelVertical = 0; + } + + private void takeKeyboardFocus() { + SwingUtilities.invokeLater(() -> { + var canvas = client.getCanvas(); + if (canvas != null) + canvas.requestFocusInWindow(); + }); + } + + @Subscribe + public void onBeforeRender(BeforeRender event) { + if (relaxedPitch != enabled) { + relaxedPitch = enabled; + client.setCameraPitchRelaxerEnabled(enabled); + } + + long now = System.nanoTime(); + float seconds = lastMoveNanos == 0 ? 0 : Math.min((now - lastMoveNanos) / 1e9f, MAX_STEP_SECONDS); + lastMoveNanos = now; + + if (!enabled || seconds <= 0) + return; + + if (KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow() == null) { + heldKeys.clear(); + dragging = false; + } + + float frames = seconds * CLIENT_FRAMES_PER_SECOND; + turnWithKeys(frames); + travel(frames); + pointGameCameraAlong(); + } + + private void pointGameCameraAlong() { + client.setCameraYawTarget(toJagexUnits(yaw) & 2047); + client.setCameraPitchTarget(toJagexUnits(pitch)); + } + + private static int toJagexUnits(float radians) { + return Math.round(radians / (float) (2 * Math.PI) * 2048); + } + + private void turnWithKeys(float frames) { + int wantedYaw = heldKeys.contains(KeyEvent.VK_LEFT) ? -YAW_TURN_UNITS + : heldKeys.contains(KeyEvent.VK_RIGHT) ? YAW_TURN_UNITS : 0; + int wantedPitch = heldKeys.contains(KeyEvent.VK_UP) ? PITCH_TURN_UNITS + : heldKeys.contains(KeyEvent.VK_DOWN) ? -PITCH_TURN_UNITS : 0; + + float closed = 1 - (float) Math.pow(1 - TURN_GAP_CLOSED_PER_FRAME, frames); + yawSpeed += (wantedYaw - yawSpeed) * closed; + pitchSpeed += (wantedPitch - pitchSpeed) * closed; + + turnUnits(yawSpeed / 2 * frames, pitchSpeed / 2 * frames); + } + + private void travel(float frames) { + int heading = headingOf(heldKeys); + int vertical = verticalOf(heldKeys); + + float wanted = 0; + if (heading >= 0 || vertical != 0) { + int perFrame = heldKeys.contains(KeyEvent.VK_CONTROL) ? SLOW_SPEED : NORMAL_SPEED; + wanted = perFrame * speed * SPEED_FRACTION; + travelHeading = heading; + travelVertical = vertical; + } + + if (travelSpeed < wanted) { + travelSpeed = Math.min(wanted, travelSpeed + wanted * SPEED_GAINED_PER_FRAME * frames); + } else if (travelSpeed > wanted) { + travelSpeed *= (float) Math.pow(SPEED_KEPT_PER_FRAME, frames); + if (travelSpeed < 1) { + travelSpeed = 0; + travelHeading = -1; + travelVertical = 0; + } + } + if (travelSpeed <= 0) + return; + + float distance = travelSpeed / SPEED_FRACTION * frames; + if (travelHeading >= 0) { + float angle = (travelHeading - yaw / RADIANS_PER_UNIT) * RADIANS_PER_UNIT; + position[0] += distance * (float) Math.sin(angle); + position[2] += distance * (float) Math.cos(angle); + } + position[1] += travelVertical * distance; + } + + static int headingOf(Set held) { + int heading = -1; + if (held.contains(KeyEvent.VK_W)) { + heading = 0; + } else if (held.contains(KeyEvent.VK_S)) { + heading = QUARTER_TURN * 2; + } + + if (held.contains(KeyEvent.VK_A)) { + heading = heading == 0 ? QUARTER_TURN * 7 / 2 + : heading == QUARTER_TURN * 2 ? QUARTER_TURN * 5 / 2 + : QUARTER_TURN * 3; + } else if (held.contains(KeyEvent.VK_D)) { + heading = heading == 0 ? QUARTER_TURN / 2 + : heading == QUARTER_TURN * 2 ? QUARTER_TURN * 3 / 2 + : QUARTER_TURN; + } + return heading; + } + + static int verticalOf(Set held) { + boolean up = held.contains(KeyEvent.VK_R) || held.contains(KeyEvent.VK_E) + || held.contains(KeyEvent.VK_SPACE); + boolean down = held.contains(KeyEvent.VK_F) || held.contains(KeyEvent.VK_Q) + || held.contains(KeyEvent.VK_SHIFT); + if (up == down) + return 0; + return up ? -1 : 1; + } + + private void turnUnits(float yawUnits, float pitchUnits) { + if (yawUnits == 0 && pitchUnits == 0) + return; + yaw += yawUnits * RADIANS_PER_UNIT; + pitch = clampPitch(pitch + pitchUnits * RADIANS_PER_UNIT); + } + + private static float clampPitch(float pitch) { + return Math.max(MIN_PITCH, Math.min(MAX_PITCH, pitch)); + } + + static int cameraValuesAt(Object[] args) { + if (args == null || args.length < 6) + return -1; + if (args[0] instanceof Scene && ((Scene) args[0]).getWorldViewId() != WorldView.TOPLEVEL) + return -1; + + for (int i = 0; i + 5 <= args.length; i++) + if (args[i] instanceof Float) + return i; + return -1; + } + + void interceptPreSceneDraw(Object[] args) { + int first = cameraValuesAt(args); + if (first >= 0) + swapCamera(args, first, true); + } + + void interceptDrawScene(Object[] args) { + if (args == null || args.length < 6) + return; + swapCamera(args, args.length - 6, false); + } + + private void swapCamera(Object[] args, int first, boolean asFloat) { + gamePosition[0] = ((Number) args[first]).floatValue(); + gamePosition[1] = ((Number) args[first + 1]).floatValue(); + gamePosition[2] = ((Number) args[first + 2]).floatValue(); + gamePitch = ((Number) args[first + 3]).floatValue(); + gameYaw = ((Number) args[first + 4]).floatValue(); + + if (!enabled) + return; + + if (!placed) { + System.arraycopy(gamePosition, 0, position, 0, 3); + yaw = gameYaw; + pitch = clampPitch(gamePitch); + placed = true; + log.debug( + "Flying from {}, {}, {} facing yaw {} pitch {}", + position[0], position[1], position[2], yaw, pitch + ); + } + + if (asFloat) { + args[first] = position[0]; + args[first + 1] = position[1]; + args[first + 2] = position[2]; + args[first + 3] = pitch; + args[first + 4] = yaw; + } else { + args[first] = (double) position[0]; + args[first + 1] = (double) position[1]; + args[first + 2] = (double) position[2]; + args[first + 3] = (double) pitch; + args[first + 4] = (double) yaw; + } + } + + private boolean dispatchKey(KeyEvent event) { + if (!enabled || isTyping()) + return false; + + int id = event.getID(); + int code = id == KeyEvent.KEY_TYPED + ? KeyEvent.getExtendedKeyCodeForChar(event.getKeyChar()) + : event.getKeyCode(); + + if (isModifier(code)) { + hold(id, code); + return false; + } + if (!isCameraKey(code)) + return false; + + hold(id, code); + return true; + } + + private void hold(int eventId, int keyCode) { + if (eventId == KeyEvent.KEY_PRESSED) { + if (heldKeys.isEmpty()) + log.debug("Flying on {}", KeyEvent.getKeyText(keyCode)); + heldKeys.add(keyCode); + } else if (eventId == KeyEvent.KEY_RELEASED) { + heldKeys.remove(keyCode); + } + } + + private static boolean isModifier(int keyCode) { + return keyCode == KeyEvent.VK_SHIFT || keyCode == KeyEvent.VK_CONTROL; + } + + private static boolean isTyping() { + return KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() instanceof JTextComponent; + } + + private static boolean isCameraKey(int keyCode) { + switch (keyCode) { + case KeyEvent.VK_W: + case KeyEvent.VK_A: + case KeyEvent.VK_S: + case KeyEvent.VK_D: + case KeyEvent.VK_Q: + case KeyEvent.VK_E: + case KeyEvent.VK_R: + case KeyEvent.VK_F: + case KeyEvent.VK_SPACE: + case KeyEvent.VK_LEFT: + case KeyEvent.VK_RIGHT: + case KeyEvent.VK_UP: + case KeyEvent.VK_DOWN: + return true; + default: + return false; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/ModelPreview.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/ModelPreview.java new file mode 100644 index 0000000..a30b09a --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/ModelPreview.java @@ -0,0 +1,236 @@ +package rs117.hd.dev.sceneloader; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.Graphics; +import java.awt.RenderingHints; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.annotation.Nullable; +import javax.swing.JComponent; +import javax.swing.ToolTipManager; +import net.runelite.client.ui.ColorScheme; +import net.runelite.client.ui.FontManager; +import rs117.hd.dev.sceneloader.scene.BuiltModel; + +public class ModelPreview extends JComponent { + private static final double START_YAW = 0.6; + private static final double START_PITCH = 0.5; + private static final double RADIANS_PER_PIXEL = 0.012; + private static final double MAX_PITCH = Math.PI / 2 - 0.05; + private static final int CAPTION_HEIGHT = 13; + private static final int PADDING = 4; + + @Nullable + private BuiltModel model; + @Nullable + private int[] faceColors; + private String caption = ""; + private String emptyText = ""; + + private double yaw = START_YAW; + private double pitch = START_PITCH; + + private float[] rotatedX = new float[0], rotatedY = new float[0], rotatedZ = new float[0]; + private int[] faceOrder = new int[0]; + private float[] faceDepth = new float[0]; + private final int[] polyX = new int[3], polyY = new int[3]; + + public ModelPreview(int size) { + var bounds = new Dimension(size, size + CAPTION_HEIGHT); + setPreferredSize(bounds); + setMinimumSize(bounds); + setMaximumSize(bounds); + setFont(FontManager.getRunescapeSmallFont()); + ToolTipManager.sharedInstance().registerComponent(this); + + var drag = new MouseAdapter() { + private int lastX, lastY; + + @Override + public void mousePressed(MouseEvent e) { + lastX = e.getX(); + lastY = e.getY(); + } + + @Override + public void mouseDragged(MouseEvent e) { + yaw -= (e.getX() - lastX) * RADIANS_PER_PIXEL; + pitch = Math.max(-MAX_PITCH, Math.min(MAX_PITCH, pitch + (e.getY() - lastY) * RADIANS_PER_PIXEL)); + lastX = e.getX(); + lastY = e.getY(); + repaint(); + } + + @Override + public void mouseClicked(MouseEvent e) { + if (e.getClickCount() == 2) { + yaw = START_YAW; + pitch = START_PITCH; + repaint(); + } + } + }; + addMouseListener(drag); + addMouseMotionListener(drag); + } + + public static final class Shape { + final BuiltModel model; + final int[] faceColors; + + public Shape(BuiltModel model, int[] faceColors) { + this.model = model; + this.faceColors = faceColors; + } + } + + public void show(@Nullable Shape shape, String caption, String emptyText) { + this.model = shape == null ? null : shape.model; + this.faceColors = shape == null ? null : shape.faceColors; + this.caption = caption; + this.emptyText = emptyText; + setToolTipText(caption.isEmpty() ? null : caption + " — drag to turn, double click to straighten"); + repaint(); + } + + public String getCaption() { + return caption; + } + + public void matchAngleOf(ModelPreview other) { + yaw = other.yaw; + pitch = other.pitch; + repaint(); + } + + @Override + protected void paintComponent(Graphics graphics) { + Graphics2D g = (Graphics2D) graphics.create(); + try { + int width = getWidth(); + int height = getHeight() - CAPTION_HEIGHT; + + g.setColor(ColorScheme.DARKER_GRAY_COLOR); + g.fillRect(0, 0, width, height); + g.setColor(ColorScheme.MEDIUM_GRAY_COLOR); + g.drawRect(0, 0, width - 1, height - 1); + + if (model != null && faceColors != null && model.getFaceCount() > 0) { + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + paintModel(g, width, height); + } else { + g.setColor(ColorScheme.LIGHT_GRAY_COLOR); + g.setFont(getFont()); + int textWidth = g.getFontMetrics().stringWidth(emptyText); + g.drawString(emptyText, (width - textWidth) / 2, height / 2); + } + + if (!caption.isEmpty()) { + g.setColor(Color.LIGHT_GRAY); + g.setFont(getFont()); + int textWidth = g.getFontMetrics().stringWidth(caption); + g.drawString(caption, Math.max(0, (width - textWidth) / 2), height + CAPTION_HEIGHT - 3); + } + } finally { + g.dispose(); + } + } + + private void paintModel(Graphics2D g, int width, int height) { + assert model != null && faceColors != null; + + int vertexCount = model.getVerticesCount(); + float[] sourceX = model.getVerticesX(); + float[] sourceY = model.getVerticesY(); + float[] sourceZ = model.getVerticesZ(); + + if (rotatedX.length < vertexCount) { + rotatedX = new float[vertexCount]; + rotatedY = new float[vertexCount]; + rotatedZ = new float[vertexCount]; + } + + float sinYaw = (float) Math.sin(yaw), cosYaw = (float) Math.cos(yaw); + float sinPitch = (float) Math.sin(pitch), cosPitch = (float) Math.cos(pitch); + + float minX = Float.MAX_VALUE, maxX = -Float.MAX_VALUE; + float minY = Float.MAX_VALUE, maxY = -Float.MAX_VALUE; + for (int v = 0; v < vertexCount; v++) { + float x = sourceX[v], y = sourceY[v], z = sourceZ[v]; + + float turnedX = x * cosYaw - z * sinYaw; + float turnedZ = x * sinYaw + z * cosYaw; + float tippedY = y * cosPitch - turnedZ * sinPitch; + float tippedZ = y * sinPitch + turnedZ * cosPitch; + + rotatedX[v] = turnedX; + rotatedY[v] = tippedY; + rotatedZ[v] = tippedZ; + + if (turnedX < minX) minX = turnedX; + if (turnedX > maxX) maxX = turnedX; + if (tippedY < minY) minY = tippedY; + if (tippedY > maxY) maxY = tippedY; + } + + float spanX = Math.max(1, maxX - minX); + float spanY = Math.max(1, maxY - minY); + float scale = Math.min((width - 2 * PADDING) / spanX, (height - 2 * PADDING) / spanY); + float offsetX = width / 2f - (minX + maxX) / 2f * scale; + float offsetY = height / 2f - (minY + maxY) / 2f * scale; + + int faceCount = model.getFaceCount(); + int[] indicesA = model.getFaceIndices1(); + int[] indicesB = model.getFaceIndices2(); + int[] indicesC = model.getFaceIndices3(); + + if (faceOrder.length < faceCount) { + faceOrder = new int[faceCount]; + faceDepth = new float[faceCount]; + } + + int drawable = 0; + for (int f = 0; f < faceCount; f++) { + if (faceColors[f] < 0) + continue; + int a = indicesA[f], b = indicesB[f], c = indicesC[f]; + if (a >= vertexCount || b >= vertexCount || c >= vertexCount) + continue; + faceDepth[f] = rotatedZ[a] + rotatedZ[b] + rotatedZ[c]; + faceOrder[drawable++] = f; + } + + sortByDepthDescending(faceOrder, faceDepth, drawable); + + for (int i = 0; i < drawable; i++) { + int f = faceOrder[i]; + int a = indicesA[f], b = indicesB[f], c = indicesC[f]; + + polyX[0] = Math.round(rotatedX[a] * scale + offsetX); + polyX[1] = Math.round(rotatedX[b] * scale + offsetX); + polyX[2] = Math.round(rotatedX[c] * scale + offsetX); + polyY[0] = Math.round(rotatedY[a] * scale + offsetY); + polyY[1] = Math.round(rotatedY[b] * scale + offsetY); + polyY[2] = Math.round(rotatedY[c] * scale + offsetY); + + g.setColor(new Color(faceColors[f])); + g.fillPolygon(polyX, polyY, 3); + g.drawPolygon(polyX, polyY, 3); + } + } + + private static void sortByDepthDescending(int[] order, float[] depth, int count) { + for (int i = 1; i < count; i++) { + int face = order[i]; + float d = depth[face]; + int j = i - 1; + while (j >= 0 && depth[order[j]] < d) { + order[j + 1] = order[j]; + j--; + } + order[j + 1] = face; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoader.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoader.java new file mode 100644 index 0000000..9deb584 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoader.java @@ -0,0 +1,862 @@ +package rs117.hd.dev.sceneloader; + +import java.awt.Color; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.swing.SwingUtilities; +import lombok.extern.slf4j.Slf4j; +import net.runelite.api.Actor; +import net.runelite.api.Client; +import net.runelite.api.GameState; +import net.runelite.api.Model; +import net.runelite.api.Projection; +import net.runelite.api.Renderable; +import net.runelite.api.Scene; +import net.runelite.api.WorldView; +import net.runelite.api.events.GameTick; +import net.runelite.api.hooks.DrawCallbacks; +import net.runelite.client.callback.ClientThread; +import net.runelite.client.callback.RenderCallback; +import net.runelite.client.callback.RenderCallbackManager; +import net.runelite.client.eventbus.EventBus; +import net.runelite.client.eventbus.Subscribe; +import net.runelite.client.ui.ClientToolbar; +import net.runelite.client.ui.NavigationButton; +import rs117.hd.HdPlugin; +import rs117.hd.dev.sceneloader.devtools.CameraOverlay; +import rs117.hd.dev.sceneloader.devtools.DevToolBridge; +import rs117.hd.dev.sceneloader.devtools.LocationOverlay; +import rs117.hd.dev.sceneloader.devtools.SceneToolsOverlay; +import rs117.hd.dev.sceneloader.devtools.SelectionHighlight; +import rs117.hd.dev.sceneloader.scene.BuiltScene; +import rs117.hd.dev.sceneloader.scene.Definitions; +import rs117.hd.dev.sceneloader.scene.SceneBuilder; +import rs117.hd.dev.sceneloader.scene.VariantObject; +import rs117.hd.dev.sceneloader.scene.VariantOptions; +import rs117.hd.renderer.zone.ZoneRenderer; +import rs117.hd.scene.GamevalManager; + +import static net.runelite.api.Constants.MAX_Z; +import static rs117.hd.dev.sceneloader.scene.SceneBuilder.OFFSET; +import static rs117.hd.renderer.zone.SceneManager.NUM_ZONES; + +@Slf4j +@Singleton +public class SceneLoader implements RenderCallback { + @Inject + private Client client; + + @Inject + private ClientThread clientThread; + + @Inject + private ClientToolbar clientToolbar; + + @Inject + private EventBus eventBus; + + @Inject + private HdPlugin plugin; + + @Inject + private GamevalManager gamevalManager; + + @Inject + private RenderCallbackManager renderCallbackManager; + + @Inject + private FreeCamera camera; + + @Inject + private SelectionHighlight highlight; + + @Inject + private DevToolBridge runeliteDevTools; + + @Inject + private SceneToolsOverlay runeliteDevOverlay; + + @Inject + private LocationOverlay runeliteLocation; + + @Inject + private CameraOverlay runeliteCamera; + + private boolean started; + private NavigationButton button; + private SceneLoaderPanel panel; + + private ExecutorService worker; + + @Nullable + private volatile Definitions defs; + @Nullable + private volatile SceneBuilder builder; + + @Nullable + private volatile BuiltScene loaded; + private volatile boolean keepLoaded = true; + private volatile boolean loading; + + private volatile int plane; + private volatile boolean planesBelow = true; + private volatile boolean showRoofs; + private volatile Set allRoofIds = Set.of(); + private volatile boolean wantFreeCamera = true; + + private final VariantOptions variants = new VariantOptions(); + private volatile int lastWorldX = 3222, lastWorldY = 3218, lastChunks; + @Nullable + private volatile int[] lastStitched; + + @Nullable + private DrawCallbacks wrapped; + @Nullable + private DrawCallbacks wrapper; + + public void startUp() { + if (started) + return; + started = true; + eventBus.register(this); + renderCallbackManager.register(this); + camera.startUp(); + highlight.startUp(); + runeliteDevOverlay.startUp(); + runeliteLocation.startUp(); + runeliteCamera.startUp(); + worker = Executors.newSingleThreadExecutor(runnable -> { + Thread thread = new Thread(runnable, "117 HD cache scene"); + thread.setDaemon(true); + return thread; + }); + + SwingUtilities.invokeLater(() -> { + if (button != null) + return; + panel = new SceneLoaderPanel(this); + button = NavigationButton.builder() + .tooltip("117 HD Cache Scene") + .icon(SceneLoaderPanel.createIcon()) + .priority(2) + .panel(panel) + .build(); + clientToolbar.addNavigation(button); + }); + } + + public void shutDown() { + if (!started) + return; + started = false; + eventBus.unregister(this); + renderCallbackManager.unregister(this); + camera.shutDown(); + highlight.shutDown(); + runeliteDevOverlay.shutDown(); + runeliteLocation.shutDown(); + runeliteCamera.shutDown(); + + restoreGameScene(); + releaseDetailDistance(); + runeliteDevTools.standDown(); + clientThread.invoke(this::unwrap); + + SwingUtilities.invokeLater(() -> { + if (panel != null) + panel.closeMap(); + if (button != null) { + clientToolbar.removeNavigation(button); + button = null; + panel = null; + } + }); + + if (worker != null) { + worker.shutdownNow(); + worker = null; + } + + var open = defs; + defs = null; + builder = null; + if (open != null) { + try { + open.close(); + } catch (Exception ex) { + log.warn("Failed to close the cache", ex); + } + } + } + + Client client() { + return client; + } + + public void setPlane(int plane) { + this.plane = plane; + } + + public void setPlanesBelow(boolean planesBelow) { + this.planesBelow = planesBelow; + } + + public void setShowRoofs(boolean showRoofs) { + this.showRoofs = showRoofs; + } + + private void overrideLevels(Object[] args, int cameraValuesAt) { + int levels = cameraValuesAt + 5; + if (levels + 3 >= args.length) + return; + + int level = Math.max(0, Math.min(MAX_Z - 1, plane)); + args[levels] = planesBelow ? 0 : level; + args[levels + 1] = level; + args[levels + 2] = MAX_Z - 1; + args[levels + 3] = showRoofs ? Set.of() : allRoofIds; + } + + private static final int DETAIL_DISTANCE_WHILE_LOADED = 320; + + private volatile int detailDistanceBefore = -1; + + private void holdDetailDistanceOpen() { + if (plugin.configDetailDrawDistance == DETAIL_DISTANCE_WHILE_LOADED) + return; + if (detailDistanceBefore < 0) + detailDistanceBefore = plugin.configDetailDrawDistance; + plugin.configDetailDrawDistance = DETAIL_DISTANCE_WHILE_LOADED; + } + + private void releaseDetailDistance() { + if (detailDistanceBefore < 0) + return; + plugin.configDetailDrawDistance = detailDistanceBefore; + detailDistanceBefore = -1; + } + + private void drawDynamics() { + var scene = loaded; + if (scene == null || scene.getDynamics().isEmpty()) + return; + + if (!(plugin.renderer instanceof ZoneRenderer)) + return; + Projection projection = ((ZoneRenderer) plugin.renderer).sceneCamera; + + int cycle = client.getGameCycle(); + + int level = Math.max(0, Math.min(MAX_Z - 1, plane)); + int minLevel = planesBelow ? 0 : level; + var hiddenRoofIds = showRoofs ? Set.of() : allRoofIds; + int[][][] roofs = scene.getRoofs(); + + int drawn = 0; + for (BuiltScene.Dynamic dynamic : scene.getDynamics()) { + if (!isDrawnAt(dynamic, roofs, minLevel, level, hiddenRoofIds)) + continue; + + Model model = dynamic.renderable.modelAt(cycle); + if (model == null) + continue; + + plugin.renderer.drawDynamic( + -1, projection, scene, dynamic.tileObject, dynamic.renderable, model, + dynamic.orientation, dynamic.x, dynamic.y, dynamic.z + ); + drawn++; + } + reportDynamics(scene, cycle, drawn); + } + + private static boolean isDrawnAt( + BuiltScene.Dynamic dynamic, int[][][] roofs, int minLevel, int level, Set hiddenRoofIds + ) { + int objectLevel = dynamic.tileObject.getPlane(); + if (objectLevel < minLevel) + return false; + if (objectLevel <= level || objectLevel >= MAX_Z || hiddenRoofIds.isEmpty()) + return true; + + int tileX = (dynamic.x >> 7) + OFFSET; + int tileZ = (dynamic.z >> 7) + OFFSET; + var plan = roofs[objectLevel]; + if (tileX < 0 || tileX >= plan.length || tileZ < 0 || tileZ >= plan[tileX].length) + return true; + + int roofId = plan[tileX][tileZ]; + return roofId == 0 || !hiddenRoofIds.contains(roofId); + } + + /** + * Hands 117 HD the scene a zone at a time, solid parts first and see through parts last. + * + *

This is the game's job normally, and it does it by walking its own scene outwards from its own + * camera. Neither of those is what is on screen here, so the order it asks for is an order for + * somewhere else, and it hands over solid and see through parts of one zone before it reaches the next. + * + *

That order is not a detail. See through surfaces are drawn without writing depth, so nothing + * sorts them afterwards: whatever is drawn last is on top. 117 HD says as much where it draws them, + * that it relies on the zones arriving back to front. Water is drawn at the start of a zone's see + * through pass, so with the whole scene's solid parts laid down first it ends up between the two, which + * is where it belongs. Out of order, a river is painted over the bank in front of it. + */ + private void drawZones() { + var scene = loaded; + if (scene == null || !(plugin.renderer instanceof ZoneRenderer)) + return; + var renderer = (ZoneRenderer) plugin.renderer; + Projection projection = renderer.sceneCamera; + + int level = Math.max(0, Math.min(MAX_Z - 1, plane)); + int minLevel = planesBelow ? 0 : level; + + // Solid first, and in any order: it writes depth, so it sorts itself + for (int zx = 0; zx < NUM_ZONES; zx++) + for (int zz = 0; zz < NUM_ZONES; zz++) + renderer.drawZoneOpaque(projection, scene, zx, zz); + + int[] order = zonesFurthestFirst(scene); + for (int at = minLevel; at <= MAX_Z - 1; at++) + for (int zone : order) + renderer.drawZoneAlpha(projection, scene, at, zone >> 8, zone & 0xFF); + } + + /** The zones, furthest from the camera first, which is the order see through parts have to be drawn in */ + private int[] zonesFurthestFirst(BuiltScene scene) { + int count = NUM_ZONES * NUM_ZONES; + if (zoneOrder == null || zoneOrder.length != count) { + zoneOrder = new int[count]; + zoneDistance = new long[count]; + } + + int offset = scene.getSceneOffset(); + float cameraX = plugin.cameraPosition[0]; + float cameraZ = plugin.cameraPosition[2]; + + for (int zx = 0, at = 0; zx < NUM_ZONES; zx++) { + for (int zz = 0; zz < NUM_ZONES; zz++, at++) { + // The middle of the zone, in the units the scene is measured in + float x = (zx * 8 - offset) * 128 + 512; + float z = (zz * 8 - offset) * 128 + 512; + float dx = x - cameraX; + float dz = z - cameraZ; + zoneOrder[at] = zx << 8 | zz; + zoneDistance[at] = (long) (dx * dx + dz * dz); + } + } + + // A plain insertion sort, since the order barely changes between one frame and the next + for (int i = 1; i < count; i++) { + int zone = zoneOrder[i]; + long distance = zoneDistance[i]; + int j = i - 1; + while (j >= 0 && zoneDistance[j] < distance) { + zoneOrder[j + 1] = zoneOrder[j]; + zoneDistance[j + 1] = zoneDistance[j]; + j--; + } + zoneOrder[j + 1] = zone; + zoneDistance[j + 1] = distance; + } + return zoneOrder; + } + + private int[] zoneOrder; + private long[] zoneDistance; + + private volatile int dynamicsDrawnOnFrame = -1; + private long lastDynamicReport; + private volatile int acceptedLastFrame; + + private void reportDynamics(BuiltScene scene, int cycle, int drawn) { + long now = System.currentTimeMillis(); + if (now - lastDynamicReport < 1000) + return; + lastDynamicReport = now; + + var first = scene.getDynamics().get(0); + int posed = 0; + for (var dynamic : scene.getDynamics()) { + if (dynamic.renderable.posesDiffer()) { + if (posed == 0) + first = dynamic; + posed++; + } + } + int accepted = acceptedLastFrame; + + var current = panel; + if (current != null) { + current.setSummary(String.format( + "%s \u2014 animating %d (%d move), drawn %d, frame %d", + describe(scene), drawn, posed, accepted, first.renderable.getAnimFrame() + )); + } + + log.debug( + "Animating: handed over {} of {} ({} actually move), 117 HD drew {}, cycle {}, " + + "sampling {} on frame {} at {}, {}, {}", + drawn, scene.getDynamics().size(), posed, accepted, cycle, + first.renderable, first.renderable.getAnimFrame(), + first.x, first.y, first.z + ); + } + + private void nameFromGamevals(List found) { + if (found.isEmpty()) + return; + + try (var gamevals = gamevalManager.obtainHandle()) { + var byId = new HashMap(); + for (var gameval : gamevals.getObjects().entrySet()) + byId.putIfAbsent(gameval.getValue(), gameval.getKey()); + + for (VariantObject object : found) { + object.gameval = byId.get(object.baseId); + + var names = new String[object.variantIds.length]; + for (int i = 0; i < names.length; i++) + if (object.variantIds[i] != -1) + names[i] = byId.get(object.variantIds[i]); + object.variantGamevals = names; + } + } catch (Exception ex) { + log.warn("Could not name the variable objects", ex); + } + } + + private static Set roofIdsOf(BuiltScene scene) { + var ids = new HashSet(); + for (int[][] plane : scene.getRoofs()) + for (int[] column : plane) + for (int roofId : column) + if (roofId > 0) + ids.add(roofId); + return ids; + } + + public void setKeepLoaded(boolean keepLoaded) { + this.keepLoaded = keepLoaded; + } + + @Nullable + public String goToPlacement(VariantObject object, int which) { + var placements = object.placements; + if (placements.isEmpty()) + return null; + + int index = Math.floorMod(which, placements.size()); + var placed = placements.get(index); + String label = (index + 1) + " of " + placements.size(); + + clientThread.invoke(() -> { + camera.goTo(placed.x, placed.y, placed.z); + highlight.mark(placed, label); + }); + return label; + } + + public void setFreeCamera(boolean free) { + wantFreeCamera = free; + camera.setEnabled(free); + clientThread.invoke(this::updateHooks); + } + + public void setCameraSpeed(float speed) { + camera.setSpeed(speed); + } + + @Override + public boolean addEntity(Renderable renderable, boolean drawingUi) { + return loaded == null || !(renderable instanceof Actor); + } + + public VariantOptions getVariants() { + return variants; + } + + public boolean hasScene() { + return loaded != null; + } + + /** The scene on screen, or null while the game's own is being drawn */ + @Nullable + public BuiltScene getLoaded() { + return loaded; + } + + public void reload() { + var stitched = lastStitched; + if (stitched != null) { + loadStitched(stitched); + return; + } + load(lastWorldX, lastWorldY, lastChunks); + } + + public void loadStitched(int[] regionIds) { + if (regionIds.length == 0) + return; + if (regionIds.length == 1) { + lastStitched = null; + load(worldXOfRegion(regionIds[0]), worldYOfRegion(regionIds[0]), lastChunks); + return; + } + + var executor = worker; + if (executor == null) + return; + + lastStitched = regionIds.clone(); + var wanted = lastStitched; + + executor.submit(() -> { + try { + loading = true; + long start = System.nanoTime(); + + var scene = openCache().buildStitched(wanted, 0, variants); + long ms = (System.nanoTime() - start) / 1_000_000; + + int[] placed = scene.getMapRegions(); + var names = new StringBuilder(); + for (int i = 0; i < placed.length; i++) + names.append(i == 0 ? "" : ", ").append(placed[i]); + + String status = "Stitched " + names + " in " + ms + "ms"; + if (placed.length < wanted.length) + status += " — " + (wanted.length - placed.length) + " would not fit"; + finish(scene, status); + } catch (Throwable ex) { + log.error("Failed to stitch regions", ex); + setStatus("Could not stitch: " + ex.getMessage(), Color.RED.darker()); + } finally { + loading = false; + } + }); + } + + private static int worldXOfRegion(int region) { + return ((region >> 8) << 6) + 32; + } + + private static int worldYOfRegion(int region) { + return ((region & 0xFF) << 6) + 32; + } + + private void finish(BuiltScene scene, String status) { + loaded = scene; + runeliteDevTools.standIn(); + allRoofIds = roofIdsOf(scene); + var found = variants.getFound(); + nameFromGamevals(found); + var current = panel; + if (current != null) + current.setVariantObjects(found); + + apply(scene, () -> { + setStatus(status, Color.GREEN.darker()); + setSummary(describe(scene) + ", " + found.size() + " variable, " + + scene.getDynamics().size() + " animating"); + if (wantFreeCamera) + camera.setEnabled(true); + }); + } + + public void load(int worldX, int worldY, int expandedChunks) { + var executor = worker; + if (executor == null) + return; + + lastStitched = null; + lastWorldX = worldX; + lastWorldY = worldY; + lastChunks = expandedChunks; + + executor.submit(() -> { + try { + loading = true; + long start = System.nanoTime(); + + var sceneBuilder = openCache(); + var scene = sceneBuilder.build(worldX, worldY, expandedChunks, 0, variants); + long ms = (System.nanoTime() - start) / 1_000_000; + + loaded = scene; + runeliteDevTools.standIn(); + allRoofIds = roofIdsOf(scene); + var found = variants.getFound(); + nameFromGamevals(found); + var current = panel; + if (current != null) + current.setVariantObjects(found); + + apply(scene, () -> { + setStatus("Loaded " + worldX + ", " + worldY + " in " + ms + "ms", Color.GREEN.darker()); + setSummary(describe(scene) + ", " + found.size() + " variable, " + + scene.getDynamics().size() + " animating"); + if (wantFreeCamera) + camera.setEnabled(true); + }); + } catch (Throwable ex) { + log.error("Failed to build a scene from the cache", ex); + setStatus(String.valueOf(ex.getMessage()), Color.RED.brighter()); + } finally { + loading = false; + } + }); + } + + public void restoreGameScene() { + if (loaded == null) + return; + loaded = null; + releaseDetailDistance(); + runeliteDevTools.standDown(); + camera.setEnabled(false); + clientThread.invoke(() -> { + var worldView = client.getTopLevelWorldView(); + if (worldView == null || client.getGameState() != GameState.LOGGED_IN) + return; + handOver(worldView, worldView.getScene()); + updateHooks(); + }); + setStatus("Back to the game's scene", Color.LIGHT_GRAY); + setSummary(" "); + } + + public void previewObject(int objectId, Consumer onReady) { + var pool = worker; + if (pool == null) + return; + if (objectId < 0) { + SwingUtilities.invokeLater(() -> onReady.accept(null)); + return; + } + + pool.submit(() -> { + ModelPreview.Shape shape = null; + try { + shape = openCache().preview(objectId, -1); + } catch (Exception ex) { + log.warn("Could not build a preview of object {}", objectId, ex); + } + + var built = shape; + SwingUtilities.invokeLater(() -> onReady.accept(built)); + }); + } + + private SceneBuilder openCache() throws Exception { + var existing = builder; + if (existing != null) + return existing; + + synchronized (this) { + if (builder == null) { + var opened = new Definitions(Definitions.findDefaultCache()); + defs = opened; + builder = new SceneBuilder(opened); + } + return builder; + } + } + + private void apply(BuiltScene scene, Runnable onApplied) { + clientThread.invoke(() -> { + if (client.getGameState() != GameState.LOGGED_IN) + return false; + + var worldView = client.getTopLevelWorldView(); + if (worldView == null) + return false; + + handOver(worldView, scene); + updateHooks(); + onApplied.run(); + return true; + }); + } + + private void handOver(WorldView worldView, Scene scene) { + assert client.isClientThread(); + plugin.renderer.loadScene(worldView, scene); + plugin.renderer.swapScene(scene); + + for (int x = 0; x < NUM_ZONES; x++) + for (int z = 0; z < NUM_ZONES; z++) + plugin.renderer.invalidateZone(scene, x, z); + } + + private static final Set PER_FRAME_DRAWS = Set.of("draw", "drawDynamic", "drawTemp"); + + /** + * The two calls that say which part of the scene to draw next, and in what order. + * + *

The game makes these as it walks its own scene outwards from its own camera, and neither is this + * one. They are dropped and reissued in {@link #drawZones} instead. + */ + private static final Set ZONE_DRAWS = Set.of("drawZoneOpaque", "drawZoneAlpha"); + + private void updateHooks() { + assert client.isClientThread(); + if (loaded != null || camera.isEnabled()) { + wrap(); + } else { + unwrap(); + } + } + + private void wrap() { + DrawCallbacks current = client.getDrawCallbacks(); + if (current == wrapper) + return; + if (current == null) { + log.warn("Nothing is drawing the scene, so there is nothing to step in front of"); + return; + } + + wrapped = current; + wrapper = (DrawCallbacks) Proxy.newProxyInstance( + DrawCallbacks.class.getClassLoader(), + new Class[] { DrawCallbacks.class }, + new Hooks(current) + ); + client.setDrawCallbacks(wrapper); + log.debug("Stepped in front of {}", current.getClass().getSimpleName()); + } + + private void unwrap() { + if (wrapper != null && client.getDrawCallbacks() == wrapper) + client.setDrawCallbacks(wrapped); + wrapper = null; + wrapped = null; + } + + private class Hooks implements InvocationHandler { + private final DrawCallbacks target; + + Hooks(DrawCallbacks target) { + this.target = target; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String name = method.getName(); + + boolean preSceneDraw = "preSceneDraw".equals(name); + int cameraValuesAt = -1; + + if (preSceneDraw) { + acceptedLastFrame = plugin.drawnDynamicRenderableCount; + cameraValuesAt = FreeCamera.cameraValuesAt(args); + if (cameraValuesAt >= 0) { + camera.interceptPreSceneDraw(args); + if (loaded != null) + overrideLevels(args, cameraValuesAt); + } + if (loaded != null) + holdDetailDistanceOpen(); + } else if ("drawScene".equals(name)) { + camera.interceptDrawScene(args); + } else if (loaded != null && ZONE_DRAWS.contains(name)) { + return null; + } else if (skipsDraw(name, args, loaded)) { + return null; + } + + Object result; + try { + result = method.invoke(target, args); + } catch (InvocationTargetException ex) { + throw ex.getCause(); + } + + if (preSceneDraw && cameraValuesAt >= 0 && plugin.frame != dynamicsDrawnOnFrame) { + dynamicsDrawnOnFrame = plugin.frame; + // Animating things first: they hand their see through parts to the zone they stand in, and + // a zone sorts what it has been given when it is asked to draw it + drawDynamics(); + drawZones(); + } + return result; + } + } + + static boolean skipsDraw(String method, @Nullable Object[] args, @Nullable BuiltScene loaded) { + if (loaded == null || args == null || !PER_FRAME_DRAWS.contains(method)) + return false; + + for (Object arg : args) + if (arg instanceof Scene) + return arg != loaded; + return false; + } + + @Subscribe + public void onGameTick(GameTick event) { + var scene = loaded; + if (!keepLoaded || scene == null || loading) + return; + + var context = plugin.renderer.getSceneContext(); + if (context == null || context.scene == scene) + return; + + log.debug("The game replaced the cache scene, putting it back"); + apply(scene, () -> {}); + } + + private static String describe(BuiltScene scene) { + int floors = 0; + int objects = 0; + var tiles = scene.getExtendedTiles(); + for (int plane = 0; plane < tiles.length; plane++) { + for (int x = 0; x < tiles[plane].length; x++) { + for (int y = 0; y < tiles[plane][x].length; y++) { + var tile = tiles[plane][x][y]; + if (tile == null) + continue; + if (tile.getSceneTilePaint() != null || tile.getSceneTileModel() != null) + floors++; + for (var object : tile.getGameObjects()) + if (object != null) + objects++; + if (tile.getWallObject() != null) + objects++; + if (tile.getDecorativeObject() != null) + objects++; + if (tile.getGroundObject() != null) + objects++; + } + } + } + return floors + " floors, " + objects + " objects"; + } + + private void setStatus(String text, Color color) { + var current = panel; + if (current != null) + current.setStatus(text, color); + } + + private void setSummary(String text) { + var current = panel; + if (current != null) + current.setSummary(text); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoaderPanel.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoaderPanel.java new file mode 100644 index 0000000..7b5cb11 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/SceneLoaderPanel.java @@ -0,0 +1,862 @@ +package rs117.hd.dev.sceneloader; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Insets; +import java.awt.RenderingHints; +import java.awt.image.BufferedImage; +import java.util.ArrayList; +import java.util.List; +import javax.annotation.Nullable; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.DefaultListCellRenderer; +import javax.swing.DefaultListModel; +import javax.swing.ImageIcon; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSpinner; +import javax.swing.JTextField; +import javax.swing.ListSelectionModel; +import javax.swing.SpinnerNumberModel; +import javax.swing.SwingUtilities; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import net.runelite.client.ui.ColorScheme; +import net.runelite.client.ui.FontManager; +import net.runelite.client.ui.PluginPanel; +import rs117.hd.dev.sceneloader.map.MapHost; +import rs117.hd.dev.sceneloader.scene.SceneBuilder; +import rs117.hd.dev.sceneloader.scene.VariantObject; +import rs117.hd.dev.sceneloader.scene.VariantOptions; + +import static net.runelite.api.Constants.REGION_SIZE; + +public class SceneLoaderPanel extends PluginPanel { + /** Somewhere recognisable for the map to open looking at, which is not the same as picking it */ + private static final int LUMBRIDGE = 50 << 8 | 50; + + private static final int ROW_HEIGHT = 24; + private static final int SPINNER_WIDTH = 66; + private static final int WIDE_SPINNER_WIDTH = 100; + private static final int ICON_BUTTON_WIDTH = 26; + private static final int LIST_HEIGHT = 150; + private static final int PREVIEW_SIZE = 86; + private static final int FIRST_FORM_ITEM = 2; + + private final SceneLoader tools; + + private final JTextField regionIds = new JTextField(); + private final JLabel regionNote = note(Color.GRAY); + private final JSpinner expandedChunks = spinner(5, 0, 5); + private final JSpinner plane = spinner(0, 0, 3); + private final JCheckBox planesBelow = new JCheckBox("Draw planes below", true); + private final JCheckBox showRoofs = new JCheckBox("Draw roofs", false); + private final JCheckBox keepLoaded = new JCheckBox("Keep loaded", true); + private final JCheckBox freeCamera = new JCheckBox("Free camera", true); + private final JSpinner cameraSpeed = spinner(1, 1, 20); + + private final JLabel status = note(Color.LIGHT_GRAY); + private final JLabel summary = note(Color.GRAY); + + private final DefaultListModel variantModel = new DefaultListModel<>(); + private final JList variantList = new JList<>(variantModel); + private final JComboBox formChoice = new JComboBox<>(); + private final JLabel variantHeading = heading("Variable objects"); + private final JLabel formLabel = heading("Form"); + private final ModelPreview nowPreview = new ModelPreview(PREVIEW_SIZE); + private final ModelPreview nextPreview = new ModelPreview(PREVIEW_SIZE); + private JPanel previewRow; + private int[] formOptions = new int[0]; + private JButton goTo; + private int goToIndex; + private JButton applyForm; + private JButton resetForm; + private JScrollPane variantScroll; + + @Nullable + private MapHost mapHost; + + private int filling; + + public SceneLoaderPanel(SceneLoader tools) { + super(true); + this.tools = tools; + + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); + setBackground(ColorScheme.DARK_GRAY_COLOR); + + regionIds.setToolTipText( + "One region id, or several separated by commas to lay them out side by side. " + + "Up to " + SceneBuilder.MAX_STITCHED_REGIONS + " fit, " + + SceneBuilder.REGIONS_PER_SIDE + " to a side, and extra chunks are ignored for those."); + regionIds.setFont(FontManager.getRunescapeSmallFont()); + add(labelled("Region ID", narrow(regionIds, WIDE_SPINNER_WIDTH), mapButton())); + add(regionNote); + add(Box.createVerticalStrut(6)); + + expandedChunks.setToolTipText("How far past the usual scene to build, in chunks of eight tiles"); + expandedChunks.addChangeListener(e -> { + if (mapHost != null) + mapHost.refresh(); + }); + add(labelled("Extra chunks", expandedChunks, SPINNER_WIDTH)); + add(Box.createVerticalStrut(8)); + + plane.setToolTipText("Which plane to look at, in place of the one the player is standing on"); + plane.addChangeListener(e -> { + tools.setPlane((Integer) plane.getValue()); + if (filling == 0) + reloadForPlane(); + }); + add(labelled("Plane", plane, SPINNER_WIDTH)); + add(Box.createVerticalStrut(4)); + + checkBox(planesBelow, "Keep the planes under the one being looked at, rather than only that one"); + planesBelow.addActionListener(e -> tools.setPlanesBelow(planesBelow.isSelected())); + add(planesBelow); + add(Box.createVerticalStrut(4)); + + checkBox(showRoofs, "Leave the roofs on. Turning them off opens up everything above the plane below."); + showRoofs.addActionListener(e -> tools.setShowRoofs(showRoofs.isSelected())); + add(showRoofs); + add(Box.createVerticalStrut(8)); + + checkBox(keepLoaded, "Put the scene back whenever the game replaces it, such as when you move"); + keepLoaded.addActionListener(e -> tools.setKeepLoaded(keepLoaded.isSelected())); + add(keepLoaded); + add(Box.createVerticalStrut(4)); + + checkBox(freeCamera, + "Flies the view instead of following the player, and comes on whenever a scene is loaded. " + + "Moves the way the game's own detached camera does: WASD travels level, space or R to rise, " + + "shift or Q or F to drop, control to go slowly, and the arrow keys or a drag with the mouse " + + "wheel held to look around."); + freeCamera.addActionListener(e -> { + tools.setFreeCamera(freeCamera.isSelected()); + cameraSpeed.setEnabled(freeCamera.isSelected()); + }); + cameraSpeed.setToolTipText("How fast flying moves. One is exactly the speed of the game's own camera."); + cameraSpeed.addChangeListener(e -> tools.setCameraSpeed((Integer) cameraSpeed.getValue())); + add(alongside(freeCamera, cameraSpeed)); + + add(Box.createVerticalStrut(10)); + add(status); + add(summary); + + add(Box.createVerticalStrut(10)); + add(variantHeading); + add(Box.createVerticalStrut(2)); + buildVariantSection(); + + add(Box.createVerticalStrut(10)); + add(button("Load from cache", "Build the scene at these coordinates and hand it to 117 HD", this::load)); + add(Box.createVerticalStrut(4)); + add(button("Back to the game", "Drop the cache scene and let the game's own scene render again", + tools::restoreGameScene)); + + regionIds.getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + regionsChanged(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + regionsChanged(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + regionsChanged(); + } + }); + updateRegionNote(); + + setVariantObjects(List.of()); + } + + private void buildVariantSection() { + variantList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + variantList.setBackground(ColorScheme.DARKER_GRAY_COLOR); + variantList.setForeground(Color.LIGHT_GRAY); + variantList.setFont(FontManager.getRunescapeSmallFont()); + variantList.setCellRenderer(new VariantRenderer()); + variantList.addListSelectionListener(e -> { + if (!e.getValueIsAdjusting()) + showFormsFor(variantList.getSelectedValue()); + }); + + variantScroll = new JScrollPane(variantList); + variantScroll.setAlignmentX(Component.LEFT_ALIGNMENT); + variantScroll.setPreferredSize(new Dimension(contentWidth(), LIST_HEIGHT)); + variantScroll.setMaximumSize(new Dimension(Integer.MAX_VALUE, LIST_HEIGHT)); + variantScroll.setBorder(BorderFactory.createLineBorder(ColorScheme.DARKER_GRAY_COLOR)); + add(variantScroll); + + add(Box.createVerticalStrut(6)); + add(formLabel); + add(dropdown(formChoice, "Which form this object takes, since the cache alone does not decide it", + this::chooseForm)); + + add(Box.createVerticalStrut(4)); + previewRow = sideBySide(nowPreview, nextPreview); + add(previewRow); + + add(Box.createVerticalStrut(4)); + goTo = button("Go to", "Fly to this object in the scene and ring it", this::goToNext); + add(goTo); + + add(Box.createVerticalStrut(4)); + applyForm = button("Apply transform", "Rebuild the scene with the chosen form in place", this::applyForm); + add(applyForm); + add(Box.createVerticalStrut(2)); + resetForm = button("Reset to default", "Put this object back to the form the game would pick", + this::resetForm); + add(resetForm); + + } + + private void reloadForPlane() { + if (!tools.hasScene()) + return; + setStatus("Rebuilding on plane " + plane.getValue() + "...", Color.LIGHT_GRAY); + tools.reload(); + } + + private void load() { + int[] wanted = wantedRegions(); + if (wanted.length == 0) { + setStatus("No region id to load", Color.GRAY); + return; + } + + getOutOfTheWay(); + + if (wanted.length > 1) { + int fit = SceneBuilder.regionsThatFit(wanted).length; + setStatus("Stitching " + fit + " regions...", Color.LIGHT_GRAY); + tools.loadStitched(wanted); + return; + } + + int region = wanted[0]; + setStatus("Loading region " + region + "...", Color.LIGHT_GRAY); + tools.load(worldXOf(region), worldYOf(region), (Integer) expandedChunks.getValue()); + } + + /** + * Puts the game view back before loading, where the map is sitting over it. + * + *

A map in a window of its own is left alone: there is nothing in the way, and closing it would + * mean opening it again for the next pick. + */ + private void getOutOfTheWay() { + if (mapHost != null && mapHost.isOpen() && !mapHost.isPoppedOut()) + mapHost.close(); + } + + private int[] wantedRegions() { + var found = new ArrayList(); + for (String part : regionIds.getText().split("[, ]+")) { + if (part.isEmpty()) + continue; + try { + int region = Integer.parseInt(part.trim()); + if (region >= 0 && region <= 0xFFFF) + found.add(region); + } catch (NumberFormatException ignored) { + } + } + + var regions = new int[found.size()]; + for (int i = 0; i < regions.length; i++) + regions[i] = found.get(i); + return regions; + } + + private void regionsChanged() { + updateRegionNote(); + int[] wanted = wantedRegions(); + expandedChunks.setEnabled(wanted.length <= 1); + if (mapHost != null) { + mapHost.setListed(wanted); + mapHost.refresh(); + } + } + + /** Ctrl clicking a region picks it, and ctrl clicking a picked one takes it back out */ + private void toggleRegion(int region) { + int[] wanted = wantedRegions(); + + var kept = new ArrayList(); + boolean removed = false; + for (int already : wanted) { + if (already == region) { + removed = true; + continue; + } + kept.add(already); + } + + if (removed) { + setRegions(kept); + setStatus("Took region " + region + " back out, " + kept.size() + " picked", Color.LIGHT_GRAY); + return; + } + + if (wanted.length >= SceneBuilder.MAX_STITCHED_REGIONS) { + setStatus( + SceneBuilder.MAX_STITCHED_REGIONS + " regions at a time is the most this picks up", + Color.GRAY + ); + return; + } + + kept.add(region); + setRegions(kept); + setStatus("Picked region " + region + ", " + kept.size() + " picked", Color.LIGHT_GRAY); + } + + /** Drops back to a single region, which is the mode everything else in the panel is written for */ + private void clearPickedRegions() { + int[] wanted = wantedRegions(); + regionIds.setText(wanted.length == 0 ? "" : String.valueOf(wanted[0])); + setStatus("Back to one region at a time", Color.LIGHT_GRAY); + } + + private void setRegions(java.util.List regions) { + var text = new StringBuilder(); + for (int region : regions) + text.append(text.length() == 0 ? "" : ", ").append(region); + regionIds.setText(text.toString()); + } + + private void updateRegionNote() { + int[] wanted = wantedRegions(); + if (wanted.length == 0) { + regionNote.setText("No region"); + regionNote.setToolTipText(null); + return; + } + + if (wanted.length > 1) { + int fit = SceneBuilder.regionsThatFit(wanted).length; + String text = fit + " regions laid out"; + if (wanted.length > fit) + text += ", " + (wanted.length - fit) + " will not fit"; + regionNote.setText(text); + regionNote.setForeground(wanted.length > fit ? Color.ORANGE.darker() : Color.GRAY); + regionNote.setToolTipText( + "Regions that adjoin in the world are laid against each other, and anything unrelated is " + + "set apart. Whether they all fit depends on their shape, not just how many there are: the " + + "scene is " + SceneBuilder.EXTENDED + " tiles across, so a pair side by side next to " + + "a pair stacked up needs more room than there is."); + return; + } + + int region = wanted[0]; + String text = (region >> 8) + ", " + (region & 0xFF) + + " at " + worldXOf(region) + ", " + worldYOf(region); + regionNote.setText(text); + regionNote.setForeground(Color.GRAY); + regionNote.setToolTipText("Region " + (region >> 8) + ", " + (region & 0xFF) + + ", centred on world tile " + worldXOf(region) + ", " + worldYOf(region)); + } + + private static int worldXOf(int region) { + return ((region >> 8) << 6) + REGION_SIZE / 2; + } + + private static int worldYOf(int region) { + return ((region & 0xFF) << 6) + REGION_SIZE / 2; + } + + public void setVariantObjects(List objects) { + SwingUtilities.invokeLater(() -> { + filling++; + try { + VariantObject previous = variantList.getSelectedValue(); + + variantModel.clear(); + for (VariantObject object : objects) + variantModel.addElement(object); + + boolean any = !objects.isEmpty(); + variantHeading.setVisible(any); + variantScroll.setVisible(any); + formLabel.setVisible(any); + formChoice.setVisible(any); + + if (previous != null) { + for (VariantObject object : objects) { + if (object.baseId == previous.baseId) { + variantList.setSelectedValue(object, true); + break; + } + } + } + } finally { + filling--; + } + showFormsFor(variantList.getSelectedValue()); + }); + } + + private void showFormsFor(@Nullable VariantObject object) { + filling++; + try { + formChoice.removeAllItems(); + goToIndex = 0; + + if (object == null) { + formOptions = new int[0]; + formChoice.setEnabled(false); + retitle(formLabel, "Form"); + return; + } + + formChoice.setEnabled(true); + int fallback = object.firstVisibleVariant(); + formChoice.addItem(fallback < 0 ? "Default" : "Default (" + fallback + ")"); + formChoice.addItem("Hidden"); + + var offered = new ArrayList(); + for (int i = 0; i < object.variantIds.length; i++) { + if (object.variantIds[i] == -1) + continue; + formChoice.addItem(i + ": " + object.variantLabel(i)); + offered.add(i); + } + formOptions = new int[offered.size()]; + for (int i = 0; i < formOptions.length; i++) + formOptions[i] = offered.get(i); + + retitle(formLabel, formOptions.length == object.variantIds.length + ? "Form" + : "Form — " + formOptions.length + " of " + object.variantIds.length); + + int choice = tools.getVariants().choiceFor(object.baseId); + if (choice == VariantOptions.HIDDEN) { + formChoice.setSelectedIndex(1); + } else { + int item = itemForForm(choice); + formChoice.setSelectedIndex(item < 0 ? 0 : item); + } + } finally { + filling--; + updatePreviews(); + } + } + + private void chooseForm() { + if (filling > 0) + return; + updatePreviews(); + } + + private int pendingChoice() { + int selected = formChoice.getSelectedIndex(); + if (selected <= 0) + return VariantOptions.DEFAULT; + if (selected == 1) + return VariantOptions.HIDDEN; + + int form = selected - FIRST_FORM_ITEM; + return form < formOptions.length ? formOptions[form] : VariantOptions.DEFAULT; + } + + private int itemForForm(int form) { + for (int i = 0; i < formOptions.length; i++) + if (formOptions[i] == form) + return FIRST_FORM_ITEM + i; + return -1; + } + + private static int objectFor(VariantObject object, int choice) { + if (choice == VariantOptions.HIDDEN) + return -1; + + int index = choice == VariantOptions.DEFAULT ? object.firstVisibleVariant() : choice; + if (index < 0 || index >= object.variantIds.length) + index = object.firstVisibleVariant(); + if (index < 0) + return -1; + return object.variantIds[index]; + } + + private void updatePreviews() { + if (previewRow == null) + return; + + VariantObject object = variantList.getSelectedValue(); + boolean any = object != null; + previewRow.setVisible(any); + goTo.setVisible(any); + applyForm.setVisible(any); + resetForm.setVisible(any); + if (!any) { + nowPreview.show(null, "", ""); + nextPreview.show(null, "", ""); + return; + } + + int applied = tools.getVariants().choiceFor(object.baseId); + int pending = pendingChoice(); + int appliedId = object.appliedId; + int pendingId = objectFor(object, pending); + + boolean changes = pending != applied && pendingId != appliedId; + applyForm.setEnabled(changes); + applyForm.setText(changes ? "Apply transform" : "Already this form"); + applyForm.setToolTipText( + changes + ? "Rebuild the scene with the chosen form in place" + : "The scene already has this object as " + (appliedId < 0 ? "nothing" : appliedId) + + ", so there is nothing to apply. Pick a different form." + ); + resetForm.setEnabled(applied != VariantOptions.DEFAULT); + + int copies = object.placements.size(); + goTo.setEnabled(copies > 0); + goTo.setText(copies > 1 ? "Go to next of " + copies : "Go to"); + goTo.setToolTipText( + copies == 0 + ? "This object is not standing anywhere in the scene, so there is nowhere to go" + : copies == 1 + ? "Fly to this object and ring it" + : "Fly to the next of the " + copies + " in the scene, coming back round to the first" + ); + + loadPreview(nowPreview, appliedId, "Now", null); + loadPreview(nextPreview, pendingId, "After", nowPreview); + } + + private void goToNext() { + VariantObject object = variantList.getSelectedValue(); + if (object == null) + return; + + String where = tools.goToPlacement(object, goToIndex); + if (where == null) { + setStatus("Nowhere to go: " + object.label() + " is not in the scene", Color.GRAY); + return; + } + goToIndex++; + if (!freeCamera.isSelected()) { + freeCamera.setSelected(true); + cameraSpeed.setEnabled(true); + } + setStatus("Looking at " + object.label() + ", " + where, Color.LIGHT_GRAY); + } + + private void loadPreview(ModelPreview preview, int objectId, String caption, @Nullable ModelPreview matchAngle) { + String label = objectId < 0 ? caption + ": nothing" : caption + ": " + objectId; + preview.show(null, label, "..."); + tools.previewObject(objectId, shape -> { + if (!label.equals(preview.getCaption())) + return; + preview.show(shape, label, objectId < 0 ? "Nothing" : "No model"); + if (matchAngle != null) + preview.matchAngleOf(matchAngle); + }); + } + + private void applyForm() { + VariantObject object = variantList.getSelectedValue(); + if (object == null) + return; + + int choice = pendingChoice(); + int applied = objectFor(object, choice); + tools.getVariants().setChoice(object.baseId, choice); + updatePreviews(); + setStatus( + "Rebuilding with " + object.label() + " as " + (applied < 0 ? "nothing" : applied) + "...", + Color.LIGHT_GRAY + ); + tools.reload(); + } + + private void resetForm() { + VariantObject object = variantList.getSelectedValue(); + if (object == null) + return; + + tools.getVariants().setChoice(object.baseId, VariantOptions.DEFAULT); + filling++; + try { + formChoice.setSelectedIndex(0); + } finally { + filling--; + } + updatePreviews(); + setStatus("Rebuilding with " + object.label() + " at its default...", Color.LIGHT_GRAY); + tools.reload(); + } + + public void setStatus(String text, Color color) { + SwingUtilities.invokeLater(() -> { + status.setText(text); + status.setToolTipText(text); + status.setForeground(color); + }); + } + + public void setSummary(String text) { + SwingUtilities.invokeLater(() -> { + summary.setText(text); + summary.setToolTipText(text); + }); + } + + + private static int contentWidth() { + return PANEL_WIDTH - 2 * BORDER_OFFSET; + } + + private static void retitle(JLabel label, String text) { + label.setMaximumSize(null); + label.setText(text); + label.setMaximumSize(label.getPreferredSize()); + } + + private static JLabel heading(String text) { + JLabel label = new JLabel(text); + label.setFont(FontManager.getRunescapeSmallFont()); + label.setForeground(Color.LIGHT_GRAY); + label.setAlignmentX(Component.LEFT_ALIGNMENT); + label.setMaximumSize(label.getPreferredSize()); + return label; + } + + private static JLabel note(Color color) { + JLabel label = new JLabel(" "); + label.setFont(FontManager.getRunescapeSmallFont()); + label.setForeground(color); + label.setAlignmentX(Component.LEFT_ALIGNMENT); + label.setMaximumSize(new Dimension(Integer.MAX_VALUE, 16)); + return label; + } + + private static JPanel labelled(String text, JComponent field, @Nullable Component after) { + JPanel panel = row(); + panel.add(heading(text)); + panel.add(Box.createHorizontalGlue()); + panel.add(field); + if (after != null) { + panel.add(Box.createHorizontalStrut(4)); + panel.add(after); + } + return panel; + } + + private static JTextField narrow(JTextField field, int width) { + field.setMaximumSize(new Dimension(width, ROW_HEIGHT)); + field.setPreferredSize(new Dimension(width, ROW_HEIGHT)); + return field; + } + + private static JPanel labelled(String text, JSpinner spinner, int width) { + return labelled(text, spinner, width, null); + } + + private static JPanel labelled(String text, JSpinner spinner, int width, @Nullable Component after) { + JPanel panel = row(); + panel.add(heading(text)); + panel.add(Box.createHorizontalGlue()); + panel.add(narrow(spinner, width)); + if (after != null) { + panel.add(Box.createHorizontalStrut(4)); + panel.add(after); + } + return panel; + } + + private JButton mapButton() { + JButton button = new JButton(new ImageIcon(createMapIcon())); + button.setToolTipText("Pick a region off the world map, or close it if it is already open"); + button.setMargin(new Insets(0, 0, 0, 0)); + var size = new Dimension(ICON_BUTTON_WIDTH, ROW_HEIGHT); + button.setPreferredSize(size); + button.setMaximumSize(size); + button.addActionListener(e -> toggleMap()); + return button; + } + + private static JPanel alongside(JCheckBox box, JSpinner spinner) { + JPanel panel = row(); + box.setMaximumSize(box.getPreferredSize()); + panel.add(box); + panel.add(Box.createHorizontalGlue()); + panel.add(narrow(spinner, SPINNER_WIDTH)); + return panel; + } + + private static JSpinner narrow(JSpinner spinner, int width) { + spinner.setMaximumSize(new Dimension(width, ROW_HEIGHT)); + spinner.setPreferredSize(new Dimension(width, ROW_HEIGHT)); + return spinner; + } + + private static void checkBox(JCheckBox box, String tooltip) { + box.setBackground(ColorScheme.DARK_GRAY_COLOR); + box.setForeground(Color.LIGHT_GRAY); + box.setAlignmentX(Component.LEFT_ALIGNMENT); + box.setMaximumSize(new Dimension(Integer.MAX_VALUE, ROW_HEIGHT)); + box.setToolTipText(tooltip); + } + + private static JPanel sideBySide(ModelPreview left, ModelPreview right) { + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); + panel.setBackground(ColorScheme.DARK_GRAY_COLOR); + panel.setAlignmentX(Component.LEFT_ALIGNMENT); + panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, left.getPreferredSize().height)); + panel.add(left); + panel.add(Box.createHorizontalStrut(4)); + panel.add(right); + panel.add(Box.createHorizontalGlue()); + return panel; + } + + private static JPanel row() { + JPanel panel = new JPanel(); + panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); + panel.setBackground(ColorScheme.DARK_GRAY_COLOR); + panel.setAlignmentX(Component.LEFT_ALIGNMENT); + panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, ROW_HEIGHT)); + return panel; + } + + private static JButton button(String text, String tooltip, Runnable action) { + JButton button = new JButton(text); + button.setToolTipText(tooltip); + button.setAlignmentX(Component.LEFT_ALIGNMENT); + button.setMaximumSize(new Dimension(Integer.MAX_VALUE, 26)); + button.addActionListener(e -> action.run()); + return button; + } + + private static JComboBox dropdown(JComboBox combo, String tooltip, Runnable action) { + combo.setFont(FontManager.getRunescapeSmallFont()); + combo.setAlignmentX(Component.LEFT_ALIGNMENT); + combo.setMaximumSize(new Dimension(Integer.MAX_VALUE, ROW_HEIGHT)); + combo.setToolTipText(tooltip); + combo.addActionListener(e -> action.run()); + return combo; + } + + private static JSpinner spinner(int value, int min, int max) { + JSpinner spinner = new JSpinner(new SpinnerNumberModel(value, min, max, 1)); + var editor = new JSpinner.NumberEditor(spinner, "#"); + editor.getTextField().setHorizontalAlignment(JTextField.LEFT); + spinner.setEditor(editor); + + spinner.setMinimumSize(new Dimension(44, ROW_HEIGHT)); + spinner.setPreferredSize(new Dimension(60, ROW_HEIGHT)); + spinner.setMaximumSize(new Dimension(Integer.MAX_VALUE, ROW_HEIGHT)); + return spinner; + } + + private void toggleMap() { + if (mapHost != null && mapHost.isOpen()) { + mapHost.close(); + return; + } + + if (mapHost == null) { + mapHost = new MapHost( + tools.client(), + region -> regionIds.setText(String.valueOf(region)), + region -> { + regionIds.setText(String.valueOf(region)); + load(); + }, + this::coverageOf + ); + mapHost.setOnAdded(this::toggleRegion); + mapHost.setOnCleared(this::clearPickedRegions); + } + + int[] wanted = wantedRegions(); + mapHost.setListed(wanted); + mapHost.open(wanted.length == 0 ? LUMBRIDGE : wanted[0]); + } + + @Nullable + private int[] coverageOf(int region) { + // Picked regions are laid out side by side rather than where they sit in the world, and nothing is + // loaded around them, so the only true thing to show is which ones are picked + if (region < 0 || wantedRegions().length > 1) + return null; + return SceneBuilder.sceneTiles( + worldXOf(region), worldYOf(region), (Integer) expandedChunks.getValue()); + } + + public void closeMap() { + if (mapHost != null) + mapHost.close(); + } + + private static BufferedImage createMapIcon() { + BufferedImage image = new BufferedImage(14, 14, BufferedImage.TYPE_INT_ARGB); + var g = image.createGraphics(); + + g.setColor(new Color(0xC8, 0xC8, 0xC8)); + g.fillRect(1, 1, 12, 12); + g.setColor(new Color(0xFF, 0xA0, 0x30)); + g.fillRect(5, 5, 4, 4); + + g.setColor(new Color(0x38, 0x38, 0x38)); + g.drawRect(1, 1, 12, 12); + g.drawLine(5, 2, 5, 12); + g.drawLine(9, 2, 9, 12); + g.drawLine(2, 5, 12, 5); + g.drawLine(2, 9, 12, 9); + + g.dispose(); + return image; + } + + public static BufferedImage createIcon() { + BufferedImage image = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); + var g = image.createGraphics(); + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setColor(new Color(0xC0, 0xC0, 0xC0)); + g.fillOval(3, 1, 10, 10); + g.fillPolygon(new int[] { 5, 11, 8 }, new int[] { 9, 9, 15 }, 3); + g.setColor(ColorScheme.DARK_GRAY_COLOR); + g.fillOval(6, 4, 4, 4); + g.dispose(); + return image; + } + + private static final class VariantRenderer extends DefaultListCellRenderer { + @Override + public Component getListCellRendererComponent( + JList list, Object value, int index, boolean selected, boolean focused + ) { + super.getListCellRendererComponent(list, value, index, selected, focused); + if (!(value instanceof VariantObject)) + return this; + + var object = (VariantObject) value; + setText(object.label() + (object.animated ? " [anim]" : "")); + setToolTipText(object.variantIds.length + " forms to choose between"); + setFont(FontManager.getRunescapeSmallFont()); + if (!selected) + setForeground(Color.LIGHT_GRAY); + return this; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/CameraOverlay.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/CameraOverlay.java new file mode 100644 index 0000000..52f0bcb --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/CameraOverlay.java @@ -0,0 +1,92 @@ +package rs117.hd.dev.sceneloader.devtools; + +import java.awt.Dimension; +import java.awt.Graphics2D; +import javax.inject.Inject; +import javax.inject.Singleton; +import net.runelite.api.Client; +import net.runelite.client.ui.overlay.Overlay; +import net.runelite.client.ui.overlay.OverlayManager; +import net.runelite.client.ui.overlay.OverlayPosition; +import net.runelite.client.ui.overlay.components.LineComponent; +import net.runelite.client.ui.overlay.components.PanelComponent; +import rs117.hd.HdPlugin; +import rs117.hd.dev.sceneloader.SceneLoader; + +import static rs117.hd.utils.MathUtils.JAU_FINE_TO_RAD; + +/** + * RuneLite's Camera panel, for the camera the scene is actually drawn with. + * + *

The same four rows in the same order and the same units. Only where the numbers come from differs: the + * client's own camera stays over the player while this one is flown about, so reading it would describe a + * view nobody is looking through. 117 HD keeps what it was handed each frame, which is what was drawn. + */ +@Singleton +public class CameraOverlay extends Overlay { + @Inject + private Client client; + + @Inject + private HdPlugin plugin; + + @Inject + private OverlayManager overlayManager; + + @Inject + private SceneLoader tools; + + @Inject + private DevToolBridge devTools; + + private final PanelComponent panel = new PanelComponent(); + private boolean added; + + public CameraOverlay() { + setPosition(OverlayPosition.TOP_LEFT); + } + + public void startUp() { + if (added) + return; + added = true; + overlayManager.add(this); + } + + public void shutDown() { + if (!added) + return; + added = false; + overlayManager.remove(this); + } + + @Override + public Dimension render(Graphics2D g) { + if (tools.getLoaded() == null || !devTools.isStandingIn() || !devTools.isActive("cameraPosition")) + return null; + + var position = plugin.cameraPosition; + panel.getChildren().clear(); + + // RuneLite prints x, then height, then northing, which is the order this is already kept in + panel.getChildren().add(LineComponent.builder() + .left("Camera") + .right(Math.round(position[0]) + ", " + Math.round(position[1]) + ", " + Math.round(position[2])) + .build()); + // Back into the whole units the client counts angles in, so these read like the original's + panel.getChildren().add(LineComponent.builder() + .left("Pitch") + .right(String.valueOf(Math.round(plugin.cameraOrientation[1] / JAU_FINE_TO_RAD))) + .build()); + panel.getChildren().add(LineComponent.builder() + .left("Yaw") + .right(String.valueOf(Math.round(plugin.cameraOrientation[0] / JAU_FINE_TO_RAD))) + .build()); + panel.getChildren().add(LineComponent.builder() + .left("Scale") + .right(String.valueOf(client.getScale())) + .build()); + + return panel.render(g); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/DevToolBridge.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/DevToolBridge.java new file mode 100644 index 0000000..bf7aee4 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/DevToolBridge.java @@ -0,0 +1,193 @@ +package rs117.hd.dev.sceneloader.devtools; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.swing.AbstractButton; +import javax.swing.SwingUtilities; +import lombok.extern.slf4j.Slf4j; +import net.runelite.client.plugins.Plugin; +import net.runelite.client.plugins.PluginManager; +import net.runelite.client.ui.overlay.Overlay; +import net.runelite.client.ui.overlay.OverlayManager; + +/** + * Lets RuneLite's own scene tools keep working on a scene they know nothing about. + * + *

Their buttons are left alone and read rather than disabled, so pressing Walls still means walls. What + * is taken away is their drawing: every one of them reads the scene straight off the client and draws it + * through the client's camera, and neither is what is on screen while a cache scene is up. They would + * outline tiles where nothing stands and name objects belonging to wherever the player happens to be. + * + *

So their overlays are lifted out for as long as a cache scene is loaded and {@link SceneToolsOverlay} + * draws the same things from this scene instead. The buttons go on working as they always did; only what + * answers them changes. + */ +@Slf4j +@Singleton +public class DevToolBridge { + private static final String DEV_TOOLS_PACKAGE = "net.runelite.client.plugins.devtools."; + private static final String DEV_TOOLS_PLUGIN = DEV_TOOLS_PACKAGE + "DevToolsPlugin"; + + /** + * The ones there is nothing here for them to describe. + * + *

A cache scene is ground and scenery and nothing else: nobody is standing in it, nothing is moving + * through it, and it carries none of the collision the client walks on. These are switched off and + * greyed while it is up, since leaving them pressable would only ever answer about somewhere else. + * Everything that is not about the scene at all — the widget, variable, script and inventory + * inspectors, the shell and the rest — is left alone. + */ + private static final List UNANSWERABLE = List.of( + "players", + "npcs", + "groundItems", + "graphicsObjects", + "projectiles", + "interacting", + "worldEntities", + "lineOfSight", + "validMovement", + "movementFlags", + "zoneBorders", + "loadingLines", + "worldMapLocation", + "detachedCamera" + ); + + private static final String WHY_GREYED = + "Nothing for this to describe while a cache scene is loaded: it is ground and scenery only."; + + @Inject + private PluginManager pluginManager; + + @Inject + private OverlayManager overlayManager; + + /** Their overlays while they are lifted out, so the same ones can be put back */ + private final List lifted = new ArrayList<>(); + /** Which of the greyed ones were switched on, so they come back the way they were */ + private final List wasActive = new ArrayList<>(); + private final Map buttons = new HashMap<>(); + private boolean standingIn; + + /** Whether one of RuneLite's tools is switched on, by the name of its button's field */ + public boolean isActive(String name) { + Field field = button(name); + if (field == null) + return false; + + try { + Object button = field.get(find()); + Method isActive = button.getClass().getDeclaredMethod("isActive"); + isActive.setAccessible(true); + return (Boolean) isActive.invoke(button); + } catch (Exception ex) { + log.debug("Could not read RuneLite's {} tool", name, ex); + return false; + } + } + + @Nullable + private Field button(String name) { + if (buttons.containsKey(name)) + return buttons.get(name); + + Field found = null; + Plugin devTools = find(); + if (devTools != null) { + try { + found = devTools.getClass().getDeclaredField(name); + found.setAccessible(true); + } catch (Exception ex) { + log.debug("RuneLite has no {} tool", name, ex); + } + } + buttons.put(name, found); + return found; + } + + /** Takes over the drawing, leaving the buttons where they are */ + public void standIn() { + if (standingIn) + return; + standingIn = true; + + // The predicate is what does the lifting, since there is no way to ask which overlays are in there + overlayManager.removeIf(overlay -> { + if (!overlay.getClass().getName().startsWith(DEV_TOOLS_PACKAGE)) + return false; + lifted.add(overlay); + return true; + }); + + SwingUtilities.invokeLater(() -> greyOut(true)); + } + + /** Hands the drawing back */ + public void standDown() { + if (!standingIn) + return; + standingIn = false; + + for (Overlay overlay : lifted) + overlayManager.add(overlay); + lifted.clear(); + + SwingUtilities.invokeLater(() -> greyOut(false)); + } + + private void greyOut(boolean grey) { + for (String name : UNANSWERABLE) { + Field field = button(name); + if (field == null) + continue; + + try { + Object button = field.get(find()); + if (!(button instanceof AbstractButton)) + continue; + + if (grey) { + if (isActive(name)) + wasActive.add(name); + setActive(button, false); + } else if (wasActive.contains(name)) { + setActive(button, true); + } + + ((AbstractButton) button).setEnabled(!grey); + ((AbstractButton) button).setToolTipText(grey ? WHY_GREYED : null); + } catch (Exception ex) { + log.debug("Could not grey RuneLite's {} tool", name, ex); + } + } + + if (!grey) + wasActive.clear(); + } + + private static void setActive(Object button, boolean active) throws Exception { + Method setActive = button.getClass().getDeclaredMethod("setActive", boolean.class); + setActive.setAccessible(true); + setActive.invoke(button, active); + } + + public boolean isStandingIn() { + return standingIn; + } + + @Nullable + private Plugin find() { + for (Plugin plugin : pluginManager.getPlugins()) + if (DEV_TOOLS_PLUGIN.equals(plugin.getClass().getName())) + return plugin; + return null; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/LocationOverlay.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/LocationOverlay.java new file mode 100644 index 0000000..ea3e90c --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/LocationOverlay.java @@ -0,0 +1,114 @@ +package rs117.hd.dev.sceneloader.devtools; + +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.util.Arrays; +import java.util.stream.Collectors; +import javax.inject.Inject; +import javax.inject.Singleton; +import net.runelite.api.Client; +import net.runelite.client.ui.overlay.Overlay; +import net.runelite.client.ui.overlay.OverlayManager; +import net.runelite.client.ui.overlay.OverlayPosition; +import net.runelite.client.ui.overlay.components.LineComponent; +import net.runelite.client.ui.overlay.components.PanelComponent; +import rs117.hd.HdPlugin; +import rs117.hd.dev.sceneloader.SceneLoader; +import rs117.hd.utils.HDUtils; + +import static net.runelite.api.Constants.CHUNK_SIZE; + +/** + * RuneLite's Location panel, for the scene that is on screen. + * + *

The same rows in the same order, read the same way. What they describe is the camera rather than the + * player, since a cache scene has no player in it: the player is still standing wherever the game left + * them, usually in another part of the world entirely, and reporting that while looking at somewhere else + * is how the original goes wrong here. + */ +@Singleton +public class LocationOverlay extends Overlay { + private static final int TILE_SIZE = 128; + + @Inject + private Client client; + + @Inject + private HdPlugin plugin; + + @Inject + private OverlayManager overlayManager; + + @Inject + private SceneLoader tools; + + @Inject + private DevToolBridge devTools; + + private final PanelComponent panel = new PanelComponent(); + private boolean added; + + public LocationOverlay() { + setPosition(OverlayPosition.TOP_LEFT); + } + + public void startUp() { + if (added) + return; + added = true; + overlayManager.add(this); + } + + public void shutDown() { + if (!added) + return; + added = false; + overlayManager.remove(this); + } + + @Override + public Dimension render(Graphics2D g) { + var scene = tools.getLoaded(); + if (scene == null || !devTools.isStandingIn() || !devTools.isActive("location")) + return null; + + int localX = Math.round(plugin.cameraPosition[0]); + int localY = Math.round(plugin.cameraPosition[2]); + int sceneX = Math.floorDiv(localX, TILE_SIZE); + int sceneY = Math.floorDiv(localY, TILE_SIZE); + int plane = client.getPlane(); + int[] world = scene.isInstance() + ? HDUtils.sceneToWorld(scene, sceneX, sceneY, plane) + : new int[] { scene.getBaseX() + sceneX, scene.getBaseY() + sceneY, plane }; + + panel.getChildren().clear(); + if (scene.isInstance()) + panel.getChildren().add(LineComponent.builder().left("Instance").build()); + + panel.getChildren().add(LineComponent.builder() + .left("Local") + .right(localX + ", " + localY) + .build()); + panel.getChildren().add(LineComponent.builder() + .left("World") + .right(world[0] + ", " + world[1] + ", " + world[2]) + .build()); + panel.getChildren().add(LineComponent.builder() + .left("Scene") + .right(sceneX + ", " + sceneY) + .build()); + + panel.getChildren().add(LineComponent.builder() + .left("Base") + .right(scene.getBaseX() + ", " + scene.getBaseY()) + .build()); + panel.getChildren().add(LineComponent.builder() + .left("Map regions") + .right(Arrays.stream(scene.getMapRegions()) + .mapToObj(String::valueOf) + .collect(Collectors.joining(", "))) + .build()); + + return panel.render(g); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SceneToolsOverlay.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SceneToolsOverlay.java new file mode 100644 index 0000000..1257877 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SceneToolsOverlay.java @@ -0,0 +1,284 @@ +package rs117.hd.dev.sceneloader.devtools; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.Polygon; +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; +import net.runelite.api.Client; +import net.runelite.api.Tile; +import net.runelite.api.TileObject; +import net.runelite.client.ui.FontManager; +import net.runelite.client.ui.overlay.Overlay; +import net.runelite.client.ui.overlay.OverlayLayer; +import net.runelite.client.ui.overlay.OverlayManager; +import net.runelite.client.ui.overlay.OverlayPosition; +import rs117.hd.HdPlugin; +import rs117.hd.dev.sceneloader.SceneLoader; +import rs117.hd.dev.sceneloader.scene.BuiltScene; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; +import static net.runelite.api.Constants.MAX_Z; + +/** + * Draws what RuneLite's scene tools would draw, for the scene that is actually on screen. + * + *

Its buttons are RuneLite's own, read through {@link DevToolBridge}, so Walls still means walls and + * turning one off still turns it off. Only the two things RuneLite's own drawing cannot get right here are + * done differently: the tiles come from the cache scene rather than from the client, and the projection uses + * the camera the frame was drawn with rather than the client's, which stays wherever the player is standing + * while this one is flown about. + */ +@Singleton +public class SceneToolsOverlay extends Overlay { + private static final Color GAME_OBJECTS = Color.GREEN; + private static final Color WALLS = new Color(0x00, 0xB0, 0xFF); + private static final Color DECORATIONS = new Color(0xD0, 0x60, 0xFF); + private static final Color GROUND_OBJECTS = new Color(0xFF, 0xA0, 0x30); + private static final Color MAP_SQUARES = new Color(0xFF, 0xFF, 0x00, 0xA0); + private static final Color TILE_LOCATION = Color.WHITE; + /** Red, the same as RuneLite draws its tile flags in */ + private static final Color TILE_FLAGS = Color.RED; + + private static final int TILE_SIZE = 128; + private static final int REGION_TILES = 64; + /** How far out to bother drawing, since every tile has to be projected by hand */ + private static final int DRAW_RADIUS_TILES = 28; + + @Inject + private Client client; + + @Inject + private HdPlugin plugin; + + @Inject + private OverlayManager overlayManager; + + @Inject + private SceneLoader tools; + + @Inject + private DevToolBridge devTools; + + private boolean added; + + public SceneToolsOverlay() { + setPosition(OverlayPosition.DYNAMIC); + setLayer(OverlayLayer.ABOVE_SCENE); + } + + public void startUp() { + if (added) + return; + added = true; + overlayManager.add(this); + } + + public void shutDown() { + if (!added) + return; + added = false; + overlayManager.remove(this); + } + + @Override + public Dimension render(Graphics2D g) { + var scene = tools.getLoaded(); + if (scene == null || !devTools.isStandingIn()) + return null; + + g.setFont(FontManager.getRunescapeSmallFont()); + + boolean gameObjects = devTools.isActive("gameObjects"); + boolean walls = devTools.isActive("walls"); + boolean decorations = devTools.isActive("decorations"); + boolean groundObjects = devTools.isActive("groundObjects"); + boolean tileLocation = devTools.isActive("tileLocation"); + boolean tileFlags = devTools.isActive("tileFlags"); + + if (gameObjects || walls || decorations || groundObjects || tileLocation || tileFlags) + drawTiles(g, scene, gameObjects, walls, decorations, groundObjects, tileLocation, tileFlags); + + if (devTools.isActive("mapSquares")) + drawMapSquares(g, scene); + + return null; + } + + private void drawTiles( + Graphics2D g, BuiltScene scene, + boolean gameObjects, boolean walls, boolean decorations, boolean groundObjects, + boolean tileLocation, boolean tileFlags + ) { + var tiles = scene.getExtendedTiles(); + int plane = Math.max(0, Math.min(MAX_Z - 1, client.getPlane())); + + int fromX = cameraTileX() - DRAW_RADIUS_TILES; + int toX = cameraTileX() + DRAW_RADIUS_TILES; + int fromY = cameraTileY() - DRAW_RADIUS_TILES; + int toY = cameraTileY() + DRAW_RADIUS_TILES; + + for (int x = Math.max(0, fromX); x <= Math.min(EXTENDED_SCENE_SIZE - 1, toX); x++) { + for (int y = Math.max(0, fromY); y <= Math.min(EXTENDED_SCENE_SIZE - 1, toY); y++) { + Tile tile = tiles[plane][x][y]; + if (tile == null) + continue; + + if (gameObjects) + for (var object : tile.getGameObjects()) + mark(g, scene, plane, x, y, object, GAME_OBJECTS); + if (walls) + mark(g, scene, plane, x, y, tile.getWallObject(), WALLS); + if (decorations) + mark(g, scene, plane, x, y, tile.getDecorativeObject(), DECORATIONS); + if (groundObjects) + mark(g, scene, plane, x, y, tile.getGroundObject(), GROUND_OBJECTS); + if (tileLocation) + label(g, scene, plane, x, y, (x - scene.getSceneOffset()) + ", " + (y - scene.getSceneOffset()), + TILE_LOCATION); + // The same settings byte RuneLite reads off the client, taken from this scene instead + if (tileFlags) + label(g, scene, plane, x, y, + String.valueOf(scene.getExtendedTileSettings()[plane][x][y]), TILE_FLAGS); + } + } + } + + private void mark( + Graphics2D g, BuiltScene scene, int plane, int x, int y, @Nullable TileObject object, Color color + ) { + if (object == null) + return; + + var poly = tilePoly(scene, plane, x, y); + if (poly == null) + return; + + g.setColor(color); + g.drawPolygon(poly); + label(g, scene, plane, x, y, String.valueOf(object.getId()), color); + } + + private void label(Graphics2D g, BuiltScene scene, int plane, int x, int y, String text, Color color) { + float[] middle = project( + (x - scene.getSceneOffset()) * TILE_SIZE + TILE_SIZE / 2, + (y - scene.getSceneOffset()) * TILE_SIZE + TILE_SIZE / 2, + heightAt(scene, plane, x, y) + ); + if (middle == null) + return; + + int width = g.getFontMetrics().stringWidth(text); + g.setColor(Color.BLACK); + g.drawString(text, middle[0] - width / 2f + 1, middle[1] + 1); + g.setColor(color); + g.drawString(text, middle[0] - width / 2f, middle[1]); + } + + private void drawMapSquares(Graphics2D g, BuiltScene scene) { + g.setColor(MAP_SQUARES); + int offset = scene.getSceneOffset(); + + // Where the regions fall is a property of the world, so the lines go wherever a region edge lands + for (int x = -offset; x <= EXTENDED_SCENE_SIZE - offset; x++) { + if (Math.floorMod(scene.getBaseX() + x, REGION_TILES) != 0) + continue; + drawSceneLine(g, scene, x, -offset, x, EXTENDED_SCENE_SIZE - offset); + } + for (int y = -offset; y <= EXTENDED_SCENE_SIZE - offset; y++) { + if (Math.floorMod(scene.getBaseY() + y, REGION_TILES) != 0) + continue; + drawSceneLine(g, scene, -offset, y, EXTENDED_SCENE_SIZE - offset, y); + } + } + + private void drawSceneLine(Graphics2D g, BuiltScene scene, int fromX, int fromY, int toX, int toY) { + int plane = Math.max(0, Math.min(MAX_Z - 1, client.getPlane())); + int steps = Math.max(Math.abs(toX - fromX), Math.abs(toY - fromY)); + float[] previous = null; + + for (int i = 0; i <= steps; i++) { + int x = fromX + (toX - fromX) * i / steps; + int y = fromY + (toY - fromY) * i / steps; + float[] point = project( + x * TILE_SIZE, y * TILE_SIZE, + heightAt(scene, plane, x + scene.getSceneOffset(), y + scene.getSceneOffset()) + ); + if (previous != null && point != null) + g.drawLine((int) previous[0], (int) previous[1], (int) point[0], (int) point[1]); + previous = point; + } + } + + private int cameraTileX() { + return (int) Math.floor(plugin.cameraPosition[0] / TILE_SIZE) + BuiltScene.SCENE_OFFSET; + } + + private int cameraTileY() { + return (int) Math.floor(plugin.cameraPosition[2] / TILE_SIZE) + BuiltScene.SCENE_OFFSET; + } + + private static int heightAt(BuiltScene scene, int plane, int x, int y) { + int[][][] heights = scene.getTileHeights(); + if (x < 0 || y < 0 || x >= heights[plane].length || y >= heights[plane][x].length) + return 0; + return heights[plane][x][y]; + } + + @Nullable + private Polygon tilePoly(BuiltScene scene, int plane, int x, int y) { + int offset = scene.getSceneOffset(); + int west = (x - offset) * TILE_SIZE; + int east = west + TILE_SIZE; + int south = (y - offset) * TILE_SIZE; + int north = south + TILE_SIZE; + + float[] sw = project(west, south, heightAt(scene, plane, x, y)); + float[] se = project(east, south, heightAt(scene, plane, x + 1, y)); + float[] ne = project(east, north, heightAt(scene, plane, x + 1, y + 1)); + float[] nw = project(west, north, heightAt(scene, plane, x, y + 1)); + if (sw == null || se == null || ne == null || nw == null) + return null; + + var poly = new Polygon(); + poly.addPoint((int) sw[0], (int) sw[1]); + poly.addPoint((int) se[0], (int) se[1]); + poly.addPoint((int) ne[0], (int) ne[1]); + poly.addPoint((int) nw[0], (int) nw[1]); + return poly; + } + + /** + * Local scene coordinates to the canvas, through the camera the scene was drawn with. + * + *

The client's own camera is no use here: it stays where the player is standing while this tool's + * camera is flown elsewhere, and everything would be placed from there instead of from what is on + * screen. 117 HD keeps what it was handed, which is what was actually drawn. + */ + @Nullable + private float[] project(int x, int y, int height) { + float dx = x - plugin.cameraPosition[0]; + float dy = y - plugin.cameraPosition[2]; + float dz = height - plugin.cameraPosition[1]; + + float yawSin = (float) Math.sin(plugin.cameraOrientation[0]); + float yawCos = (float) Math.cos(plugin.cameraOrientation[0]); + float pitchSin = (float) Math.sin(plugin.cameraOrientation[1]); + float pitchCos = (float) Math.cos(plugin.cameraOrientation[1]); + + float x1 = dx * yawCos + dy * yawSin; + float y1 = dy * yawCos - dx * yawSin; + float y2 = dz * pitchCos - y1 * pitchSin; + float z1 = y1 * pitchCos + dz * pitchSin; + if (z1 < 1) + return null; + + float scale = client.getScale(); + return new float[] { + x1 * scale / z1 + client.getViewportWidth() / 2f + client.getViewportXOffset(), + y2 * scale / z1 + client.getViewportHeight() / 2f + client.getViewportYOffset() + }; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SelectionHighlight.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SelectionHighlight.java new file mode 100644 index 0000000..394c4f2 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/devtools/SelectionHighlight.java @@ -0,0 +1,120 @@ +package rs117.hd.dev.sceneloader.devtools; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics2D; +import java.awt.Polygon; +import javax.annotation.Nullable; +import javax.inject.Inject; +import javax.inject.Singleton; +import net.runelite.api.Client; +import net.runelite.api.Perspective; +import net.runelite.api.Point; +import net.runelite.client.ui.FontManager; +import net.runelite.client.ui.overlay.Overlay; +import net.runelite.client.ui.overlay.OverlayLayer; +import net.runelite.client.ui.overlay.OverlayManager; +import net.runelite.client.ui.overlay.OverlayPosition; +import rs117.hd.dev.sceneloader.scene.VariantObject; + +@Singleton +public class SelectionHighlight extends Overlay { + private static final Color OUTLINE = new Color(0x00E0FF); + private static final Color SHADE = new Color(0x2200E0FF, true); + private static final int TILE_SIZE = 128; + private static final long SHOWN_FOR_MILLIS = 8000; + + @Inject + private Client client; + + @Inject + private OverlayManager overlayManager; + + private boolean added; + + @Nullable + private volatile VariantObject.Placed target; + private volatile String label = ""; + private volatile long until; + + public SelectionHighlight() { + setPosition(OverlayPosition.DYNAMIC); + setLayer(OverlayLayer.ABOVE_SCENE); + } + + public void startUp() { + if (added) + return; + added = true; + overlayManager.add(this); + } + + public void shutDown() { + if (!added) + return; + added = false; + clear(); + overlayManager.remove(this); + } + + public void mark(VariantObject.Placed placed, String label) { + this.target = placed; + this.label = label; + this.until = System.currentTimeMillis() + SHOWN_FOR_MILLIS; + } + + public void clear() { + target = null; + } + + @Override + public Dimension render(Graphics2D g) { + var placed = target; + if (placed == null) + return null; + if (System.currentTimeMillis() > until) { + target = null; + return null; + } + + int halfX = placed.sizeX * TILE_SIZE / 2; + int halfY = placed.sizeY * TILE_SIZE / 2; + + Point southWest = project(placed.x - halfX, placed.z - halfY, placed.y); + Point southEast = project(placed.x + halfX, placed.z - halfY, placed.y); + Point northEast = project(placed.x + halfX, placed.z + halfY, placed.y); + Point northWest = project(placed.x - halfX, placed.z + halfY, placed.y); + if (southWest == null || southEast == null || northEast == null || northWest == null) + return null; + + var footprint = new Polygon(); + footprint.addPoint(southWest.getX(), southWest.getY()); + footprint.addPoint(southEast.getX(), southEast.getY()); + footprint.addPoint(northEast.getX(), northEast.getY()); + footprint.addPoint(northWest.getX(), northWest.getY()); + + g.setColor(SHADE); + g.fill(footprint); + g.setColor(OUTLINE); + g.setStroke(new BasicStroke(2)); + g.draw(footprint); + + if (!label.isEmpty()) { + int top = Math.min(Math.min(southWest.getY(), southEast.getY()), Math.min(northEast.getY(), northWest.getY())); + int middle = (southWest.getX() + northEast.getX()) / 2; + g.setFont(FontManager.getRunescapeSmallFont()); + int width = g.getFontMetrics().stringWidth(label); + g.setColor(Color.BLACK); + g.drawString(label, middle - width / 2 + 1, top - 5); + g.setColor(OUTLINE); + g.drawString(label, middle - width / 2, top - 6); + } + return null; + } + + @Nullable + private Point project(int x, int z, int height) { + return Perspective.localToCanvas(client, x, z, height); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapControls.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapControls.java new file mode 100644 index 0000000..85c9bee --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapControls.java @@ -0,0 +1,218 @@ +package rs117.hd.dev.sceneloader.map; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.FlowLayout; +import javax.annotation.Nullable; +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTextField; +import net.runelite.client.ui.ColorScheme; +import net.runelite.client.ui.FontManager; + +import static rs117.hd.dev.sceneloader.map.MapProjection.REGION_SIZE; + + +class MapControls extends JPanel { + private static final int NARROW = 44; + private static final int WIDE = 58; + + private final RegionMapPanel map; + + private final JTextField worldX = field(WIDE, "The world tile under the mouse. Type one and press enter to go there."); + private final JTextField worldY = field(WIDE, "The world tile under the mouse. Type one and press enter to go there."); + private final JTextField regionId = field(WIDE, "The region under the mouse. Type one and press enter to go there."); + private final JTextField regionX = field(NARROW, "Which region across. Type one and press enter to go there."); + private final JTextField regionY = field(NARROW, "Which region up. Type one and press enter to go there."); + private final JTextField baseX = readOnly(WIDE, "The world tile the region starts at"); + private final JTextField baseY = readOnly(WIDE, "The world tile the region starts at"); + private final JTextField localX = readOnly(NARROW, "How far into the region, across"); + private final JTextField localY = readOnly(NARROW, "How far into the region, up"); + private final JComboBox plane = new JComboBox<>(new String[] { "0", "1", "2", "3" }); + private final JButton popOut = new JButton(); + private final JButton clearPicked = new JButton("Clear"); + private final MapWindow window; + + interface MapWindow { + void togglePopOut(); + + void close(); + + boolean isPoppedOut(); + } + + MapControls(RegionMapPanel map, MapWindow window) { + this.map = map; + this.window = window; + + setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4)); + setBackground(ColorScheme.DARK_GRAY_COLOR); + setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4)); + + add(label("X")); + add(worldX); + add(label("Y")); + add(worldY); + add(gap()); + + add(label("Region")); + add(regionId); + add(label("at")); + add(regionX); + add(label(",")); + add(regionY); + add(gap()); + + add(label("Base")); + add(baseX); + add(label(",")); + add(baseY); + add(gap()); + + add(label("Local")); + add(localX); + add(label(",")); + add(localY); + add(gap()); + + add(label("Plane")); + plane.setFont(FontManager.getRunescapeSmallFont()); + plane.setToolTipText("Which floor of the map to show"); + plane.addActionListener(e -> map.setPlane(plane.getSelectedIndex())); + add(plane); + add(gap()); + + popOut.setFont(FontManager.getRunescapeSmallFont()); + popOut.addActionListener(e -> { + window.togglePopOut(); + updatePopOut(); + }); + add(popOut); + + clearPicked.setFont(FontManager.getRunescapeSmallFont()); + clearPicked.setToolTipText("Forget the picked regions and go back to choosing one at a time"); + clearPicked.addActionListener(e -> map.clearPicked()); + add(clearPicked); + + var close = new JButton("Close"); + close.setFont(FontManager.getRunescapeSmallFont()); + close.setToolTipText("Put the game view back"); + close.addActionListener(e -> window.close()); + add(close); + + updatePopOut(); + + onEnter(worldX, this::goToWorld); + onEnter(worldY, this::goToWorld); + onEnter(regionId, this::goToRegionId); + onEnter(regionX, this::goToRegionCoords); + onEnter(regionY, this::goToRegionCoords); + + map.setPointerListener(this::follow); + map.setPickingListener(this::updatePicking); + updatePicking(); + } + + /** The button is only worth having while there is something picked to forget */ + private void updatePicking() { + clearPicked.setVisible(map.isPicking()); + } + + private void updatePopOut() { + boolean out = window.isPoppedOut(); + popOut.setText(out ? "Over game" : "Pop out"); + popOut.setToolTipText(out + ? "Put the map over the game view, where it has the most room" + : "Move the map into a window of its own, so the game can be seen behind it"); + } + + private void follow(int tileX, int tileY) { + int region = MapProjection.regionIdAt(tileX, tileY); + int rx = MapProjection.regionX(region); + int ry = MapProjection.regionY(region); + + set(worldX, tileX); + set(worldY, tileY); + set(regionId, region); + set(regionX, rx); + set(regionY, ry); + set(baseX, rx * REGION_SIZE); + set(baseY, ry * REGION_SIZE); + set(localX, tileX - rx * REGION_SIZE); + set(localY, tileY - ry * REGION_SIZE); + } + + private static void set(JTextField field, int value) { + if (field.isFocusOwner()) + return; + field.setText(Integer.toString(value)); + } + + private void goToWorld() { + Integer x = number(worldX); + Integer y = number(worldY); + if (x == null || y == null) + return; + map.goTo(x, y); + } + + private void goToRegionId() { + Integer id = number(regionId); + if (id != null) + map.select(id); + } + + private void goToRegionCoords() { + Integer x = number(regionX); + Integer y = number(regionY); + if (x == null || y == null || x < 0 || x > 0xFF || y < 0 || y > 0xFF) + return; + map.select(x << 8 | y); + } + + @Nullable + private static Integer number(JTextField field) { + try { + return Integer.parseInt(field.getText().trim()); + } catch (NumberFormatException ignored) { + return null; + } + } + + private static void onEnter(JTextField field, Runnable action) { + field.addActionListener(e -> action.run()); + } + + private static JTextField field(int width, String tooltip) { + var field = new JTextField(); + field.setFont(FontManager.getRunescapeSmallFont()); + field.setToolTipText(tooltip); + field.setHorizontalAlignment(JTextField.CENTER); + field.setPreferredSize(new Dimension(width, 20)); + return field; + } + + private static JTextField readOnly(int width, String tooltip) { + var field = field(width, tooltip); + field.setEditable(false); + field.setFocusable(false); + field.setBackground(ColorScheme.DARKER_GRAY_COLOR); + field.setForeground(Color.LIGHT_GRAY); + return field; + } + + private static JLabel label(String text) { + var label = new JLabel(text); + label.setFont(FontManager.getRunescapeSmallFont()); + label.setForeground(Color.LIGHT_GRAY); + return label; + } + + private static java.awt.Component gap() { + return Box.createHorizontalStrut(10); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapHost.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapHost.java new file mode 100644 index 0000000..db290f4 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapHost.java @@ -0,0 +1,248 @@ +package rs117.hd.dev.sceneloader.map; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Window; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.function.IntConsumer; +import javax.annotation.Nullable; +import javax.swing.BorderFactory; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import lombok.extern.slf4j.Slf4j; +import net.runelite.api.Client; +import net.runelite.client.ui.ColorScheme; +import net.runelite.client.ui.FontManager; + +@Slf4j +public class MapHost implements MapControls.MapWindow { + private static final String CLIENT_PANEL = "net.runelite.client.ui.ClientPanel"; + private static final Dimension WINDOW_SIZE = new Dimension(960, 760); + + private final Client client; + private final IntConsumer onChosen; + private final IntConsumer onOpened; + @Nullable + private final RegionMapPanel.Coverage coverage; + + @Nullable + private JPanel content; + @Nullable + private RegionMapPanel map; + + @Nullable + private JDialog window; + + @Nullable + private Container gameHost; + @Nullable + private Component gameView; + + private boolean poppedOut; + + public MapHost( + Client client, IntConsumer onChosen, IntConsumer onOpened, + @Nullable RegionMapPanel.Coverage coverage + ) { + this.client = client; + this.onChosen = onChosen; + this.onOpened = onOpened; + this.coverage = coverage; + } + + public void setOnAdded(@Nullable IntConsumer onAdded) { + this.onAdded = onAdded; + if (map != null) + map.setOnAdded(onAdded); + } + + public void setOnCleared(@Nullable Runnable onCleared) { + this.onCleared = onCleared; + if (map != null) + map.setOnCleared(onCleared); + } + + public void setListed(int[] listedRegions) { + this.listed = listedRegions; + if (map != null) + map.setListed(listedRegions); + } + + @Nullable + private IntConsumer onAdded; + @Nullable + private Runnable onCleared; + private int[] listed = new int[0]; + + public void refresh() { + if (map != null) + map.setCoverage(coverage); + } + + public boolean isOpen() { + return content != null; + } + + public void open(int startRegion) { + assert SwingUtilities.isEventDispatchThread(); + + if (content != null) { + if (map != null) + map.select(startRegion); + if (window != null) + window.toFront(); + return; + } + + build(startRegion); + if (poppedOut || !embed()) + popOutWindow(); + } + + private void build(int startRegion) { + var status = new JLabel(" "); + status.setFont(FontManager.getRunescapeSmallFont()); + status.setForeground(Color.LIGHT_GRAY); + status.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8)); + + map = new RegionMapPanel(startRegion, onChosen, region -> { + onOpened.accept(region); + if (!poppedOut) + close(); + }, status); + map.setCoverage(coverage); + map.setOnAdded(onAdded); + map.setOnCleared(onCleared); + map.setListed(listed); + + content = new JPanel(new BorderLayout()); + content.setBackground(ColorScheme.DARK_GRAY_COLOR); + content.add(new MapControls(map, this), BorderLayout.NORTH); + content.add(map, BorderLayout.CENTER); + content.add(status, BorderLayout.SOUTH); + } + + @Override + public boolean isPoppedOut() { + return poppedOut; + } + + @Override + public void togglePopOut() { + if (content == null) + return; + + if (poppedOut) { + closeWindow(); + if (!embed()) + popOutWindow(); + } else { + restoreGameView(); + popOutWindow(); + } + } + + @Override + public void close() { + if (content == null) + return; + + closeWindow(); + restoreGameView(); + if (map != null) + map.shutDown(); + map = null; + content = null; + } + + + private boolean embed() { + Container host = findGameHost(); + if (host == null) { + log.debug("Could not find the game view to put the map over, so it opens in a window instead"); + return false; + } + + gameHost = host; + gameView = centreOf(host); + if (gameView == null) + return false; + + gameView.setVisible(false); + host.add(content, BorderLayout.CENTER); + host.revalidate(); + host.repaint(); + + poppedOut = false; + return true; + } + + private void restoreGameView() { + if (gameHost == null || gameView == null) + return; + + gameHost.remove(content); + ((BorderLayout) gameHost.getLayout()).addLayoutComponent(gameView, BorderLayout.CENTER); + gameView.setVisible(true); + gameHost.revalidate(); + gameHost.repaint(); + + gameHost = null; + gameView = null; + } + + @Nullable + private Container findGameHost() { + Component canvas = client.getCanvas(); + for (Container parent = canvas == null ? null : canvas.getParent(); + parent != null; + parent = parent.getParent()) { + if (CLIENT_PANEL.equals(parent.getClass().getName()) && parent.getLayout() instanceof BorderLayout) + return parent; + } + return null; + } + + @Nullable + private static Component centreOf(Container host) { + var layout = (BorderLayout) host.getLayout(); + return layout.getLayoutComponent(BorderLayout.CENTER); + } + + + private void popOutWindow() { + Window parent = SwingUtilities.getWindowAncestor(client.getCanvas()); + window = new JDialog(parent, "117 HD — pick a region", JDialog.ModalityType.MODELESS); + window.setContentPane(content); + window.setSize(WINDOW_SIZE); + window.setLocationRelativeTo(parent); + window.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + window.addWindowListener(new WindowAdapter() { + @Override + public void windowClosed(WindowEvent event) { + if (window != null) { + window = null; + close(); + } + } + }); + + poppedOut = true; + window.setVisible(true); + } + + private void closeWindow() { + if (window == null) + return; + var closing = window; + window = null; + closing.setContentPane(new JPanel()); + closing.dispose(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapProjection.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapProjection.java new file mode 100644 index 0000000..dc38a9f --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapProjection.java @@ -0,0 +1,72 @@ +package rs117.hd.dev.sceneloader.map; + +public final class MapProjection { + public static final int TILE_SIZE = 256; + public static final int MIN_ZOOM = 4; + public static final int MAX_ZOOM = 11; + public static final int WORLD_TILE_PX = 32; + public static final int REGION_SIZE = 64; + public static final int REGION_PX = REGION_SIZE * WORLD_TILE_PX; + + private static final int VERTICAL_ORIGIN_PX = 364544; + private static final int WORLD_X_ORIGIN = 960; + private static final int WORLD_Y_ORIGIN = 6208; + + public static final int MIN_WORLD_X = WORLD_X_ORIGIN; + public static final int MAX_WORLD_X = 4224; + public static final int MIN_WORLD_Y = 1216; + public static final int MAX_WORLD_Y = 12608; + + private MapProjection() {} + + public static int pixelX(int worldX) { + return (worldX - WORLD_X_ORIGIN) * WORLD_TILE_PX; + } + + public static int pixelY(int worldY) { + return VERTICAL_ORIGIN_PX - (worldY - WORLD_Y_ORIGIN) * WORLD_TILE_PX; + } + + public static int worldX(double pixelX) { + return (int) Math.floor(pixelX / WORLD_TILE_PX) + WORLD_X_ORIGIN; + } + + public static int worldY(double pixelY) { + return (int) Math.floor((VERTICAL_ORIGIN_PX - pixelY) / WORLD_TILE_PX) + WORLD_Y_ORIGIN; + } + + public static int scale(int zoom) { + return 1 << (MAX_ZOOM - zoom); + } + + public static int regionPx(int zoom) { + return REGION_PX / scale(zoom); + } + + public static int regionIdAt(int worldX, int worldY) { + return (worldX / REGION_SIZE) << 8 | worldY / REGION_SIZE; + } + + public static int regionX(int regionId) { + return regionId >> 8 & 0xFF; + } + + public static int regionY(int regionId) { + return regionId & 0xFF; + } + + public static boolean isOnMap(int regionId) { + int worldX = regionX(regionId) * REGION_SIZE; + int worldY = regionY(regionId) * REGION_SIZE; + return worldX >= MIN_WORLD_X && worldX < MAX_WORLD_X + && worldY >= MIN_WORLD_Y && worldY < MAX_WORLD_Y; + } + + public static int tileIndex(double pixel, int zoom) { + return (int) Math.floor(pixel / scale(zoom) / TILE_SIZE); + } + + public static int flipTileY(int tileY, int zoom) { + return (1 << zoom) - 1 - tileY; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapTileCache.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapTileCache.java new file mode 100644 index 0000000..601666b --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/MapTileCache.java @@ -0,0 +1,240 @@ +package rs117.hd.dev.sceneloader.map; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import javax.imageio.ImageIO; +import lombok.extern.slf4j.Slf4j; +import rs117.hd.HdPlugin; + +@Slf4j +public class MapTileCache { + private static final String REPO = "Mark7625/osrs_map_tiles"; + private static final String BRANCH = "master"; + private static final String RAW_URL = "https://raw.githubusercontent.com/" + REPO + "/%s/%d/%d/%d/%d.png"; + private static final String COMMIT_URL = "https://api.github.com/repos/" + REPO + "/commits/" + BRANCH; + private static final String USER_AGENT = "117hd-dev-cache-scene"; + + private static final long RECHECK_MILLIS = 12 * 60 * 60 * 1000L; + private static final int CONNECT_TIMEOUT_MILLIS = 8000; + private static final int READ_TIMEOUT_MILLIS = 20000; + + private static final int IMAGES_IN_MEMORY = 160; + + private final Path root = HdPlugin.PLUGIN_DIR.resolve("map-tiles").toPath(); + private final ExecutorService downloads = Executors.newFixedThreadPool(4, runnable -> { + Thread thread = new Thread(runnable, "cache-scene-map-tiles"); + thread.setDaemon(true); + return thread; + }); + + private final Map images = new LinkedHashMap<>(16, 0.75f, true) { + @Override + protected boolean removeEldestEntry(Map.Entry eldest) { + return size() > IMAGES_IN_MEMORY; + } + }; + + private final Set pending = ConcurrentHashMap.newKeySet(); + private final Set missing = ConcurrentHashMap.newKeySet(); + + private volatile String commit; + + private final Runnable onLoaded; + + public MapTileCache(Runnable onLoaded) { + this.onLoaded = onLoaded; + } + + public void shutDown() { + downloads.shutdownNow(); + synchronized (images) { + images.clear(); + } + } + + @Nullable + public BufferedImage get(int plane, int zoom, int tileX, int tileY) { + long key = key(plane, zoom, tileX, tileY); + + BufferedImage image; + synchronized (images) { + image = images.get(key); + } + if (image != null || missing.contains(key)) + return image; + + if (pending.add(key)) + downloads.submit(() -> load(key, plane, zoom, tileX, tileY)); + return null; + } + + private void load(long key, int plane, int zoom, int tileX, int tileY) { + try { + String commit = commit(); + Path file = root.resolve(commit).resolve(plane + "/" + zoom + "/" + tileX + "/" + tileY + ".png"); + + byte[] bytes; + if (Files.isRegularFile(file)) { + bytes = Files.readAllBytes(file); + } else { + bytes = download(String.format(RAW_URL, commit, plane, zoom, tileX, tileY)); + if (bytes != null) { + Files.createDirectories(file.getParent()); + Path partial = file.resolveSibling(file.getFileName() + ".part"); + Files.write(partial, bytes); + Files.move(partial, file, java.nio.file.StandardCopyOption.REPLACE_EXISTING); + } + } + + if (bytes == null) { + missing.add(key); + return; + } + + BufferedImage image = ImageIO.read(new java.io.ByteArrayInputStream(bytes)); + if (image == null) { + missing.add(key); + return; + } + + synchronized (images) { + images.put(key, image); + } + onLoaded.run(); + } catch (Exception ex) { + missing.add(key); + log.debug("Could not load map tile {}/{}/{}/{}", plane, zoom, tileX, tileY, ex); + } finally { + pending.remove(key); + } + } + + @Nullable + private byte[] download(String url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestProperty("User-Agent", USER_AGENT); + connection.setConnectTimeout(CONNECT_TIMEOUT_MILLIS); + connection.setReadTimeout(READ_TIMEOUT_MILLIS); + try { + if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) + return null; + try (InputStream in = connection.getInputStream()) { + return in.readAllBytes(); + } + } finally { + connection.disconnect(); + } + } + + private synchronized String commit() { + if (commit == null) { + try { + commit = resolveCommit(); + } catch (Exception ex) { + log.debug("Could not work out which map tiles are current, using whatever is cached", ex); + commit = BRANCH; + } + } + return commit; + } + + private String resolveCommit() throws IOException { + Path marker = root.resolve("version"); + String stored = null; + long checkedAt = 0; + if (Files.isRegularFile(marker)) { + String[] lines = Files.readString(marker, StandardCharsets.UTF_8).split("\n"); + stored = lines[0].trim(); + if (lines.length > 1) { + try { + checkedAt = Long.parseLong(lines[1].trim()); + } catch (NumberFormatException ignored) { + } + } + } + + boolean due = System.currentTimeMillis() - checkedAt > RECHECK_MILLIS; + if (stored != null && !due) + return stored; + + String current = fetchCommit(); + if (current == null) + return stored != null ? stored : BRANCH; + + if (!current.equals(stored)) { + log.debug("Map tiles have changed, fetching them again at {}", current); + deleteOldTiles(current); + } + + Files.createDirectories(root); + Files.writeString(marker, current + "\n" + System.currentTimeMillis(), StandardCharsets.UTF_8); + return current; + } + + @Nullable + private String fetchCommit() throws IOException { + HttpURLConnection connection = (HttpURLConnection) new URL(COMMIT_URL).openConnection(); + connection.setRequestProperty("User-Agent", USER_AGENT); + connection.setRequestProperty("Accept", "application/vnd.github+json"); + connection.setConnectTimeout(CONNECT_TIMEOUT_MILLIS); + connection.setReadTimeout(READ_TIMEOUT_MILLIS); + try { + if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) + return null; + try (var reader = new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8)) { + var json = new Gson().fromJson(reader, JsonObject.class); + return json != null && json.has("sha") ? json.get("sha").getAsString() : null; + } + } finally { + connection.disconnect(); + } + } + + private void deleteOldTiles(String keep) { + if (!Files.isDirectory(root)) + return; + try (Stream entries = Files.list(root)) { + entries + .filter(Files::isDirectory) + .filter(path -> !path.getFileName().toString().equals(keep)) + .forEach(MapTileCache::deleteTree); + } catch (IOException ex) { + log.debug("Could not clear out the old map tiles", ex); + } + } + + private static void deleteTree(Path path) { + try (Stream tree = Files.walk(path)) { + tree.sorted(Comparator.reverseOrder()).forEach(entry -> { + try { + Files.deleteIfExists(entry); + } catch (IOException ignored) { + } + }); + } catch (IOException ex) { + log.debug("Could not delete {}", path, ex); + } + } + + private static long key(int plane, int zoom, int tileX, int tileY) { + return (long) plane << 56 | (long) zoom << 48 | (long) (tileX & 0xFFFFFF) << 24 | tileY & 0xFFFFFF; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/map/RegionMapPanel.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/RegionMapPanel.java new file mode 100644 index 0000000..bb70981 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/map/RegionMapPanel.java @@ -0,0 +1,485 @@ +package rs117.hd.dev.sceneloader.map; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Point; +import java.awt.RenderingHints; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseWheelEvent; +import java.awt.image.BufferedImage; +import java.util.function.IntConsumer; +import javax.annotation.Nullable; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import net.runelite.client.ui.ColorScheme; + +import static rs117.hd.dev.sceneloader.map.MapProjection.MAX_ZOOM; +import static rs117.hd.dev.sceneloader.map.MapProjection.MIN_ZOOM; +import static rs117.hd.dev.sceneloader.map.MapProjection.REGION_SIZE; +import static rs117.hd.dev.sceneloader.map.MapProjection.TILE_SIZE; + + +public class RegionMapPanel extends JPanel { + private static final int INITIAL_ZOOM = 6; + private static final int GRID_VISIBLE_PX = 24; + + private static final Color HOVER_FILL = new Color(0x33, 0xB5, 0xE5, 90); + private static final Color HOVER_LINE = new Color(0x33, 0xB5, 0xE5); + private static final Color CHOSEN_LINE = new Color(0xFF, 0xA0, 0x30); + private static final Color GRID_LINE = new Color(255, 255, 255, 40); + private static final Color COVERAGE_FILL = new Color(0xFF, 0xA0, 0x30, 36); + private static final Color COVERAGE_LINE = new Color(0xFF, 0xC8, 0x70, 190); + private static final Color BUILT_LINE = new Color(0x7C, 0xE8, 0x7C); + private static final BasicStroke COVERAGE_STROKE = new BasicStroke( + 2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10, new float[] { 6, 4 }, 0); + + private static final Color LISTED_FILL = new Color(0x33, 0xE0, 0xFF, 0x33); + private static final Color LISTED_LINE = new Color(0x33, 0xE0, 0xFF); + + private final MapTileCache tiles; + private final IntConsumer onChosen; + private final IntConsumer onOpened; + private final JLabel status; + + private int plane; + private int zoom = INITIAL_ZOOM; + private double centreX, centreY; + + private int chosenRegion; + private int hoveredRegion = -1; + @Nullable + private IntConsumer onAdded; + @Nullable + private Runnable onCleared; + @Nullable + private Runnable pickingListener; + private int[] listedRegions = new int[0]; + private Point dragFrom; + + @Nullable + private PointerListener pointerListener; + + public interface PointerListener { + void moved(int worldX, int worldY); + } + + @Nullable + private Coverage coverage; + + public interface Coverage { + @Nullable + int[] tilesFor(int regionId); + } + + public void setOnAdded(@Nullable IntConsumer onAdded) { + this.onAdded = onAdded; + } + + public void setOnCleared(@Nullable Runnable onCleared) { + this.onCleared = onCleared; + } + + public void clearPicked() { + if (onCleared != null) + onCleared.run(); + } + + public void setListed(int[] listedRegions) { + this.listedRegions = listedRegions; + if (pickingListener != null) + pickingListener.run(); + describe(); + repaint(); + } + + public void setPickingListener(@Nullable Runnable pickingListener) { + this.pickingListener = pickingListener; + } + + /** Whether more than one region is picked, which is when the map stops being a single choice */ + public boolean isPicking() { + return listedRegions.length > 1; + } + + public void setCoverage(@Nullable Coverage coverage) { + this.coverage = coverage; + describe(); + repaint(); + } + + public RegionMapPanel(int startRegion, IntConsumer onChosen, IntConsumer onOpened, JLabel status) { + this.onChosen = onChosen; + this.onOpened = onOpened; + this.status = status; + // Where it opens looking, not what it has picked. Nothing is picked until something is clicked. + this.chosenRegion = -1; + this.tiles = new MapTileCache(this::repaintLater); + + centreOn(startRegion); + + setBackground(ColorScheme.DARKER_GRAY_COLOR); + setFocusable(true); + + var mouse = new MouseAdapter() { + @Override + public void mousePressed(MouseEvent event) { + dragFrom = event.getPoint(); + requestFocusInWindow(); + } + + @Override + public void mouseReleased(MouseEvent event) { + dragFrom = null; + } + + @Override + public void mouseDragged(MouseEvent event) { + if (dragFrom == null) + return; + int scale = MapProjection.scale(zoom); + centreX -= (double) (event.getX() - dragFrom.x) * scale; + centreY -= (double) (event.getY() - dragFrom.y) * scale; + dragFrom = event.getPoint(); + updatePointer(event.getPoint()); + repaint(); + } + + @Override + public void mouseMoved(MouseEvent event) { + updatePointer(event.getPoint()); + } + + @Override + public void mouseExited(MouseEvent event) { + hoveredRegion = -1; + describe(); + repaint(); + } + + @Override + public void mouseClicked(MouseEvent event) { + int region = regionAt(event.getPoint()); + if (region < 0) + return; + + if (event.isControlDown() && onAdded != null) { + onAdded.accept(region); + describe(); + repaint(); + return; + } + + // While several are picked the map is a list to edit, not a place to go, so an ordinary + // click would either be ignored or throw the picking away. It does nothing instead. + if (isPicking()) + return; + + chosenRegion = region; + onChosen.accept(region); + describe(); + repaint(); + + if (event.getClickCount() >= 2) + onOpened.accept(region); + } + + @Override + public void mouseWheelMoved(MouseWheelEvent event) { + zoomBy(-event.getWheelRotation(), event.getPoint()); + } + }; + addMouseListener(mouse); + addMouseMotionListener(mouse); + addMouseWheelListener(mouse); + } + + public void shutDown() { + tiles.shutDown(); + } + + public void setPlane(int plane) { + this.plane = plane; + repaint(); + } + + private void repaintLater() { + SwingUtilities.invokeLater(this::repaint); + } + + public void goTo(int worldX, int worldY) { + centreX = MapProjection.pixelX(worldX); + centreY = MapProjection.pixelY(worldY); + repaint(); + } + + public void select(int regionId) { + if (!MapProjection.isOnMap(regionId)) + return; + chosenRegion = regionId; + onChosen.accept(regionId); + describe(); + centreOn(regionId); + } + + public void centreOn(int regionId) { + centreX = MapProjection.pixelX(MapProjection.regionX(regionId) * REGION_SIZE + REGION_SIZE / 2); + centreY = MapProjection.pixelY(MapProjection.regionY(regionId) * REGION_SIZE + REGION_SIZE / 2); + repaint(); + } + + private void zoomBy(int steps, Point at) { + int wanted = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoom + steps)); + if (wanted == zoom) + return; + + double beforeX = pixelAtX(at.x); + double beforeY = pixelAtY(at.y); + zoom = wanted; + centreX += beforeX - pixelAtX(at.x); + centreY += beforeY - pixelAtY(at.y); + + updatePointer(at); + repaint(); + } + + private double pixelAtX(int screenX) { + return centreX + (screenX - getWidth() / 2.0) * MapProjection.scale(zoom); + } + + private double pixelAtY(int screenY) { + return centreY + (screenY - getHeight() / 2.0) * MapProjection.scale(zoom); + } + + public void setPointerListener(@Nullable PointerListener listener) { + this.pointerListener = listener; + } + + private void updatePointer(Point at) { + if (pointerListener != null) { + int worldX = MapProjection.worldX(pixelAtX(at.x)); + int worldY = MapProjection.worldY(pixelAtY(at.y)); + if (worldX >= 0 && worldY >= 0) + pointerListener.moved(worldX, worldY); + } + updateHover(at); + } + + private void updateHover(Point at) { + int region = regionAt(at); + if (region == hoveredRegion) + return; + hoveredRegion = region; + describe(); + repaint(); + } + + private int regionAt(Point at) { + int worldX = MapProjection.worldX(pixelAtX(at.x)); + int worldY = MapProjection.worldY(pixelAtY(at.y)); + if (worldX < 0 || worldY < 0) + return -1; + + int region = MapProjection.regionIdAt(worldX, worldY); + return MapProjection.isOnMap(region) ? region : -1; + } + + private void describe() { + if (status == null) + return; + + String hint; + if (onAdded == null) { + hint = "Drag to move, scroll to zoom, double click a region to load it"; + } else if (isPicking()) { + hint = "Ctrl click to pick a region or take one back, Clear to go back to one at a time"; + } else { + hint = "Drag to move, scroll to zoom, double click to load, ctrl click to pick several"; + } + String here = hoveredRegion < 0 + ? hint + : String.format( + "Region %d (%d, %d) at %d, %d", + hoveredRegion, + MapProjection.regionX(hoveredRegion), MapProjection.regionY(hoveredRegion), + MapProjection.regionX(hoveredRegion) * REGION_SIZE, + MapProjection.regionY(hoveredRegion) * REGION_SIZE + ); + if (hoveredRegion >= 0 && isPicking()) + here += " — " + listedRegions.length + " picked, ctrl click to " + + (isListed(hoveredRegion) ? "take it back" : "add it"); + status.setText(here + coverageNote()); + } + + /** + * What loading the region under the mouse would pull in. + * + *

It follows the pointer rather than whatever is chosen, so it reads as a preview of the region being + * considered. Pinned to the chosen one it painted a large overlay the moment the map opened, over a + * region nobody had picked, which looks like a selection that was never made. + */ + @Nullable + private int[] coverageTiles() { + if (coverage == null || hoveredRegion < 0) + return null; + return coverage.tilesFor(hoveredRegion); + } + + private String coverageNote() { + int[] tiles = coverageTiles(); + if (tiles == null) + return ""; + + int across = (tiles[2] >> 6) - (tiles[0] >> 6) + 1; + int up = (tiles[3] >> 6) - (tiles[1] >> 6) + 1; + return String.format( + " Loading %d builds %d x %d tiles, x %d to %d and y %d to %d, reading %d x %d regions (%d)", + hoveredRegion, + tiles[2] - tiles[0] + 1, tiles[3] - tiles[1] + 1, + tiles[0], tiles[2], tiles[1], tiles[3], + across, up, across * up + ); + } + + @Override + protected void paintComponent(Graphics graphics) { + super.paintComponent(graphics); + var g = (Graphics2D) graphics.create(); + try { + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); + drawTiles(g); + drawGrid(g); + drawCoverage(g); + for (int listed : listedRegions) + drawRegion(g, listed, LISTED_FILL, LISTED_LINE, 2); + if (!isPicking()) + drawRegion(g, chosenRegion, null, CHOSEN_LINE, 2); + if (hoveredRegion >= 0 && hoveredRegion != chosenRegion) + drawRegion(g, hoveredRegion, HOVER_FILL, HOVER_LINE, 1); + else if (hoveredRegion >= 0) + drawRegion(g, hoveredRegion, HOVER_FILL, CHOSEN_LINE, 2); + } finally { + g.dispose(); + } + } + + private void drawTiles(Graphics2D g) { + int scale = MapProjection.scale(zoom); + int onScreen = TILE_SIZE; + + int firstX = MapProjection.tileIndex(pixelAtX(0), zoom); + int lastX = MapProjection.tileIndex(pixelAtX(getWidth()), zoom); + int firstY = MapProjection.tileIndex(pixelAtY(0), zoom); + int lastY = MapProjection.tileIndex(pixelAtY(getHeight()), zoom); + + for (int tileX = firstX; tileX <= lastX; tileX++) { + for (int tileY = firstY; tileY <= lastY; tileY++) { + if (tileX < 0 || tileY < 0) + continue; + + BufferedImage image = tiles.get(plane, zoom, tileX, MapProjection.flipTileY(tileY, zoom)); + if (image == null) + continue; + + int screenX = screenXOf((double) tileX * TILE_SIZE * scale); + int screenY = screenYOf((double) tileY * TILE_SIZE * scale); + g.drawImage(image, screenX, screenY, onScreen, onScreen, null); + } + } + } + + private void drawCoverage(Graphics2D g) { + int[] tiles = coverageTiles(); + if (tiles == null) + return; + + fillTiles(g, + (tiles[0] >> 6) * REGION_SIZE, (tiles[1] >> 6) * REGION_SIZE, + ((tiles[2] >> 6) + 1) * REGION_SIZE - 1, ((tiles[3] >> 6) + 1) * REGION_SIZE - 1, + COVERAGE_FILL, COVERAGE_LINE, new BasicStroke(1)); + + fillTiles(g, tiles[0], tiles[1], tiles[2], tiles[3], null, BUILT_LINE, COVERAGE_STROKE); + } + + private void fillTiles( + Graphics2D g, int firstX, int firstY, int lastX, int lastY, + @Nullable Color fill, Color line, BasicStroke stroke + ) { + int left = screenXOf(MapProjection.pixelX(firstX)); + int right = screenXOf(MapProjection.pixelX(lastX + 1)); + int bottom = screenYOf(MapProjection.pixelY(firstY)); + int top = screenYOf(MapProjection.pixelY(lastY + 1)); + + if (fill != null) { + g.setColor(fill); + g.fillRect(left, top, right - left, bottom - top); + } + g.setColor(line); + g.setStroke(stroke); + g.drawRect(left, top, right - left, bottom - top); + } + + private void drawGrid(Graphics2D g) { + int regionPx = MapProjection.regionPx(zoom); + if (regionPx < GRID_VISIBLE_PX) + return; + + g.setColor(GRID_LINE); + g.setStroke(new BasicStroke(1)); + + int firstX = Math.floorDiv(MapProjection.worldX(pixelAtX(0)), REGION_SIZE); + int lastX = Math.floorDiv(MapProjection.worldX(pixelAtX(getWidth())), REGION_SIZE); + for (int x = firstX; x <= lastX + 1; x++) { + int screenX = screenXOf(MapProjection.pixelX(x * REGION_SIZE)); + g.drawLine(screenX, 0, screenX, getHeight()); + } + + int firstY = Math.floorDiv(MapProjection.worldY(pixelAtY(getHeight())), REGION_SIZE); + int lastY = Math.floorDiv(MapProjection.worldY(pixelAtY(0)), REGION_SIZE); + for (int y = firstY; y <= lastY + 1; y++) { + int screenY = screenYOf(MapProjection.pixelY(y * REGION_SIZE)); + g.drawLine(0, screenY, getWidth(), screenY); + } + } + + private boolean isListed(int region) { + for (int listed : listedRegions) + if (listed == region) + return true; + return false; + } + + private void drawRegion(Graphics2D g, int regionId, Color fill, Color line, int thickness) { + if (regionId < 0) + return; + + int worldX = MapProjection.regionX(regionId) * REGION_SIZE; + int worldY = MapProjection.regionY(regionId) * REGION_SIZE; + + int left = screenXOf(MapProjection.pixelX(worldX)); + int right = screenXOf(MapProjection.pixelX(worldX + REGION_SIZE)); + int bottom = screenYOf(MapProjection.pixelY(worldY)); + int top = screenYOf(MapProjection.pixelY(worldY + REGION_SIZE)); + + if (fill != null) { + g.setColor(fill); + g.fillRect(left, top, right - left, bottom - top); + } + g.setColor(line); + g.setStroke(new BasicStroke(thickness)); + g.drawRect(left, top, right - left, bottom - top); + } + + private int screenXOf(double pixelX) { + return (int) Math.round((pixelX - centreX) / MapProjection.scale(zoom) + getWidth() / 2.0); + } + + private int screenYOf(double pixelY) { + return (int) Math.round((pixelY - centreY) / MapProjection.scale(zoom) + getHeight() / 2.0); + } + +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltAnimation.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltAnimation.java new file mode 100644 index 0000000..e5a5d9f --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltAnimation.java @@ -0,0 +1,86 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.Animation; +import net.runelite.cache.definitions.SequenceDefinition; + +public class BuiltAnimation implements Animation { + private final SequenceDefinition sequence; + private final int duration; + + private int restartMode; + + public BuiltAnimation(SequenceDefinition sequence) { + this.sequence = sequence; + + int total = 0; + if (sequence.frameLengths != null) + for (int length : sequence.frameLengths) + total += length; + this.duration = total; + } + + public SequenceDefinition definition() { + return sequence; + } + + public int frameCount() { + return sequence.frameIDs == null ? 0 : sequence.frameIDs.length; + } + + public int frameLength(int frame) { + int[] lengths = sequence.frameLengths; + if (lengths == null || frame < 0 || frame >= lengths.length) + return 1; + return Math.max(1, lengths[frame]); + } + + @Override + public int getId() { + return sequence.getId(); + } + + @Override + public int getDuration() { + return duration; + } + + @Override + public int getNumFrames() { + return frameCount(); + } + + @Override + public int getRestartMode() { + return restartMode; + } + + @Override + public void setRestartMode(int restartMode) { + this.restartMode = restartMode; + } + + @Override + public int[] getFrameLengths() { + return sequence.frameLengths; + } + + @Override + public int getLeftHandItem() { + return sequence.leftHandItem; + } + + @Override + public int getRightHandItem() { + return sequence.rightHandItem; + } + + @Override + public int getFrameStep() { + return sequence.frameStep; + } + + @Override + public boolean isMayaAnim() { + return sequence.animMayaID != -1; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDecorativeObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDecorativeObject.java new file mode 100644 index 0000000..9fbc7d1 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDecorativeObject.java @@ -0,0 +1,69 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.DecorativeObject; +import net.runelite.api.Renderable; + +public class BuiltDecorativeObject extends BuiltTileObject implements DecorativeObject { + private Renderable renderable, renderable2; + private int xOffset, yOffset; + private final int xOffset2, yOffset2; + + public BuiltDecorativeObject( + BuiltScene scene, long hash, int config, int x, int y, int z, int plane, + Renderable renderable, Renderable renderable2, + int xOffset, int yOffset, int xOffset2, int yOffset2 + ) { + super(scene, hash, config, x, y, z, plane); + this.renderable = renderable; + this.renderable2 = renderable2; + this.xOffset = xOffset; + this.yOffset = yOffset; + this.xOffset2 = xOffset2; + this.yOffset2 = yOffset2; + } + + public void displace(int displacement) { + if (xOffset != 0) + xOffset = xOffset < 0 ? -displacement : displacement; + if (yOffset != 0) + yOffset = yOffset < 0 ? -displacement : displacement; + } + + @Override + public Renderable getRenderable() { + return renderable; + } + + @Override + public Renderable getRenderable2() { + return renderable2; + } + + public void setRenderable(Renderable renderable) { + this.renderable = renderable; + } + + public void setRenderable2(Renderable renderable) { + renderable2 = renderable; + } + + @Override + public int getXOffset() { + return xOffset; + } + + @Override + public int getYOffset() { + return yOffset; + } + + @Override + public int getXOffset2() { + return xOffset2; + } + + @Override + public int getYOffset2() { + return yOffset2; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDynamicObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDynamicObject.java new file mode 100644 index 0000000..66c7bbd --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltDynamicObject.java @@ -0,0 +1,225 @@ +package rs117.hd.dev.sceneloader.scene; + +import javax.annotation.Nullable; +import net.runelite.api.Animation; +import net.runelite.api.DynamicObject; +import net.runelite.api.Model; +import net.runelite.api.ObjectComposition; + +public class BuiltDynamicObject implements net.runelite.api.Renderable, DynamicObject { + public static final int CYCLE_MILLIS = 20; + + private final int objectId; + @Nullable + private final BuiltAnimation animation; + private final Model[] frames; + + private int frame; + private int cycleInFrame; + private int loops; + private int lastCycle = Integer.MIN_VALUE; + + private int modelHeight; + + public BuiltDynamicObject(int objectId, @Nullable BuiltAnimation animation, Model[] frames) { + this.objectId = objectId; + this.animation = animation; + this.frames = frames; + } + + public boolean posesDiffer() { + if (posesChecked) + return posesMove; + posesChecked = true; + + Model first = null; + for (Model model : frames) { + if (model == null) + continue; + if (first == null) { + first = model; + continue; + } + if (movedFrom(first, model)) { + posesMove = true; + break; + } + } + return posesMove; + } + + private boolean posesChecked; + private boolean posesMove; + + private static boolean movedFrom(Model a, Model b) { + if (a == b) + return false; + + float[] ax = a.getVerticesX(), bx = b.getVerticesX(); + float[] az = a.getVerticesZ(), bz = b.getVerticesZ(); + if (ax.length != bx.length) + return true; + for (int i = 0; i < ax.length; i++) + if (ax[i] != bx[i] || az[i] != bz[i]) + return true; + + byte[] at = a.getFaceTransparencies(), bt = b.getFaceTransparencies(); + if (at == null || bt == null) + return at != bt; + if (at.length != bt.length) + return true; + for (int i = 0; i < at.length; i++) + if (at[i] != bt[i]) + return true; + return false; + } + + public boolean hasModel() { + for (Model model : frames) + if (model != null) + return true; + return false; + } + + public Model modelAt(int cycle) { + advanceTo(cycle); + return getModel(); + } + + private void advanceTo(int cycle) { + if (animation == null || frames.length <= 1) + return; + + if (lastCycle == Integer.MIN_VALUE) { + lastCycle = cycle; + return; + } + + int elapsed = cycle - lastCycle; + lastCycle = cycle; + if (elapsed <= 0) + return; + + int frameCount = frames.length; + int frameStep = animation.getFrameStep(); + int duration = animation.getDuration(); + if (frameStep > 0 && duration > 0) + elapsed %= duration; + + if (frame >= frameCount) { + frame = 0; + cycleInFrame = 0; + } + + int spent = elapsed + cycleInFrame; + while (spent > animation.frameLength(frame)) { + spent -= animation.frameLength(frame); + frame++; + + if (frame >= frameCount) { + loops++; + frame -= frameStep; + if (frame < 0 || frame >= frameCount) + frame = 0; + } + } + cycleInFrame = spent; + } + + + @Override + public Model getModel() { + int at = Math.min(Math.max(frame, 0), frames.length - 1); + if (frames[at] != null) + return frames[at]; + + for (int away = 1; away < frames.length; away++) { + int before = at - away; + if (before >= 0 && frames[before] != null) + return frames[before]; + int after = at + away; + if (after < frames.length && frames[after] != null) + return frames[after]; + } + return null; + } + + @Override + public int getModelHeight() { + if (modelHeight == 0) { + Model model = getModel(); + modelHeight = model == null ? 0 : model.getModelHeight(); + } + return modelHeight; + } + + @Override + public void setModelHeight(int modelHeight) { + this.modelHeight = modelHeight; + } + + @Override + public int getRenderMode() { + return 0; + } + + @Override + public int getAnimationHeightOffset() { + return 0; + } + + @Override + public int getAnimFrame() { + return frame; + } + + @Override + public int getAnimCycle() { + return cycleInFrame; + } + + @Nullable + @Override + public Model getModelZbuf() { + return animation == null ? getModel() : null; + } + + @Nullable + @Override + public Animation getAnimation() { + return animation; + } + + @Nullable + @Override + public ObjectComposition getRecordedObjectComposition() { + return null; + } + + public int getObjectId() { + return objectId; + } + + + @Override + public net.runelite.api.Node getNext() { + return null; + } + + @Override + public net.runelite.api.Node getPrevious() { + return null; + } + + @Override + public long getHash() { + return 0; + } + + @Override + public String toString() { + return "BuiltDynamicObject(" + objectId + + ", animation " + (animation == null ? "none" : animation.getId()) + + ", " + frames.length + " frames)"; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGameObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGameObject.java new file mode 100644 index 0000000..3400145 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGameObject.java @@ -0,0 +1,66 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.GameObject; +import net.runelite.api.Point; +import net.runelite.api.Renderable; + +public class BuiltGameObject extends BuiltTileObject implements GameObject { + private static final int ROTATION_UNIT = 512; + + private Renderable renderable; + private final int modelOrientation; + private final int minSceneX, minSceneY, maxSceneX, maxSceneY; + + public BuiltGameObject( + BuiltScene scene, long hash, int config, int x, int y, int z, int plane, + Renderable renderable, int modelOrientation, + int minSceneX, int minSceneY, int maxSceneX, int maxSceneY + ) { + super(scene, hash, config, x, y, z, plane); + this.renderable = renderable; + this.modelOrientation = modelOrientation; + this.minSceneX = minSceneX; + this.minSceneY = minSceneY; + this.maxSceneX = maxSceneX; + this.maxSceneY = maxSceneY; + } + + @Override + public int sizeX() { + return maxSceneX - minSceneX + 1; + } + + @Override + public int sizeY() { + return maxSceneY - minSceneY + 1; + } + + @Override + public Point getSceneMinLocation() { + return new Point(minSceneX, minSceneY); + } + + @Override + public Point getSceneMaxLocation() { + return new Point(maxSceneX, maxSceneY); + } + + @Override + public int getOrientation() { + return getRotation() * ROTATION_UNIT + modelOrientation; + } + + @Override + public Renderable getRenderable() { + return renderable; + } + + public void setRenderable(Renderable renderable) { + this.renderable = renderable; + } + + @Override + public int getModelOrientation() { + return modelOrientation; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGroundObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGroundObject.java new file mode 100644 index 0000000..c9c039e --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltGroundObject.java @@ -0,0 +1,24 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.GroundObject; +import net.runelite.api.Renderable; + +public class BuiltGroundObject extends BuiltTileObject implements GroundObject { + private Renderable renderable; + + public BuiltGroundObject( + BuiltScene scene, long hash, int config, int x, int y, int z, int plane, Renderable renderable + ) { + super(scene, hash, config, x, y, z, plane); + this.renderable = renderable; + } + + @Override + public Renderable getRenderable() { + return renderable; + } + + public void setRenderable(Renderable renderable) { + this.renderable = renderable; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltModel.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltModel.java new file mode 100644 index 0000000..df538a0 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltModel.java @@ -0,0 +1,445 @@ +package rs117.hd.dev.sceneloader.scene; + +import javax.annotation.Nonnull; +import net.runelite.api.AABB; +import net.runelite.api.Model; +import net.runelite.api.Node; + +public class BuiltModel implements Model { + int verticesCount; + float[] verticesX, verticesY, verticesZ; + + int faceCount; + int[] faceIndices1, faceIndices2, faceIndices3; + + int[] faceColors1, faceColors2, faceColors3; + short[] unlitFaceColors; + + byte[] faceTransparencies; + byte transparency; + short[] faceTextures; + byte[] textureFaces; + int[] texIndices1, texIndices2, texIndices3; + + int[] vertexNormalsX, vertexNormalsY, vertexNormalsZ; + + byte[] faceRenderPriorities; + byte[] faceBias; + + int modelHeight, bottomY, xyzMag, radius, diameter; + private boolean boundsCalculated; + + private int sceneId, bufferOffset, uvBufferOffset; + + BuiltModel copyForContour() { + var copy = new BuiltModel(); + + copy.verticesCount = verticesCount; + copy.verticesX = verticesX; + copy.verticesY = new float[verticesCount]; + copy.verticesZ = verticesZ; + + copy.faceCount = faceCount; + copy.faceIndices1 = faceIndices1; + copy.faceIndices2 = faceIndices2; + copy.faceIndices3 = faceIndices3; + + copy.faceColors1 = faceColors1; + copy.faceColors2 = faceColors2; + copy.faceColors3 = faceColors3; + copy.unlitFaceColors = unlitFaceColors; + + copy.faceTransparencies = faceTransparencies; + copy.transparency = transparency; + copy.faceTextures = faceTextures; + copy.textureFaces = textureFaces; + copy.texIndices1 = texIndices1; + copy.texIndices2 = texIndices2; + copy.texIndices3 = texIndices3; + + copy.vertexNormalsX = vertexNormalsX; + copy.vertexNormalsY = vertexNormalsY; + copy.vertexNormalsZ = vertexNormalsZ; + + copy.faceRenderPriorities = faceRenderPriorities; + copy.faceBias = faceBias; + + return copy; + } + + BuiltModel withVertices(float[] x, float[] y, float[] z) { + var copy = copyForContour(); + copy.verticesX = x; + copy.verticesY = y; + copy.verticesZ = z; + return copy; + } + + BuiltModel withPose(float[] x, float[] y, float[] z, byte[] faceTransparencies) { + var copy = withVertices(x, y, z); + copy.faceTransparencies = faceTransparencies; + return copy; + } + + @Override + public int getVerticesCount() { + return verticesCount; + } + + @Override + public float[] getVerticesX() { + return verticesX; + } + + @Override + public float[] getVerticesY() { + return verticesY; + } + + @Override + public float[] getVerticesZ() { + return verticesZ; + } + + @Override + public int getFaceCount() { + return faceCount; + } + + @Override + public int[] getFaceIndices1() { + return faceIndices1; + } + + @Override + public int[] getFaceIndices2() { + return faceIndices2; + } + + @Override + public int[] getFaceIndices3() { + return faceIndices3; + } + + @Override + public byte[] getFaceTransparencies() { + return faceTransparencies; + } + + @Override + public short[] getFaceTextures() { + return faceTextures; + } + + @Override + public int[] getFaceColors1() { + return faceColors1; + } + + @Override + public int[] getFaceColors2() { + return faceColors2; + } + + @Override + public int[] getFaceColors3() { + return faceColors3; + } + + @Override + public short[] getUnlitFaceColors() { + return unlitFaceColors; + } + + @Override + public int getSceneId() { + return sceneId; + } + + @Override + public void setSceneId(int sceneId) { + this.sceneId = sceneId; + } + + @Override + public int getBufferOffset() { + return bufferOffset; + } + + @Override + public void setBufferOffset(int bufferOffset) { + this.bufferOffset = bufferOffset; + } + + @Override + public int getUvBufferOffset() { + return uvBufferOffset; + } + + @Override + public void setUvBufferOffset(int bufferOffset) { + uvBufferOffset = bufferOffset; + } + + @Override + public int getBottomY() { + calculateBoundsCylinder(); + return bottomY; + } + + @Override + public void calculateBoundsCylinder() { + if (boundsCalculated) + return; + boundsCalculated = true; + + modelHeight = 0; + bottomY = 0; + int magnitude = 0; + + for (int i = 0; i < verticesCount; i++) { + int x = (int) verticesX[i]; + int y = (int) verticesY[i]; + int z = (int) verticesZ[i]; + + if (-y > modelHeight) + modelHeight = -y; + if (y > bottomY) + bottomY = y; + + int squared = x * x + z * z; + if (squared > magnitude) + magnitude = squared; + } + + xyzMag = (int) (Math.sqrt(magnitude) + 0.99); + radius = (int) (Math.sqrt((double) xyzMag * xyzMag + (double) modelHeight * modelHeight) + 0.99); + diameter = radius + (int) (Math.sqrt((double) xyzMag * xyzMag + (double) bottomY * bottomY) + 0.99); + } + + @Override + public byte getTransparency() { + return transparency; + } + + @Override + public byte[] getFaceRenderPriorities() { + return faceRenderPriorities; + } + + @Override + public byte[] getFaceBias() { + return faceBias; + } + + @Override + public int getRadius() { + calculateBoundsCylinder(); + return radius; + } + + @Override + public int getDiameter() { + calculateBoundsCylinder(); + return diameter; + } + + @Override + public int getXYZMag() { + calculateBoundsCylinder(); + return xyzMag; + } + + @Override + @Deprecated + public void calculateExtreme(int orientation) {} + + @Nonnull + @Override + public AABB getAABB(int orientation) { + calculateBoundsCylinder(); + return new ModelAABB(xyzMag, modelHeight, bottomY); + } + + @Override + public boolean useBoundingBox() { + return false; + } + + @Override + public int[] getVertexNormalsX() { + return vertexNormalsX; + } + + @Override + public int[] getVertexNormalsY() { + return vertexNormalsY; + } + + @Override + public int[] getVertexNormalsZ() { + return vertexNormalsZ; + } + + @Override + public byte getOverrideAmount() { + return 0; + } + + @Override + public byte getOverrideHue() { + return 0; + } + + @Override + public byte getOverrideSaturation() { + return 0; + } + + @Override + public byte getOverrideLuminance() { + return 0; + } + + @Override + public byte[] getTextureFaces() { + return textureFaces; + } + + @Override + public int[] getTexIndices1() { + return texIndices1; + } + + @Override + public int[] getTexIndices2() { + return texIndices2; + } + + @Override + public int[] getTexIndices3() { + return texIndices3; + } + + @Override + public Model getUnskewedModel() { + return this; + } + + @Override + public void drawFrustum(int zero, int xRotate, int yRotate, int zRotate, int xCamera, int yCamera, int zCamera) { + } + + @Override + public void drawOrtho(int zero, int xRotate, int yRotate, int zRotate, int xCamera, int yCamera, int zCamera, int zoom) {} + + + @Override + public Model getModel() { + return this; + } + + @Override + public int getModelHeight() { + calculateBoundsCylinder(); + return modelHeight; + } + + @Override + public void setModelHeight(int modelHeight) { + this.modelHeight = modelHeight; + } + + @Override + public int getAnimationHeightOffset() { + return 0; + } + + @Override + public int getRenderMode() { + return RENDERMODE_DEFAULT; + } + + + @Override + public Node getNext() { + return null; + } + + @Override + public Node getPrevious() { + return null; + } + + @Override + public long getHash() { + return 0; + } + + + @Override + public Model rotateY90Ccw() { + throw new UnsupportedOperationException("A cache scene model is already built"); + } + + @Override + public Model rotateY180Ccw() { + throw new UnsupportedOperationException("A cache scene model is already built"); + } + + @Override + public Model rotateY270Ccw() { + throw new UnsupportedOperationException("A cache scene model is already built"); + } + + @Override + public Model translate(int x, int y, int z) { + throw new UnsupportedOperationException("A cache scene model is already built"); + } + + @Override + public Model scale(int x, int y, int z) { + throw new UnsupportedOperationException("A cache scene model is already built"); + } + + private static final class ModelAABB implements AABB { + private final int extremeX, extremeY, extremeZ; + private final int centerY; + + ModelAABB(int xyzMag, int modelHeight, int bottomY) { + extremeX = extremeZ = xyzMag; + extremeY = modelHeight + bottomY >> 1; + centerY = bottomY - extremeY; + } + + @Override + public int getCenterX() { + return 0; + } + + @Override + public int getCenterY() { + return centerY; + } + + @Override + public int getCenterZ() { + return 0; + } + + @Override + public int getExtremeX() { + return extremeX; + } + + @Override + public int getExtremeY() { + return extremeY; + } + + @Override + public int getExtremeZ() { + return extremeZ; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltScene.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltScene.java new file mode 100644 index 0000000..4722de3 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltScene.java @@ -0,0 +1,359 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.util.ArrayDeque; +import net.runelite.api.GameObject; +import net.runelite.api.Model; +import net.runelite.api.Node; +import net.runelite.api.Scene; +import javax.annotation.Nullable; +import net.runelite.api.Tile; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; +import static net.runelite.api.Constants.MAX_Z; +import static net.runelite.api.Constants.SCENE_SIZE; + +public class BuiltScene implements Scene { + public static final int SCENE_OFFSET = (EXTENDED_SCENE_SIZE - SCENE_SIZE) / 2; + + private final int baseX, baseY; + private final int worldViewId; + + private final BuiltTile[][][] extendedTiles = new BuiltTile[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + private final Tile[][][] tiles = new Tile[MAX_Z][SCENE_SIZE][SCENE_SIZE]; + + private final int[][][] tileHeights = new int[MAX_Z][EXTENDED_SCENE_SIZE + 1][EXTENDED_SCENE_SIZE + 1]; + private final byte[][][] extendedTileSettings = new byte[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + private final short[][][] underlayIds = new short[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + private final short[][][] overlayIds = new short[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + private final byte[][][] tileShapes = new byte[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + private final int[][][] roofs = new int[MAX_Z][EXTENDED_SCENE_SIZE][EXTENDED_SCENE_SIZE]; + + private final int[] mapRegions; + + private int drawDistance = 25; + private int minLevel; + private int roofRemovalMode; + + private int modelHeight; + + public BuiltScene(int baseX, int baseY, int worldViewId, int[] mapRegions) { + this.baseX = baseX; + this.baseY = baseY; + this.worldViewId = worldViewId; + this.mapRegions = mapRegions; + } + + public int getSceneOffset() { + return SCENE_OFFSET; + } + + public BuiltTile tile(int plane, int extendedX, int extendedY) { + BuiltTile tile = extendedTiles[plane][extendedX][extendedY]; + if (tile == null) { + tile = new BuiltTile(this, plane, extendedX, extendedY); + setTile(plane, extendedX, extendedY, tile); + } + return tile; + } + + public BuiltTile tileOrNull(int plane, int extendedX, int extendedY) { + return extendedTiles[plane][extendedX][extendedY]; + } + + public void setTile(int plane, int extendedX, int extendedY, BuiltTile tile) { + extendedTiles[plane][extendedX][extendedY] = tile; + + int sceneX = extendedX - SCENE_OFFSET; + int sceneY = extendedY - SCENE_OFFSET; + if (sceneX >= 0 && sceneX < SCENE_SIZE && sceneY >= 0 && sceneY < SCENE_SIZE) + tiles[plane][sceneX][sceneY] = tile; + } + + @Override + public Tile[][][] getTiles() { + return tiles; + } + + @Override + public Tile[][][] getExtendedTiles() { + return extendedTiles; + } + + @Override + public byte[][][] getExtendedTileSettings() { + return extendedTileSettings; + } + + @Override + public int getDrawDistance() { + return drawDistance; + } + + @Override + public void setDrawDistance(int drawDistance) { + this.drawDistance = drawDistance; + } + + @Override + public int getWorldViewId() { + return worldViewId; + } + + @Override + public int getMinLevel() { + return minLevel; + } + + @Override + public void setMinLevel(int minLevel) { + this.minLevel = minLevel; + } + + @Override + public void removeTile(Tile tile) { + if (!(tile instanceof BuiltTile)) + return; + BuiltTile cacheTile = (BuiltTile) tile; + setTile(cacheTile.getPlane(), cacheTile.getExtendedX(), cacheTile.getExtendedY(), null); + } + + @Override + public void removeGameObject(GameObject gameObject) { + for (int plane = 0; plane < MAX_Z; plane++) { + for (int x = 0; x < EXTENDED_SCENE_SIZE; x++) { + for (int y = 0; y < EXTENDED_SCENE_SIZE; y++) { + BuiltTile tile = extendedTiles[plane][x][y]; + if (tile == null) + continue; + GameObject[] objects = tile.getGameObjects(); + for (int i = 0; i < objects.length; i++) + if (objects[i] == gameObject) + objects[i] = null; + } + } + } + } + + private boolean isRoofed(int plane, int x, int y) { + return (extendedTileSettings[plane][x][y] & 4) != 0; + } + + @Override + public void buildRoofs() { + for (int plane = 0; plane < MAX_Z; plane++) + for (int x = 0; x < EXTENDED_SCENE_SIZE; x++) + java.util.Arrays.fill(roofs[plane][x], 0); + + int nextRoofId = 1; + for (int plane = MAX_Z - 1; plane >= 0; plane--) { + for (int y = 0; y < EXTENDED_SCENE_SIZE; y++) { + for (int x = 0; x < EXTENDED_SCENE_SIZE; x++) { + if (extendedTiles[plane][x][y] == null || roofs[plane][x][y] != 0 || !isRoofed(plane, x, y)) + continue; + floodRoof(plane, x, y, nextRoofId++); + } + } + } + } + + private void floodRoof(int startPlane, int startX, int startY, int roofId) { + var queue = new ArrayDeque(); + queue.add(new int[] { startPlane, startX, startY }); + + while (!queue.isEmpty()) { + int[] at = queue.poll(); + int plane = at[0], x = at[1], y = at[2]; + if (roofs[plane][x][y] != 0) + continue; + + if (isRoofed(plane, x, y)) { + for (int dx = -1; dx <= 1; dx++) { + for (int dy = -1; dy <= 1; dy++) { + if (dx == 0 && dy == 0) + continue; + int nx = x + dx; + int ny = y + dy; + if (nx < 0 || ny < 0 || nx >= EXTENDED_SCENE_SIZE || ny >= EXTENDED_SCENE_SIZE) + continue; + if (extendedTiles[plane][nx][ny] != null) + queue.add(new int[] { plane, nx, ny }); + } + } + } + + roofs[plane][x][y] = roofId; + + for (int above = plane + 1, distance = 1; above < MAX_Z; above++, distance++) { + if (roofs[above][x][y] != 0) + break; + roofs[above][x][y] = roofId | distance << 28; + } + } + } + + private final java.util.List dynamics = new java.util.ArrayList<>(); + + public static final class Dynamic { + public final net.runelite.api.TileObject tileObject; + public final BuiltDynamicObject renderable; + public final int orientation; + public final int x, y, z; + + public Dynamic( + net.runelite.api.TileObject tileObject, BuiltDynamicObject renderable, + int orientation, int x, int y, int z + ) { + this.tileObject = tileObject; + this.renderable = renderable; + this.orientation = orientation; + this.x = x; + this.y = y; + this.z = z; + } + } + + public void addDynamic(Dynamic dynamic) { + dynamics.add(dynamic); + } + + public java.util.List getDynamics() { + return dynamics; + } + + @Override + public int[][][] getRoofs() { + return roofs; + } + + @Override + public void setRoofRemovalMode(int flags) { + roofRemovalMode = flags; + } + + @Override + public int getRoofRemovalMode() { + return roofRemovalMode; + } + + @Override + public short[][][] getUnderlayIds() { + return underlayIds; + } + + @Override + public short[][][] getOverlayIds() { + return overlayIds; + } + + @Override + public byte[][][] getTileShapes() { + return tileShapes; + } + + @Override + public int[][][] getTileHeights() { + return tileHeights; + } + + @Override + public int getBaseX() { + return baseX; + } + + @Override + public int getBaseY() { + return baseY; + } + + public static final int CHUNKS_PER_SIDE = EXTENDED_SCENE_SIZE / 8; + + @Nullable + private int[][][] instanceTemplateChunks; + + public void setInstanceTemplateChunks(int[][][] instanceTemplateChunks) { + this.instanceTemplateChunks = instanceTemplateChunks; + } + + @Override + public boolean isInstance() { + return instanceTemplateChunks != null; + } + + @Nullable + @Override + public int[][][] getInstanceTemplateChunks() { + return instanceTemplateChunks; + } + + @Override + public int[] getMapRegions() { + return mapRegions; + } + + @Override + public byte getOverrideAmount() { + return 0; + } + + @Override + public byte getOverrideHue() { + return 0; + } + + @Override + public byte getOverrideSaturation() { + return 0; + } + + @Override + public byte getOverrideLuminance() { + return 0; + } + + @Override + public Model getSkybox() { + return null; + } + + + @Override + public Model getModel() { + return null; + } + + @Override + public int getModelHeight() { + return modelHeight; + } + + @Override + public void setModelHeight(int modelHeight) { + this.modelHeight = modelHeight; + } + + @Override + public int getAnimationHeightOffset() { + return 0; + } + + @Override + public int getRenderMode() { + return RENDERMODE_DEFAULT; + } + + + @Override + public Node getNext() { + return null; + } + + @Override + public Node getPrevious() { + return null; + } + + @Override + public long getHash() { + return 0; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTile.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTile.java new file mode 100644 index 0000000..9ddbf3f --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTile.java @@ -0,0 +1,186 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.util.Collections; +import java.util.List; +import javax.annotation.Nullable; +import net.runelite.api.DecorativeObject; +import net.runelite.api.GameObject; +import net.runelite.api.GroundObject; +import net.runelite.api.ItemLayer; +import net.runelite.api.Point; +import net.runelite.api.SceneTileModel; +import net.runelite.api.SceneTilePaint; +import net.runelite.api.Tile; +import net.runelite.api.TileItem; +import net.runelite.api.WallObject; +import net.runelite.api.coords.LocalPoint; +import net.runelite.api.coords.WorldPoint; + +import static net.runelite.api.Perspective.LOCAL_TILE_SIZE; + +public class BuiltTile implements Tile { + public static final int MAX_GAME_OBJECTS = 5; + + private final BuiltScene scene; + private final int extendedX, extendedY; + private int plane; + private boolean onBridge; + + private SceneTilePaint paint; + private SceneTileModel model; + + private final GameObject[] gameObjects = new GameObject[MAX_GAME_OBJECTS]; + private WallObject wallObject; + private DecorativeObject decorativeObject; + private GroundObject groundObject; + + @Nullable + private BuiltTile bridge; + + public BuiltTile(BuiltScene scene, int plane, int extendedX, int extendedY) { + this.scene = scene; + this.plane = plane; + this.extendedX = extendedX; + this.extendedY = extendedY; + } + + public int getExtendedX() { + return extendedX; + } + + public int getExtendedY() { + return extendedY; + } + + public int getSceneX() { + return extendedX - scene.getSceneOffset(); + } + + public int getSceneY() { + return extendedY - scene.getSceneOffset(); + } + + @Override + public DecorativeObject getDecorativeObject() { + return decorativeObject; + } + + public void setDecorativeObject(DecorativeObject decorativeObject) { + this.decorativeObject = decorativeObject; + } + + @Override + public GameObject[] getGameObjects() { + return gameObjects; + } + + public int gameObjectCount() { + int count = 0; + for (GameObject object : gameObjects) + if (object != null) + count++; + return count; + } + + public boolean addGameObject(GameObject gameObject) { + for (int i = 0; i < gameObjects.length; i++) { + if (gameObjects[i] == null) { + gameObjects[i] = gameObject; + return true; + } + } + return false; + } + + @Override + public ItemLayer getItemLayer() { + return null; + } + + @Override + public GroundObject getGroundObject() { + return groundObject; + } + + @Override + public void setGroundObject(GroundObject groundObject) { + this.groundObject = groundObject; + } + + @Override + public WallObject getWallObject() { + return wallObject; + } + + public void setWallObject(WallObject wallObject) { + this.wallObject = wallObject; + } + + @Override + public SceneTilePaint getSceneTilePaint() { + return paint; + } + + @Override + public void setSceneTilePaint(SceneTilePaint paint) { + this.paint = paint; + } + + @Override + public SceneTileModel getSceneTileModel() { + return model; + } + + @Override + public void setSceneTileModel(SceneTileModel model) { + this.model = model; + } + + @Override + public WorldPoint getWorldLocation() { + return new WorldPoint(scene.getBaseX() + getSceneX(), scene.getBaseY() + getSceneY(), plane); + } + + @Override + public Point getSceneLocation() { + return new Point(getSceneX(), getSceneY()); + } + + @Override + public LocalPoint getLocalLocation() { + int half = LOCAL_TILE_SIZE / 2; + return new LocalPoint(getSceneX() * LOCAL_TILE_SIZE + half, getSceneY() * LOCAL_TILE_SIZE + half); + } + + @Override + public int getPlane() { + return plane; + } + + public void setPlane(int plane) { + this.plane = plane; + } + + @Override + public int getRenderLevel() { + return plane + (onBridge ? 1 : 0) & 3; + } + + public void setOnBridge(boolean onBridge) { + this.onBridge = onBridge; + } + + @Override + public List getGroundItems() { + return Collections.emptyList(); + } + + @Override + public Tile getBridge() { + return bridge; + } + + public void setBridge(@Nullable BuiltTile bridge) { + this.bridge = bridge; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileModel.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileModel.java new file mode 100644 index 0000000..8ccf4e1 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileModel.java @@ -0,0 +1,370 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.SceneTileModel; + +public class BuiltTileModel implements SceneTileModel { + private static final int[][] SHAPE_VERTICES = { + { 1, 3, 5, 7 }, + { 1, 3, 5, 7 }, + { 1, 3, 5, 7 }, + { 1, 3, 5, 7, 6 }, + { 1, 3, 5, 7, 6 }, + { 1, 3, 5, 7, 6 }, + { 1, 3, 5, 7, 6 }, + { 1, 3, 5, 7, 2, 6 }, + { 1, 3, 5, 7, 2, 8 }, + { 1, 3, 5, 7, 2, 8 }, + { 1, 3, 5, 7, 11, 12 }, + { 1, 3, 5, 7, 11, 12 }, + { 1, 3, 5, 7, 13, 14 } + }; + + private static final int[][] SHAPE_FACES = { + { 0, 1, 2, 3, 0, 0, 1, 3 }, + { 1, 1, 2, 3, 1, 0, 1, 3 }, + { 0, 1, 2, 3, 1, 0, 1, 3 }, + { 0, 0, 1, 2, 0, 0, 2, 4, 1, 0, 4, 3 }, + { 0, 0, 1, 4, 0, 0, 4, 3, 1, 1, 2, 4 }, + { 0, 0, 4, 3, 1, 0, 1, 2, 1, 0, 2, 4 }, + { 0, 1, 2, 4, 1, 0, 1, 4, 1, 0, 4, 3 }, + { 0, 4, 1, 2, 0, 4, 2, 5, 1, 0, 4, 5, 1, 0, 5, 3 }, + { 0, 4, 1, 2, 0, 4, 2, 3, 0, 4, 3, 5, 1, 0, 4, 5 }, + { 0, 0, 4, 5, 1, 4, 1, 2, 1, 4, 2, 3, 1, 4, 3, 5 }, + { 0, 0, 1, 5, 0, 1, 4, 5, 0, 1, 2, 4, 1, 0, 5, 3, 1, 5, 4, 3, 1, 4, 2, 3 }, + { 1, 0, 1, 5, 1, 1, 4, 5, 1, 1, 2, 4, 0, 0, 5, 3, 0, 5, 4, 3, 0, 4, 2, 3 }, + { 1, 0, 5, 4, 1, 0, 1, 5, 0, 0, 4, 3, 0, 4, 5, 3, 0, 5, 2, 3, 0, 1, 2, 5 } + }; + + private static final int UNIT = 128; + private static final int HALF = UNIT / 2; + private static final int QUARTER = UNIT / 4; + private static final int THREE_QUARTER = UNIT * 3 / 4; + + private final int shape; + private final int rotation; + private final int modelUnderlay; + private final int modelOverlay; + private final boolean flat; + + private final int[] vertexX; + private final int[] vertexY; + private final int[] vertexZ; + + private final int[] faceA; + private final int[] faceB; + private final int[] faceC; + + private final int[] triangleColorA; + private final int[] triangleColorB; + private final int[] triangleColorC; + private final int[] triangleTextureId; + + private int bufferOffset, uvBufferOffset, bufferLen; + + public BuiltTileModel( + int shape, int rotation, int texture, int tileX, int tileZ, + int swY, int seY, int neY, int nwY, + int swU, int seU, int neU, int nwU, + int swO, int seO, int neO, int nwO, + int modelUnderlay, int modelOverlay + ) { + this.shape = shape; + this.rotation = rotation; + this.modelUnderlay = modelUnderlay; + this.modelOverlay = modelOverlay; + this.flat = swY == seY && swY == neY && swY == nwY; + + int[] vertices = SHAPE_VERTICES[shape]; + int vertexCount = vertices.length; + vertexX = new int[vertexCount]; + vertexY = new int[vertexCount]; + vertexZ = new int[vertexCount]; + + int[] underlayColors = new int[vertexCount]; + int[] overlayColors = new int[vertexCount]; + + int baseX = tileX * UNIT; + int baseZ = tileZ * UNIT; + + for (int i = 0; i < vertexCount; i++) { + int vertex = vertices[i]; + if ((vertex & 1) == 0 && vertex <= 8) + vertex = (vertex - rotation - rotation - 1 & 7) + 1; + if (vertex > 8 && vertex <= 12) + vertex = (vertex - 9 - rotation & 3) + 9; + if (vertex > 12 && vertex <= 16) + vertex = (vertex - 13 - rotation & 3) + 13; + + int x, z, y, underlay, overlay; + switch (vertex) { + case 1: + x = baseX; + z = baseZ; + y = swY; + underlay = swU; + overlay = swO; + break; + case 2: + x = baseX + HALF; + z = baseZ; + y = swY + seY >> 1; + underlay = swU + seU >> 1; + overlay = swO + seO >> 1; + break; + case 3: + x = baseX + UNIT; + z = baseZ; + y = seY; + underlay = seU; + overlay = seO; + break; + case 4: + x = baseX + UNIT; + z = baseZ + HALF; + y = seY + neY >> 1; + underlay = seU + neU >> 1; + overlay = seO + neO >> 1; + break; + case 5: + x = baseX + UNIT; + z = baseZ + UNIT; + y = neY; + underlay = neU; + overlay = neO; + break; + case 6: + x = baseX + HALF; + z = baseZ + UNIT; + y = neY + nwY >> 1; + underlay = neU + nwU >> 1; + overlay = neO + nwO >> 1; + break; + case 7: + x = baseX; + z = baseZ + UNIT; + y = nwY; + underlay = nwU; + overlay = nwO; + break; + case 8: + x = baseX; + z = baseZ + HALF; + y = swY + nwY >> 1; + underlay = swU + nwU >> 1; + overlay = swO + nwO >> 1; + break; + case 9: + x = baseX + HALF; + z = baseZ + QUARTER; + y = swY + seY >> 1; + underlay = swU + seU >> 1; + overlay = swO + seO >> 1; + break; + case 10: + x = baseX + THREE_QUARTER; + z = baseZ + HALF; + y = seY + neY >> 1; + underlay = seU + neU >> 1; + overlay = seO + neO >> 1; + break; + case 11: + x = baseX + HALF; + z = baseZ + THREE_QUARTER; + y = neY + nwY >> 1; + underlay = neU + nwU >> 1; + overlay = neO + nwO >> 1; + break; + case 12: + x = baseX + QUARTER; + z = baseZ + HALF; + y = swY + nwY >> 1; + underlay = swU + nwU >> 1; + overlay = swO + nwO >> 1; + break; + case 13: + x = baseX + QUARTER; + z = baseZ + QUARTER; + y = swY; + underlay = swU; + overlay = swO; + break; + case 14: + x = baseX + THREE_QUARTER; + z = baseZ + QUARTER; + y = seY; + underlay = seU; + overlay = seO; + break; + case 15: + x = baseX + THREE_QUARTER; + z = baseZ + THREE_QUARTER; + y = neY; + underlay = neU; + overlay = neO; + break; + default: + x = baseX + QUARTER; + z = baseZ + THREE_QUARTER; + y = nwY; + underlay = nwU; + overlay = nwO; + break; + } + + vertexX[i] = x; + vertexY[i] = y; + vertexZ[i] = z; + underlayColors[i] = underlay; + overlayColors[i] = overlay; + } + + int[] faces = SHAPE_FACES[shape]; + int faceCount = faces.length / 4; + faceA = new int[faceCount]; + faceB = new int[faceCount]; + faceC = new int[faceCount]; + triangleColorA = new int[faceCount]; + triangleColorB = new int[faceCount]; + triangleColorC = new int[faceCount]; + triangleTextureId = texture != -1 ? new int[faceCount] : null; + + int f = 0; + for (int i = 0; i < faceCount; i++) { + int isOverlay = faces[f]; + int a = faces[f + 1]; + int b = faces[f + 2]; + int c = faces[f + 3]; + f += 4; + + if (a < 4) + a = a - rotation & 3; + if (b < 4) + b = b - rotation & 3; + if (c < 4) + c = c - rotation & 3; + + faceA[i] = a; + faceB[i] = b; + faceC[i] = c; + + if (isOverlay == 0) { + triangleColorA[i] = underlayColors[a]; + triangleColorB[i] = underlayColors[b]; + triangleColorC[i] = underlayColors[c]; + if (triangleTextureId != null) + triangleTextureId[i] = -1; + } else { + triangleColorA[i] = overlayColors[a]; + triangleColorB[i] = overlayColors[b]; + triangleColorC[i] = overlayColors[c]; + if (triangleTextureId != null) + triangleTextureId[i] = texture; + } + } + } + + @Override + public int getModelUnderlay() { + return modelUnderlay; + } + + @Override + public int getModelOverlay() { + return modelOverlay; + } + + @Override + public int getShape() { + return shape; + } + + @Override + public int getRotation() { + return rotation; + } + + @Override + public int[] getFaceX() { + return faceA; + } + + @Override + public int[] getFaceY() { + return faceB; + } + + @Override + public int[] getFaceZ() { + return faceC; + } + + @Override + public int[] getVertexX() { + return vertexX; + } + + @Override + public int[] getVertexY() { + return vertexY; + } + + @Override + public int[] getVertexZ() { + return vertexZ; + } + + @Override + public int[] getTriangleColorA() { + return triangleColorA; + } + + @Override + public int[] getTriangleColorB() { + return triangleColorB; + } + + @Override + public int[] getTriangleColorC() { + return triangleColorC; + } + + @Override + public int[] getTriangleTextureId() { + return triangleTextureId; + } + + @Override + public boolean isFlat() { + return flat; + } + + @Override + public int getBufferOffset() { + return bufferOffset; + } + + @Override + public void setBufferOffset(int bufferOffset) { + this.bufferOffset = bufferOffset; + } + + @Override + public int getUvBufferOffset() { + return uvBufferOffset; + } + + @Override + public void setUvBufferOffset(int bufferOffset) { + uvBufferOffset = bufferOffset; + } + + @Override + public int getBufferLen() { + return bufferLen; + } + + @Override + public void setBufferLen(int bufferLen) { + this.bufferLen = bufferLen; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileObject.java new file mode 100644 index 0000000..d9e9365 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTileObject.java @@ -0,0 +1,158 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.awt.Graphics2D; +import java.awt.Polygon; +import java.awt.Shape; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import net.runelite.api.Point; +import net.runelite.api.TileObject; +import net.runelite.api.WorldView; +import net.runelite.api.coords.LocalPoint; +import net.runelite.api.coords.WorldPoint; + +public abstract class BuiltTileObject implements TileObject { + public static final int HASH_ID_SHIFT = 20; + + protected final BuiltScene scene; + protected final long hash; + protected final int config; + protected final int x, y, z; + protected int plane; + + protected BuiltTileObject(BuiltScene scene, long hash, int config, int x, int y, int z, int plane) { + this.scene = scene; + this.hash = hash; + this.config = config; + this.x = x; + this.y = y; + this.z = z; + this.plane = plane; + } + + public int getConfig() { + return config; + } + + public int getType() { + return config & 0x3F; + } + + public int getRotation() { + return config >> 6 & 3; + } + + @Override + public long getHash() { + return hash; + } + + @Override + public int getId() { + return (int) (hash >>> HASH_ID_SHIFT & 0xFFFFFFFFL); + } + + @Override + public int getX() { + return x; + } + + @Override + public int getY() { + return y; + } + + @Override + public int getZ() { + return z; + } + + @Override + public int getPlane() { + return plane; + } + + public void setPlane(int plane) { + this.plane = plane; + } + + @Override + public WorldView getWorldView() { + return null; + } + + @Nonnull + @Override + public WorldPoint getWorldLocation() { + var local = getLocalLocation(); + return new WorldPoint( + scene.getBaseX() + local.getSceneX(), + scene.getBaseY() + local.getSceneY(), + plane + ); + } + + @Nonnull + @Override + public LocalPoint getLocalLocation() { + return new LocalPoint(x, y); + } + + + @Nullable + @Override + public Point getCanvasLocation() { + return null; + } + + @Nullable + @Override + public Point getCanvasLocation(int zOffset) { + return null; + } + + @Nullable + @Override + public Polygon getCanvasTilePoly() { + return null; + } + + @Nullable + @Override + public Point getCanvasTextLocation(Graphics2D graphics, String text, int zOffset) { + return null; + } + + @Nullable + @Override + public Point getMinimapLocation() { + return null; + } + + @Nullable + @Override + public Shape getClickbox() { + return null; + } + + @Nullable + @Override + public String getOpOverride(int index) { + return null; + } + + @Override + public boolean isOpShown(int index) { + return false; + } + + @Nullable + public Shape getConvexHull() { + return null; + } + + @Nullable + public Shape getConvexHull2() { + return null; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTilePaint.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTilePaint.java new file mode 100644 index 0000000..a1c6fdb --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltTilePaint.java @@ -0,0 +1,112 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.SceneTilePaint; + +public class BuiltTilePaint implements SceneTilePaint { + private final int rgb; + private int swColor, seColor, neColor, nwColor; + private int texture; + private final boolean flat; + + private int bufferOffset, uvBufferOffset, bufferLen; + + public BuiltTilePaint(int swColor, int seColor, int neColor, int nwColor, int texture, int rgb, boolean flat) { + this.swColor = swColor; + this.seColor = seColor; + this.neColor = neColor; + this.nwColor = nwColor; + this.texture = texture; + this.rgb = rgb; + this.flat = flat; + } + + @Override + public int getRBG() { + return rgb; + } + + @Override + public int getSwColor() { + return swColor; + } + + @Override + public void setSwColor(int color) { + swColor = color; + } + + @Override + public int getSeColor() { + return seColor; + } + + @Override + public void setSeColor(int color) { + seColor = color; + } + + @Override + public int getNwColor() { + return nwColor; + } + + @Override + public void setNwColor(int color) { + nwColor = color; + } + + @Override + public int getNeColor() { + return neColor; + } + + @Override + public void setNeColor(int color) { + neColor = color; + } + + @Override + public int getTexture() { + return texture; + } + + @Override + public void setTexture(int texture) { + this.texture = texture; + } + + @Override + public boolean isFlat() { + return flat; + } + + @Override + public int getBufferOffset() { + return bufferOffset; + } + + @Override + public void setBufferOffset(int bufferOffset) { + this.bufferOffset = bufferOffset; + } + + @Override + public int getUvBufferOffset() { + return uvBufferOffset; + } + + @Override + public void setUvBufferOffset(int bufferOffset) { + uvBufferOffset = bufferOffset; + } + + @Override + public int getBufferLen() { + return bufferLen; + } + + @Override + public void setBufferLen(int bufferLen) { + this.bufferLen = bufferLen; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltWallObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltWallObject.java new file mode 100644 index 0000000..1c491fb --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/BuiltWallObject.java @@ -0,0 +1,48 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.api.Renderable; +import net.runelite.api.WallObject; + +public class BuiltWallObject extends BuiltTileObject implements WallObject { + private Renderable renderable1, renderable2; + private final int orientationA, orientationB; + + public BuiltWallObject( + BuiltScene scene, long hash, int config, int x, int y, int z, int plane, + Renderable renderable1, Renderable renderable2, int orientationA, int orientationB + ) { + super(scene, hash, config, x, y, z, plane); + this.renderable1 = renderable1; + this.renderable2 = renderable2; + this.orientationA = orientationA; + this.orientationB = orientationB; + } + + @Override + public int getOrientationA() { + return orientationA; + } + + @Override + public int getOrientationB() { + return orientationB; + } + + @Override + public Renderable getRenderable1() { + return renderable1; + } + + @Override + public Renderable getRenderable2() { + return renderable2; + } + + public void setRenderable1(Renderable renderable) { + renderable1 = renderable; + } + + public void setRenderable2(Renderable renderable) { + renderable2 = renderable; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/Definitions.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/Definitions.java new file mode 100644 index 0000000..569a90f --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/Definitions.java @@ -0,0 +1,302 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.io.Closeable; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; +import lombok.extern.slf4j.Slf4j; +import net.runelite.cache.IndexType; +import net.runelite.cache.ObjectManager; +import net.runelite.cache.OverlayManager; +import net.runelite.cache.TextureManager; +import net.runelite.cache.UnderlayManager; +import net.runelite.cache.definitions.LocationsDefinition; +import net.runelite.cache.definitions.MapDefinition; +import net.runelite.cache.definitions.ObjectDefinition; +import net.runelite.cache.definitions.OverlayDefinition; +import net.runelite.cache.definitions.TextureDefinition; +import net.runelite.cache.definitions.UnderlayDefinition; +import net.runelite.cache.ConfigType; +import net.runelite.cache.definitions.FrameDefinition; +import net.runelite.cache.definitions.FramemapDefinition; +import net.runelite.cache.definitions.ModelDefinition; +import net.runelite.cache.definitions.SequenceDefinition; +import net.runelite.cache.definitions.loaders.FrameLoader; +import net.runelite.cache.definitions.loaders.FramemapLoader; +import net.runelite.cache.definitions.loaders.LocationsLoader; +import net.runelite.cache.definitions.loaders.MapLoader; +import net.runelite.cache.definitions.loaders.ModelLoader; +import net.runelite.cache.definitions.loaders.SequenceLoader; +import net.runelite.cache.fs.Archive; +import net.runelite.cache.fs.ArchiveFiles; +import net.runelite.cache.fs.Index; +import net.runelite.cache.fs.Storage; +import net.runelite.cache.fs.Store; +import net.runelite.cache.region.Region; + +@Slf4j +public class Definitions implements Closeable { + private final Store store; + private final Index maps; + private final boolean mapsAreNamed; + private final Index models; + private final Index frameArchives; + private final Index framemapArchives; + + private final Map modelData = new HashMap<>(); + + private final Map sequences = new HashMap<>(); + private final Map frameFiles = new HashMap<>(); + private final Map framemaps = new HashMap<>(); + private final Map frames = new HashMap<>(); + + private final UnderlayManager underlays; + private final OverlayManager overlays; + private final ObjectManager objects; + private final TextureManager textures; + + private final Map regions = new HashMap<>(); + + public Definitions(Path cacheDirectory) throws IOException { + store = new Store(cacheDirectory.toFile()); + store.load(); + + maps = store.getIndex(IndexType.MAPS); + mapsAreNamed = maps.findArchiveByName("m50_50") != null; + models = store.getIndex(IndexType.MODELS); + frameArchives = store.getIndex(IndexType.ANIMATIONS); + framemapArchives = store.getIndex(IndexType.SKELETONS); + + underlays = new UnderlayManager(store); + underlays.load(); + overlays = new OverlayManager(store); + overlays.load(); + objects = new ObjectManager(store); + objects.load(); + textures = new TextureManager(store); + textures.load(); + + loadSequences(); + } + + private void loadSequences() throws IOException { + Archive archive = store.getIndex(IndexType.CONFIGS).getArchive(ConfigType.SEQUENCE.getId()); + if (archive == null) + return; + + ArchiveFiles files = archive.getFiles(store.getStorage().loadArchive(archive)); + SequenceLoader loader = new SequenceLoader().configureForRevision(archive.getRevision()); + for (var file : files.getFiles()) { + try { + sequences.put(file.getFileId(), loader.load(file.getFileId(), file.getContents())); + } catch (Exception ex) { + log.debug("Ignoring animation {}, which would not decode", file.getFileId(), ex); + } + } + } + + @Nullable + public SequenceDefinition sequence(int id) { + return sequences.get(id); + } + + @Nullable + public FrameDefinition frame(int packedFrameId) { + FrameDefinition cached = frames.get(packedFrameId); + if (cached != null || frames.containsKey(packedFrameId)) + return cached; + + FrameDefinition frame = null; + try { + frame = loadFrame(packedFrameId); + } catch (Exception ex) { + log.debug("Ignoring frame {}, which would not decode", packedFrameId, ex); + } + frames.put(packedFrameId, frame); + return frame; + } + + @Nullable + private FrameDefinition loadFrame(int packedFrameId) throws IOException { + int archiveId = packedFrameId >> 16; + int fileId = packedFrameId & 0xFFFF; + + ArchiveFiles files = frameFiles.get(archiveId); + if (files == null) { + if (frameFiles.containsKey(archiveId)) + return null; + + Archive archive = frameArchives.getArchive(archiveId); + files = archive == null + ? null + : archive.getFiles(store.getStorage().loadArchive(archive)); + frameFiles.put(archiveId, files); + if (files == null) + return null; + } + + var file = files.findFile(fileId); + if (file == null) + return null; + + byte[] data = file.getContents(); + if (data == null || data.length < 2) + return null; + + int framemapId = ((data[0] & 0xFF) << 8) | (data[1] & 0xFF); + FramemapDefinition framemap = framemap(framemapId); + if (framemap == null) + return null; + + FrameDefinition frame = new FrameLoader().load(framemap, fileId, data); + if (frame != null) { + frame.id = packedFrameId; + } + return frame; + } + + @Nullable + private FramemapDefinition framemap(int id) throws IOException { + FramemapDefinition cached = framemaps.get(id); + if (cached != null || framemaps.containsKey(id)) + return cached; + + FramemapDefinition framemap = null; + Archive archive = framemapArchives.getArchive(id); + if (archive != null) { + byte[] data = archive.decompress(store.getStorage().loadArchive(archive)); + if (data != null) + framemap = new FramemapLoader().load(id, data); + } + framemaps.put(id, framemap); + return framemap; + } + + public static Path findDefaultCache() throws IOException { + Path home = Paths.get(System.getProperty("user.home")); + Path[] candidates = { + home.resolve(".runelite").resolve("jagexcache").resolve("oldschool").resolve("LIVE"), + home.resolve("jagexcache").resolve("oldschool").resolve("LIVE") + }; + for (Path candidate : candidates) + if (Files.isRegularFile(candidate.resolve("main_file_cache.dat2"))) + return candidate; + throw new IOException("No OSRS cache found in " + home.resolve("jagexcache") + " or " + home.resolve(".runelite")); + } + + @Nullable + public Region region(int regionX, int regionY) { + int id = (regionX << 8) | regionY; + Region cached = regions.get(id); + if (cached != null) + return cached; + if (regions.containsKey(id)) + return null; + + Region region; + try { + region = load(regionX, regionY); + } catch (Exception ex) { + log.debug("Ignoring map square {},{}, which would not decode", regionX, regionY, ex); + region = null; + } + regions.put(id, region); + return region; + } + + @Nullable + private Region load(int regionX, int regionY) throws IOException { + byte[] terrain = archive("m" + regionX + "_" + regionY, (regionX << 8) | regionY, 0); + if (terrain == null) + return null; + + MapDefinition map = new MapLoader().load(regionX, regionY, terrain); + Region region = new Region(regionX, regionY); + region.loadTerrain(map); + + byte[] locations = archive("l" + regionX + "_" + regionY, (regionX << 8) | regionY, 1); + if (locations != null) { + LocationsDefinition locs = new LocationsLoader().load(regionX, regionY, locations); + region.loadLocations(locs); + } + + return region; + } + + @Nullable + private byte[] archive(String name, int regionId, int fileId) throws IOException { + Storage storage = store.getStorage(); + + if (mapsAreNamed) { + Archive named = maps.findArchiveByName(name); + return named == null ? null : named.decompress(storage.loadArchive(named)); + } + + Archive archive = maps.getArchive(regionId); + if (archive == null) + return null; + + var file = archive.getFiles(storage.loadArchive(archive)).findFile(fileId); + return file == null ? null : file.getContents(); + } + + @Nullable + public ModelDefinition model(int id) throws IOException { + byte[] data = modelData.get(id); + if (data == null) { + if (modelData.containsKey(id)) + return null; + + Archive archive = models.getArchive(id); + data = archive == null ? null : archive.decompress(store.getStorage().loadArchive(archive)); + modelData.put(id, data); + if (data == null) + return null; + } + return new ModelLoader().load(id, data); + } + + @Nullable + public UnderlayDefinition underlay(int id) { + return underlays.provide(id); + } + + @Nullable + public OverlayDefinition overlay(int id) { + return overlays.provide(id); + } + + @Nullable + public ObjectDefinition object(int id) { + return objects.getObject(id); + } + + @Nullable + public TextureDefinition texture(int id) { + return textures.findTexture(id); + } + + public List textures() { + return textures.getTextures(); + } + + public int textureColor(int id) { + TextureDefinition texture = texture(id); + return texture == null ? 0 : texture.missingColor; + } + + public Store getStore() { + return store; + } + + @Override + public void close() throws IOException { + store.close(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/HslPalette.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/HslPalette.java new file mode 100644 index 0000000..419ebfd --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/HslPalette.java @@ -0,0 +1,70 @@ +package rs117.hd.dev.sceneloader.scene; + +public final class HslPalette { + public static final double DEFAULT_BRIGHTNESS = 0.8; + + private static final int SIZE = 65536; + + private final int[] palette = new int[SIZE]; + + public HslPalette(double brightness) { + for (int hueSat = 0; hueSat < 512; hueSat++) { + double hue = (hueSat >> 3) / 64.0 + 0.0078125; + double saturation = (hueSat & 7) / 8.0 + 0.0625; + int index = hueSat * 128; + for (int luminance = 0; luminance < 128; luminance++) { + double lightness = luminance / 128.0; + double r = lightness; + double g = lightness; + double b = lightness; + if (saturation != 0) { + double high; + if (lightness < 0.5) { + high = lightness * (saturation + 1.0); + } else { + high = saturation + lightness - saturation * lightness; + } + double low = lightness * 2.0 - high; + + double redHue = hue + 1.0 / 3.0; + if (redHue > 1.0) + redHue--; + double blueHue = hue - 1.0 / 3.0; + if (blueHue < 0.0) + blueHue++; + + r = hueToChannel(redHue, high, low, lightness); + g = hueToChannel(hue, high, low, lightness); + b = hueToChannel(blueHue, high, low, lightness); + } + + int rgb = ((int) (r * 256.0) << 16) + ((int) (g * 256.0) << 8) + (int) (b * 256.0); + int adjusted = applyBrightness(rgb, brightness); + palette[index++] = adjusted == 0 ? 1 : adjusted; + } + } + } + + private static double hueToChannel(double hue, double high, double low, double fallback) { + if (hue * 6.0 < 1.0) + return (high - low) * 6.0 * hue + low; + if (hue * 2.0 < 1.0) + return high; + if (hue * 3.0 < 2.0) + return (high - low) * (2.0 / 3.0 - hue) * 6.0 + low; + return low; + } + + private static int applyBrightness(int rgb, double brightness) { + double r = Math.pow((rgb >> 16) / 256.0, brightness); + double g = Math.pow((rgb >> 8 & 0xFF) / 256.0, brightness); + double b = Math.pow((rgb & 0xFF) / 256.0, brightness); + return ((int) (r * 256.0) << 16) + ((int) (g * 256.0) << 8) + (int) (b * 256.0); + } + + public int toRgb(int packedHsl) { + if (packedHsl == -2) + return 0; + return palette[packedHsl & 0xFFFF]; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelBounds.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelBounds.java new file mode 100644 index 0000000..a122095 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelBounds.java @@ -0,0 +1,45 @@ +package rs117.hd.dev.sceneloader.scene; + +import net.runelite.cache.definitions.ModelDefinition; + +final class ModelBounds { + final int minX, maxX; + final int minZ, maxZ; + final int maxY, modelHeight; + + private ModelBounds(int minX, int maxX, int minZ, int maxZ, int maxY, int modelHeight) { + this.minX = minX; + this.maxX = maxX; + this.minZ = minZ; + this.maxZ = maxZ; + this.maxY = maxY; + this.modelHeight = modelHeight; + } + + static ModelBounds of(ModelDefinition def) { + int minX = 999999, maxX = -999999; + int minZ = 99999, maxZ = -99999; + int maxY = 0, modelHeight = 0; + + for (int i = 0; i < def.vertexCount; i++) { + int x = def.vertexX[i]; + int y = def.vertexY[i]; + int z = def.vertexZ[i]; + + if (x < minX) + minX = x; + if (x > maxX) + maxX = x; + if (z < minZ) + minZ = z; + if (z > maxZ) + maxZ = z; + if (-y > modelHeight) + modelHeight = -y; + if (y > maxY) + maxY = y; + } + + return new ModelBounds(minX, maxX, minZ, maxZ, maxY, modelHeight); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelFactory.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelFactory.java new file mode 100644 index 0000000..ee91b67 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ModelFactory.java @@ -0,0 +1,874 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; +import java.util.HashSet; +import java.util.Set; +import net.runelite.cache.definitions.FrameDefinition; +import net.runelite.cache.definitions.ModelDefinition; +import net.runelite.cache.definitions.ObjectDefinition; +import net.runelite.cache.models.CircularAngle; +import net.runelite.cache.models.FaceNormal; +import net.runelite.cache.models.VertexNormal; + +public class ModelFactory { + private static final int LIGHT_X = -50; + private static final int LIGHT_Y = -10; + private static final int LIGHT_Z = -50; + private static final int AMBIENT_BASE = 64; + private static final int CONTRAST_BASE = 768; + + static final int LOC_OBJECT = 10; + private static final int DIAGONAL_ANGLE = 256; + private static final int DIAGONAL_OFFSET = 45; + private static final int TILE_SIZE = 128; + + private final Definitions defs; + + private final Map litModels = new HashMap<>(); + + public ModelFactory(Definitions defs) { + this.defs = defs; + } + + @Nullable + public BuiltModel model(ObjectDefinition object, int type, int rotation) throws IOException { + return model(object, type, rotation, null); + } + + @Nullable + public BuiltModel model(ObjectDefinition object, int type, int rotation, @Nullable FrameDefinition frame) + throws IOException { + long shape = object.getObjectTypes() == null + ? ((long) object.getId() << 10) + rotation + : ((long) object.getId() << 10) + ((long) type << 3) + rotation; + long key = shape << 33 | (frame == null ? 0 : (frame.id & 0xFFFFFFFFL) + 1); + + if (litModels.containsKey(key)) + return litModels.get(key); + + ModelDefinition built = build(object, type, rotation); + BuiltModel lit = null; + if (built != null) { + lit = light(built, object.getAmbient() + AMBIENT_BASE, object.getContrast() + CONTRAST_BASE); + if (frame != null) + lit = pose(lit, built, frame, rotation); + } + litModels.put(key, lit); + return lit; + } + + /** + * Moves a model into one of its animation's frames. + * + *

The frame is applied with the model turned back to the way it was built, and turned round again + * afterwards. An animation's transforms are written in the model's own directions, so applying them to + * a model that has already been turned to face the way the map wants turns the animation with it: a + * wheel put down facing the other way then turns the other way, which is the one thing about it anyone + * would notice. The client does the same thing either side of the frame for the same reason. + * + * @param rotation the rotation the map asked for, which the model has already been turned by + */ + private BuiltModel pose(BuiltModel lit, ModelDefinition def, FrameDefinition frame, int rotation) { + turnBack(def, rotation & 3); + applyFrame(def, frame); + turnForward(def, rotation & 3); + + return lit.withPose( + toFloats(def.vertexX, def.vertexCount), + toFloats(def.vertexY, def.vertexCount), + toFloats(def.vertexZ, def.vertexCount), + def.faceTransparencies + ); + } + + private static final int FADE_FACES = 5; + + private static final int SET_PIVOT = 0; + private static final int MOVE = 1; + private static final int TURN = 2; + private static final int SCALE = 3; + + private static final int[] SINE = new int[2048]; + private static final int[] COSINE = new int[2048]; + + static { + for (int i = 0; i < 2048; i++) { + SINE[i] = (int) (Math.sin(i * 0.0030679615) * 65536); + COSINE[i] = (int) (Math.cos(i * 0.0030679615) * 65536); + } + } + + /** Undoes the turn the map asked for, so an animation is applied the way it was written */ + private static void turnBack(ModelDefinition def, int rotation) { + switch (rotation) { + case 1: + def.rotate3(); + break; + case 2: + def.rotate2(); + break; + case 3: + def.rotate1(); + break; + default: + break; + } + } + + /** Puts it back the way the map wanted it */ + private static void turnForward(ModelDefinition def, int rotation) { + switch (rotation) { + case 1: + def.rotate1(); + break; + case 2: + def.rotate2(); + break; + case 3: + def.rotate3(); + break; + default: + break; + } + } + + /** + * Moves a model into a frame of an animation, if it is a model that can be animated at all. + * + *

Having groups of vertices to move is what makes a model animatable, and a model without them is + * left alone entirely, fades included. That is the game's own rule and not an optimisation standing in + * for one: {@code Model.method5839} does nothing at all unless the model has vertex groups, so a model + * carrying nothing but groups of faces to fade never fades. It reads like an oversight on their part and + * there is cache data written as though it fades, but what is on screen is what the game draws, and the + * game draws those faces at the colour they were built with. Fading them here instead takes away faces + * that are supposed to be there — for the altar ruins, the whole of the mist standing in the arch. + */ + public static void applyFrame(ModelDefinition def, FrameDefinition frame) { + def.computeAnimationTables(); + int[][] vertexGroups = def.getVertexGroups(); + if (vertexGroups == null) + return; + + int[][] faceGroups = null; + int pivotX = 0, pivotY = 0, pivotZ = 0; + + var framemap = frame.framemap; + for (int i = 0; i < frame.translatorCount; i++) { + int index = frame.indexFrameIds[i]; + if (index < 0 || index >= framemap.types.length) + continue; + + int type = framemap.types[index]; + int[] groups = framemap.frameMaps[index]; + int dx = frame.translator_x[i]; + int dy = frame.translator_y[i]; + int dz = frame.translator_z[i]; + + if (type == FADE_FACES) { + if (faceGroups == null) + faceGroups = faceGroups(def); + fadeFaces(def, faceGroups, groups, dx); + continue; + } + + switch (type) { + case SET_PIVOT: { + long sumX = 0, sumY = 0, sumZ = 0; + int counted = 0; + for (int group : groups) { + if (group < 0 || group >= vertexGroups.length) + continue; + for (int vertex : vertexGroups[group]) { + sumX += def.vertexX[vertex]; + sumY += def.vertexY[vertex]; + sumZ += def.vertexZ[vertex]; + counted++; + } + } + if (counted > 0) { + pivotX = (int) (sumX / counted) + dx; + pivotY = (int) (sumY / counted) + dy; + pivotZ = (int) (sumZ / counted) + dz; + } else { + pivotX = dx; + pivotY = dy; + pivotZ = dz; + } + break; + } + + case MOVE: + for (int group : groups) { + if (group < 0 || group >= vertexGroups.length) + continue; + for (int vertex : vertexGroups[group]) { + def.vertexX[vertex] += dx; + def.vertexY[vertex] += dy; + def.vertexZ[vertex] += dz; + } + } + break; + + case TURN: { + int aroundX = (dx & 0xFF) * 8; + int aroundY = (dy & 0xFF) * 8; + int aroundZ = (dz & 0xFF) * 8; + for (int group : groups) { + if (group < 0 || group >= vertexGroups.length) + continue; + for (int vertex : vertexGroups[group]) { + int x = def.vertexX[vertex] - pivotX; + int y = def.vertexY[vertex] - pivotY; + int z = def.vertexZ[vertex] - pivotZ; + + if (aroundZ != 0) { + int sin = SINE[aroundZ], cos = COSINE[aroundZ]; + int turned = x * cos + y * sin >> 16; + y = y * cos - x * sin >> 16; + x = turned; + } + if (aroundX != 0) { + int sin = SINE[aroundX], cos = COSINE[aroundX]; + int turned = y * cos - z * sin >> 16; + z = z * cos + y * sin >> 16; + y = turned; + } + if (aroundY != 0) { + int sin = SINE[aroundY], cos = COSINE[aroundY]; + int turned = z * sin + x * cos >> 16; + z = z * cos - x * sin >> 16; + x = turned; + } + + def.vertexX[vertex] = x + pivotX; + def.vertexY[vertex] = y + pivotY; + def.vertexZ[vertex] = z + pivotZ; + } + } + break; + } + + case SCALE: + for (int group : groups) { + if (group < 0 || group >= vertexGroups.length) + continue; + for (int vertex : vertexGroups[group]) { + def.vertexX[vertex] = (def.vertexX[vertex] - pivotX) * dx / 128 + pivotX; + def.vertexY[vertex] = (def.vertexY[vertex] - pivotY) * dy / 128 + pivotY; + def.vertexZ[vertex] = (def.vertexZ[vertex] - pivotZ) * dz / 128 + pivotZ; + } + } + break; + + default: + break; + } + } + } + + @Nullable + private static int[][] faceGroups(ModelDefinition def) { + int[] packed = def.packedTransparencyVertexGroups; + if (packed == null) + return null; + + if (def.faceTransparencies == null) { + def.faceTransparencies = new byte[def.faceCount]; + } + + int faces = Math.min(def.faceCount, packed.length); + int highest = 0; + int[] counts = new int[256]; + for (int face = 0; face < faces; face++) { + int group = packed[face] & 0xFF; + counts[group]++; + if (group > highest) + highest = group; + } + + var groups = new int[highest + 1][]; + for (int group = 0; group <= highest; group++) { + groups[group] = new int[counts[group]]; + counts[group] = 0; + } + for (int face = 0; face < faces; face++) { + int group = packed[face] & 0xFF; + groups[group][counts[group]++] = face; + } + return groups; + } + + private static void fadeFaces(ModelDefinition def, @Nullable int[][] faceGroups, int[] frameMap, int by) { + if (faceGroups == null) + return; + + for (int group : frameMap) { + if (group < 0 || group >= faceGroups.length) + continue; + for (int face : faceGroups[group]) { + int alpha = (def.faceTransparencies[face] & 0xFF) + by * 8; + def.faceTransparencies[face] = (byte) Math.max(0, Math.min(255, alpha)); + } + } + } + + @Nullable + public ModelDefinition unlitModel(ObjectDefinition object, int type, int rotation) throws IOException { + return build(object, type, rotation); + } + + @Nullable + private ModelDefinition build(ObjectDefinition object, int type, int rotation) throws IOException { + int[] modelIds = object.getObjectModels(); + int[] types = object.getObjectTypes(); + + ModelDefinition model; + if (types == null) { + if (type != LOC_OBJECT || modelIds == null || modelIds.length == 0) + return null; + + boolean mirrored = object.isRotated(); + if (modelIds.length == 1) { + model = defs.model(modelIds[0]); + if (model == null) + return null; + if (mirrored) + mirror(model); + } else { + var parts = new ModelDefinition[modelIds.length]; + for (int i = 0; i < modelIds.length; i++) { + parts[i] = defs.model(modelIds[i]); + if (parts[i] == null) + return null; + if (mirrored) + mirror(parts[i]); + } + model = merge(parts); + } + } else { + int index = -1; + for (int i = 0; i < types.length; i++) { + if (types[i] == type) { + index = i; + break; + } + } + if (index == -1 || modelIds == null || index >= modelIds.length) + return null; + + model = defs.model(modelIds[index]); + if (model == null) + return null; + if (object.isRotated() ^ rotation > 3) + mirror(model); + } + + if (type == 4 && rotation > 3) { + rotate(model, DIAGONAL_ANGLE); + model.move(DIAGONAL_OFFSET, 0, -DIAGONAL_OFFSET); + } + + switch (rotation & 3) { + case 1: + model.rotate1(); + break; + case 2: + model.rotate2(); + break; + case 3: + model.rotate3(); + break; + default: + break; + } + + if (object.getFullRecolor() != -1) { + for (int i = 0; i < model.faceCount; i++) + model.faceColors[i] = object.getFullRecolor(); + } else if (object.getRecolorToFind() != null) { + short[] find = object.getRecolorToFind(); + short[] replace = object.getRecolorToReplace(); + for (int i = 0; i < find.length; i++) + model.recolor(find[i], replace[i]); + } + + if (object.getRetextureToFind() != null) { + short[] find = object.getRetextureToFind(); + short[] replace = object.getTextureToReplace(); + for (int i = 0; i < find.length; i++) + model.retexture(find[i], replace[i]); + } + + if (object.getModelSizeX() != TILE_SIZE || object.getModelSizeHeight() != TILE_SIZE || object.getModelSizeY() != TILE_SIZE) + model.resize(object.getModelSizeX(), object.getModelSizeHeight(), object.getModelSizeY()); + + int offsetX = signed(object.getOffsetX()); + int offsetHeight = signed(object.getOffsetHeight()); + int offsetY = signed(object.getOffsetY()); + if (offsetX != 0 || offsetHeight != 0 || offsetY != 0) + model.move(offsetX, offsetHeight, offsetY); + + return model; + } + + private static int signed(int unsignedShort) { + return unsignedShort > Short.MAX_VALUE ? unsignedShort - 0x10000 : unsignedShort; + } + + private static void mirror(ModelDefinition model) { + for (int i = 0; i < model.vertexCount; i++) + model.vertexZ[i] = -model.vertexZ[i]; + for (int i = 0; i < model.faceCount; i++) { + int swap = model.faceIndices1[i]; + model.faceIndices1[i] = model.faceIndices3[i]; + model.faceIndices3[i] = swap; + } + model.vertexNormals = null; + model.faceNormals = null; + } + + private static void rotate(ModelDefinition model, int angle) { + int sin = CircularAngle.SINE[angle]; + int cos = CircularAngle.COSINE[angle]; + for (int i = 0; i < model.vertexCount; i++) { + int x = model.vertexX[i]; + int z = model.vertexZ[i]; + model.vertexX[i] = x * cos + z * sin >> 16; + model.vertexZ[i] = z * cos - x * sin >> 16; + } + model.vertexNormals = null; + model.faceNormals = null; + } + + private static ModelDefinition merge(ModelDefinition[] parts) { + var merged = new ModelDefinition(); + + int vertexTotal = 0, faceTotal = 0, textureFaceTotal = 0; + boolean anyRenderTypes = false, anyPriorities = false, anyTransparencies = false; + boolean anyFaceGroups = false, anyTextures = false, anyTextureCoords = false, anyZOffsets = false; + int sharedPriority = -1; + + for (ModelDefinition part : parts) { + if (part == null) + continue; + vertexTotal += part.vertexCount; + faceTotal += part.faceCount; + textureFaceTotal += part.numTextureFaces; + + if (part.faceRenderPriorities != null) { + anyPriorities = true; + } else { + if (sharedPriority == -1) + sharedPriority = part.priority; + if (sharedPriority != part.priority) + anyPriorities = true; + } + + anyRenderTypes |= part.faceRenderTypes != null; + anyTransparencies |= part.faceTransparencies != null; + anyFaceGroups |= part.packedTransparencyVertexGroups != null; + anyTextures |= part.faceTextures != null; + anyTextureCoords |= part.textureCoords != null; + anyZOffsets |= part.faceZOffsets != null; + } + + merged.vertexX = new int[vertexTotal]; + merged.vertexY = new int[vertexTotal]; + merged.vertexZ = new int[vertexTotal]; + merged.packedVertexGroups = new int[vertexTotal]; + merged.faceIndices1 = new int[faceTotal]; + merged.faceIndices2 = new int[faceTotal]; + merged.faceIndices3 = new int[faceTotal]; + merged.faceColors = new short[faceTotal]; + merged.priority = (byte) (sharedPriority == -1 ? 0 : sharedPriority); + + if (anyRenderTypes) + merged.faceRenderTypes = new byte[faceTotal]; + if (anyPriorities) + merged.faceRenderPriorities = new byte[faceTotal]; + if (anyTransparencies) + merged.faceTransparencies = new byte[faceTotal]; + if (anyFaceGroups) + merged.packedTransparencyVertexGroups = new int[faceTotal]; + if (anyTextures) + merged.faceTextures = new short[faceTotal]; + if (anyTextureCoords) + merged.textureCoords = new byte[faceTotal]; + if (anyZOffsets) + merged.faceZOffsets = new byte[faceTotal]; + + if (textureFaceTotal > 0) { + merged.textureRenderTypes = new byte[textureFaceTotal]; + merged.texIndices1 = new short[textureFaceTotal]; + merged.texIndices2 = new short[textureFaceTotal]; + merged.texIndices3 = new short[textureFaceTotal]; + } + + merged.vertexCount = 0; + merged.faceCount = 0; + merged.numTextureFaces = 0; + + for (ModelDefinition part : parts) { + if (part == null) + continue; + + int[] partGroups = groupOfVertex(part); + + for (int face = 0; face < part.faceCount; face++) { + int at = merged.faceCount; + + if (anyRenderTypes && part.faceRenderTypes != null) + merged.faceRenderTypes[at] = part.faceRenderTypes[face]; + if (anyPriorities) + merged.faceRenderPriorities[at] = part.faceRenderPriorities != null + ? part.faceRenderPriorities[face] + : part.priority; + if (anyTransparencies && part.faceTransparencies != null) + merged.faceTransparencies[at] = part.faceTransparencies[face]; + if (anyFaceGroups && part.packedTransparencyVertexGroups != null) + merged.packedTransparencyVertexGroups[at] = part.packedTransparencyVertexGroups[face]; + if (anyTextures) + merged.faceTextures[at] = part.faceTextures != null ? part.faceTextures[face] : -1; + if (anyTextureCoords) + merged.textureCoords[at] = part.textureCoords != null && part.textureCoords[face] != -1 + ? (byte) (part.textureCoords[face] + merged.numTextureFaces) + : -1; + if (anyZOffsets && part.faceZOffsets != null) + merged.faceZOffsets[at] = part.faceZOffsets[face]; + + merged.faceColors[at] = part.faceColors[face]; + merged.faceIndices1[at] = shareVertex(merged, part, partGroups, part.faceIndices1[face]); + merged.faceIndices2[at] = shareVertex(merged, part, partGroups, part.faceIndices2[face]); + merged.faceIndices3[at] = shareVertex(merged, part, partGroups, part.faceIndices3[face]); + merged.faceCount++; + } + + for (int triangle = 0; triangle < part.numTextureFaces; triangle++) { + int at = merged.numTextureFaces; + byte renderType = merged.textureRenderTypes[at] = part.textureRenderTypes[triangle]; + if (renderType == 0) { + merged.texIndices1[at] = (short) shareVertex(merged, part, partGroups, part.texIndices1[triangle]); + merged.texIndices2[at] = (short) shareVertex(merged, part, partGroups, part.texIndices2[triangle]); + merged.texIndices3[at] = (short) shareVertex(merged, part, partGroups, part.texIndices3[triangle]); + } + merged.numTextureFaces++; + } + } + + return merged; + } + + private static int shareVertex( + ModelDefinition merged, ModelDefinition part, @Nullable int[] partGroups, int vertex + ) { + int x = part.vertexX[vertex]; + int y = part.vertexY[vertex]; + int z = part.vertexZ[vertex]; + + for (int i = 0; i < merged.vertexCount; i++) + if (merged.vertexX[i] == x && merged.vertexY[i] == y && merged.vertexZ[i] == z) + return i; + + merged.vertexX[merged.vertexCount] = x; + merged.vertexY[merged.vertexCount] = y; + merged.vertexZ[merged.vertexCount] = z; + if (partGroups != null && vertex < partGroups.length) + merged.packedVertexGroups[merged.vertexCount] = partGroups[vertex]; + return merged.vertexCount++; + } + + @Nullable + private static int[] groupOfVertex(ModelDefinition part) { + if (part.packedVertexGroups != null) + return part.packedVertexGroups; + + int[][] groups = part.getVertexGroups(); + if (groups == null) + return null; + + var byVertex = new int[part.vertexCount]; + for (int group = 0; group < groups.length; group++) { + if (groups[group] == null) + continue; + for (int vertex : groups[group]) + if (vertex >= 0 && vertex < byVertex.length) + byVertex[vertex] = group; + } + return byVertex; + } + + public static BuiltModel light(ModelDefinition def, int ambient, int contrast) { + return light(def, ambient, contrast, null); + } + + public static BuiltModel light(ModelDefinition def, int ambient, int contrast, @Nullable VertexNormal[] mergedNormals) { + def.computeNormals(); + + int lightLength = (int) Math.sqrt((double) LIGHT_Z * LIGHT_Z + (double) LIGHT_X * LIGHT_X + (double) LIGHT_Y * LIGHT_Y); + int scaledContrast = lightLength * contrast >> 8; + + var model = new BuiltModel(); + model.faceColors1 = new int[def.faceCount]; + model.faceColors2 = new int[def.faceCount]; + model.faceColors3 = new int[def.faceCount]; + + if (def.numTextureFaces > 0 && def.textureCoords != null) + buildTextureTriangles(def, model); + + for (int face = 0; face < def.faceCount; face++) { + int renderType = def.faceRenderTypes == null ? 0 : def.faceRenderTypes[face]; + int alpha = def.faceTransparencies == null ? 0 : def.faceTransparencies[face]; + int texture = def.faceTextures == null ? -1 : def.faceTextures[face]; + + if (alpha == -2) + renderType = 3; + if (alpha == -1) + renderType = 2; + + if (texture == -1) { + if (renderType == 0) { + int color = def.faceColors[face] & 0xFFFF; + model.faceColors1[face] = shade(color, vertexLight(def, mergedNormals, def.faceIndices1[face], scaledContrast, ambient)); + model.faceColors2[face] = shade(color, vertexLight(def, mergedNormals, def.faceIndices2[face], scaledContrast, ambient)); + model.faceColors3[face] = shade(color, vertexLight(def, mergedNormals, def.faceIndices3[face], scaledContrast, ambient)); + } else if (renderType == 1) { + model.faceColors1[face] = shade(def.faceColors[face] & 0xFFFF, faceLight(def, face, scaledContrast, ambient)); + model.faceColors3[face] = -1; + } else if (renderType == 3) { + model.faceColors1[face] = 128; + model.faceColors3[face] = -1; + } else { + model.faceColors3[face] = -2; + } + } else if (renderType == 0) { + model.faceColors1[face] = clamp(vertexLight(def, mergedNormals, def.faceIndices1[face], scaledContrast, ambient)); + model.faceColors2[face] = clamp(vertexLight(def, mergedNormals, def.faceIndices2[face], scaledContrast, ambient)); + model.faceColors3[face] = clamp(vertexLight(def, mergedNormals, def.faceIndices3[face], scaledContrast, ambient)); + } else if (renderType == 1) { + model.faceColors1[face] = clamp(faceLight(def, face, scaledContrast, ambient)); + model.faceColors3[face] = -1; + } else { + model.faceColors3[face] = -2; + } + } + + model.verticesCount = def.vertexCount; + model.verticesX = toFloats(def.vertexX, def.vertexCount); + model.verticesY = toFloats(def.vertexY, def.vertexCount); + model.verticesZ = toFloats(def.vertexZ, def.vertexCount); + + model.faceCount = def.faceCount; + model.faceIndices1 = def.faceIndices1; + model.faceIndices2 = def.faceIndices2; + model.faceIndices3 = def.faceIndices3; + + model.faceRenderPriorities = def.faceRenderPriorities; + model.faceTransparencies = def.faceTransparencies; + model.faceTextures = def.faceTextures; + model.faceBias = def.faceZOffsets; + model.unlitFaceColors = def.faceColors; + + storeVertexNormals(def, mergedNormals, model); + + return model; + } + + private static void buildTextureTriangles(ModelDefinition def, BuiltModel model) { + int[] remapped = new int[def.numTextureFaces]; + + for (int face = 0; face < def.faceCount; face++) + if (def.textureCoords[face] != -1) + remapped[def.textureCoords[face] & 0xFF]++; + + int kept = 0; + for (int i = 0; i < def.numTextureFaces; i++) + if (remapped[i] > 0 && def.textureRenderTypes[i] == 0) + kept++; + + model.texIndices1 = new int[kept]; + model.texIndices2 = new int[kept]; + model.texIndices3 = new int[kept]; + + int at = 0; + for (int i = 0; i < def.numTextureFaces; i++) { + if (remapped[i] > 0 && def.textureRenderTypes[i] == 0) { + model.texIndices1[at] = def.texIndices1[i] & 0xFFFF; + model.texIndices2[at] = def.texIndices2[i] & 0xFFFF; + model.texIndices3[at] = def.texIndices3[i] & 0xFFFF; + remapped[i] = at++; + } else { + remapped[i] = -1; + } + } + + model.textureFaces = new byte[def.faceCount]; + for (int face = 0; face < def.faceCount; face++) + model.textureFaces[face] = def.textureCoords[face] != -1 + ? (byte) remapped[def.textureCoords[face] & 0xFF] + : -1; + } + + private static void storeVertexNormals(ModelDefinition def, @Nullable VertexNormal[] mergedNormals, BuiltModel model) { + if (def.vertexNormals == null) + return; + + model.vertexNormalsX = new int[def.vertexCount]; + model.vertexNormalsY = new int[def.vertexCount]; + model.vertexNormalsZ = new int[def.vertexCount]; + for (int i = 0; i < def.vertexCount; i++) { + VertexNormal normal = normalAt(def, mergedNormals, i); + if (normal == null) + continue; + model.vertexNormalsX[i] = normal.x; + model.vertexNormalsY[i] = normal.y; + model.vertexNormalsZ[i] = normal.z; + } + } + + @Nullable + static VertexNormal normalAt(ModelDefinition def, @Nullable VertexNormal[] mergedNormals, int vertex) { + if (mergedNormals != null && mergedNormals[vertex] != null) + return mergedNormals[vertex]; + return def.vertexNormals[vertex]; + } + + private static int vertexLight(ModelDefinition def, @Nullable VertexNormal[] mergedNormals, int vertex, int scaledContrast, int ambient) { + VertexNormal normal = normalAt(def, mergedNormals, vertex); + int divisor = scaledContrast * normal.magnitude; + if (divisor == 0) + return ambient; + return (LIGHT_Y * normal.y + LIGHT_Z * normal.z + LIGHT_X * normal.x) / divisor + ambient; + } + + private static int faceLight(ModelDefinition def, int face, int scaledContrast, int ambient) { + FaceNormal normal = def.faceNormals[face]; + int divisor = scaledContrast / 2 + scaledContrast; + if (divisor == 0) + return ambient; + return (LIGHT_Y * normal.y + LIGHT_Z * normal.z + LIGHT_X * normal.x) / divisor + ambient; + } + + private static int shade(int color, int light) { + return (color & 0xFF80) + clamp((color & 0x7F) * light >> 7); + } + + private static int clamp(int light) { + if (light < 2) + return 2; + return Math.min(light, 126); + } + + private static float[] toFloats(int[] values, int count) { + float[] floats = new float[count]; + for (int i = 0; i < count; i++) + floats[i] = values[i]; + return floats; + } + + public static void contourDefinition( + ModelDefinition def, int[][] heights, int localX, int baseHeight, int localY, int contouredGround + ) { + ModelBounds bounds = ModelBounds.of(def); + + int minX = bounds.minX + localX; + int maxX = bounds.maxX + localX; + int minZ = bounds.minZ + localY; + int maxZ = bounds.maxZ + localY; + + if (minX < 0 || (maxX + TILE_SIZE >> 7) >= heights.length || minZ < 0 || (maxZ + TILE_SIZE >> 7) >= heights[0].length) + return; + + int westTile = minX >> 7; + int eastTile = maxX + TILE_SIZE - 1 >> 7; + int southTile = minZ >> 7; + int northTile = maxZ + TILE_SIZE - 1 >> 7; + + if (heights[westTile][southTile] == baseHeight + && heights[eastTile][southTile] == baseHeight + && heights[westTile][northTile] == baseHeight + && heights[eastTile][northTile] == baseHeight) + return; + + for (int i = 0; i < def.vertexCount; i++) { + int vertexY = def.vertexY[i]; + int ground = groundAt(def.vertexX[i] + localX, def.vertexZ[i] + localY, heights); + + if (contouredGround > 0) { + int up = (-vertexY << 16) / Math.max(1, bounds.modelHeight); + if (up >= contouredGround) + continue; + def.vertexY[i] = (contouredGround - up) * (ground - baseHeight) / contouredGround + vertexY; + } else { + def.vertexY[i] = vertexY + ground - baseHeight; + } + } + + def.vertexNormals = null; + def.faceNormals = null; + } + + static int groundAt(int x, int z, int[][] heights) { + int fracX = x & TILE_SIZE - 1; + int fracZ = z & TILE_SIZE - 1; + int tileX = x >> 7; + int tileZ = z >> 7; + + int south = (TILE_SIZE - fracX) * heights[tileX][tileZ] + heights[tileX + 1][tileZ] * fracX >> 7; + int north = (TILE_SIZE - fracX) * heights[tileX][tileZ + 1] + heights[tileX + 1][tileZ + 1] * fracX >> 7; + return (TILE_SIZE - fracZ) * south + fracZ * north >> 7; + } + + public static BuiltModel contour( + BuiltModel model, int[][] heights, int localX, int baseHeight, int localY, int contouredGround + ) { + model.calculateBoundsCylinder(); + int reach = model.xyzMag; + + int minX = localX - reach; + int maxX = localX + reach; + int minY = localY - reach; + int maxY = localY + reach; + + if (minX < 0 || (maxX + TILE_SIZE >> 7) >= heights.length || minY < 0 || (maxY + TILE_SIZE >> 7) >= heights[0].length) + return model; + + int westTile = minX >> 7; + int eastTile = maxX + TILE_SIZE - 1 >> 7; + int southTile = minY >> 7; + int northTile = maxY + TILE_SIZE - 1 >> 7; + + if (heights[westTile][southTile] == baseHeight + && heights[eastTile][southTile] == baseHeight + && heights[westTile][northTile] == baseHeight + && heights[eastTile][northTile] == baseHeight) + return model; + + BuiltModel bent = model.copyForContour(); + + for (int i = 0; i < model.verticesCount; i++) { + int vertexY = (int) model.verticesY[i]; + + if (contouredGround > 0) { + int up = (-vertexY << 16) / Math.max(1, model.modelHeight); + if (up >= contouredGround) { + bent.verticesY[i] = model.verticesY[i]; + continue; + } + int ground = groundAt(model, heights, i, localX, localY); + bent.verticesY[i] = (contouredGround - up) * (ground - baseHeight) / contouredGround + vertexY; + } else { + int ground = groundAt(model, heights, i, localX, localY); + bent.verticesY[i] = vertexY + ground - baseHeight; + } + } + + return bent; + } + + private static int groundAt(BuiltModel model, int[][] heights, int vertex, int localX, int localY) { + return groundAt((int) model.verticesX[vertex] + localX, (int) model.verticesZ[vertex] + localY, heights); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/NormalMerger.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/NormalMerger.java new file mode 100644 index 0000000..17a7712 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/NormalMerger.java @@ -0,0 +1,322 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import net.runelite.cache.definitions.ModelDefinition; +import net.runelite.cache.definitions.ObjectDefinition; +import net.runelite.cache.models.VertexNormal; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; +import static net.runelite.api.Constants.MAX_Z; + +public class NormalMerger { + private static final int TILE_SIZE = 128; + private static final int HALF_TILE = TILE_SIZE / 2; + + private static final int MIN_SHARED_TO_HIDE = 3; + private static final byte FACE_HIDDEN = 2; + + public enum Kind { + WALL_A, + WALL_B, + GAME, + GROUND + } + + public static final class Pending { + final ModelDefinition model; + final ObjectDefinition object; + final Kind kind; + final int plane; + final int extendedX, extendedY; + final int sizeX, sizeY; + final Consumer assign; + /** + * Which of the scene's regions put it down. + * + *

Normals are merged between neighbours so the light runs smoothly over a join, which is right + * for two things that really do stand next to each other. Regions laid side by side only touch by + * arrangement, so anything on one side of the join is lit by its own region alone. + */ + int region; + + final ModelBounds bounds; + VertexNormal[] merged; + final int[] marks; + boolean lit; + + public Pending( + ModelDefinition model, ObjectDefinition object, Kind kind, + int plane, int extendedX, int extendedY, int sizeX, int sizeY, + Consumer assign + ) { + this.model = model; + this.object = object; + this.kind = kind; + this.plane = plane; + this.extendedX = extendedX; + this.extendedY = extendedY; + this.sizeX = sizeX; + this.sizeY = sizeY; + this.assign = assign; + + model.computeNormals(); + this.bounds = ModelBounds.of(model); + this.marks = new int[model.vertexCount]; + } + } + + private final List pending = new ArrayList<>(); + private final Map> byTile = new HashMap<>(); + private int pass; + + public boolean isEmpty() { + return pending.isEmpty(); + } + + public void add(Pending entry) { + pending.add(entry); + for (int x = entry.extendedX; x < entry.extendedX + entry.sizeX; x++) + for (int y = entry.extendedY; y < entry.extendedY + entry.sizeY; y++) + if (x >= 0 && y >= 0 && x < EXTENDED_SCENE_SIZE && y < EXTENDED_SCENE_SIZE) + byTile.computeIfAbsent(key(entry.plane, x, y), k -> new ArrayList<>()).add(entry); + } + + public void run(int[][][] heights) { + pending.sort(Comparator + .comparingInt((Pending p) -> p.plane) + .thenComparingInt(p -> p.extendedX) + .thenComparingInt(p -> p.extendedY) + .thenComparingInt(p -> p.kind.ordinal())); + + for (Pending entry : pending) { + if (entry.lit) + continue; + + if (entry.kind == Kind.GROUND) { + mergeGroundNeighbours(entry, heights); + } else { + mergeNeighbours(entry, heights); + } + } + + for (Pending entry : pending) { + if (entry.kind != Kind.WALL_A) + continue; + Pending other = wallPartner(entry); + if (other != null) + merge(entry, other, 0, 0, 0, false); + } + + for (Pending entry : pending) + light(entry); + } + + private Pending wallPartner(Pending wall) { + for (Pending other : at(wall.plane, wall.extendedX, wall.extendedY)) + if (other.kind == Kind.WALL_B) + return other; + return null; + } + + private void mergeNeighbours(Pending entry, int[][][] heights) { + boolean sameTileRules = true; + int xStart = entry.extendedX; + int xEnd = entry.extendedX + entry.sizeX; + int yStart = entry.extendedY - 1; + int yEnd = entry.extendedY + entry.sizeY; + + int ownHeight = tileHeight(heights, entry.plane, entry.extendedX, entry.extendedY); + + for (int plane = entry.plane; plane <= entry.plane + 1; plane++) { + if (plane >= MAX_Z) + continue; + + for (int x = xStart; x <= xEnd; x++) { + if (x < 0 || x >= EXTENDED_SCENE_SIZE) + continue; + + for (int y = yStart; y <= yEnd; y++) { + if (y < 0 || y >= EXTENDED_SCENE_SIZE) + continue; + + if (sameTileRules && !(x >= xEnd || y >= yEnd || y < entry.extendedY && entry.extendedX != x)) + continue; + + int dy = tileHeight(heights, plane, x, y) - ownHeight; + + for (Pending other : at(plane, x, y)) { + if (other == entry || other.region != entry.region) + continue; + + if (other.kind == Kind.WALL_A || other.kind == Kind.WALL_B) { + merge( + entry, other, + (x - entry.extendedX) * TILE_SIZE + (1 - entry.sizeX) * HALF_TILE, + dy, + (y - entry.extendedY) * TILE_SIZE + (1 - entry.sizeY) * HALF_TILE, + sameTileRules + ); + } else if (other.kind == Kind.GAME) { + merge( + entry, other, + (other.extendedX - entry.extendedX) * TILE_SIZE + (other.sizeX - entry.sizeX) * HALF_TILE, + dy, + (other.extendedY - entry.extendedY) * TILE_SIZE + (other.sizeY - entry.sizeY) * HALF_TILE, + sameTileRules + ); + } + } + } + } + + xStart--; + sameTileRules = false; + } + } + + private void mergeGroundNeighbours(Pending entry, int[][][] heights) { + int xEnd = entry.extendedX + 1; + int yEnd = entry.extendedY + 1; + int ownHeight = tileHeight(heights, entry.plane, entry.extendedX, entry.extendedY); + + for (int x = entry.extendedX; x <= xEnd; x++) { + if (x < 0 || x >= EXTENDED_SCENE_SIZE) + continue; + + for (int y = entry.extendedY - 1; y <= yEnd; y++) { + if (y < 0 || y >= EXTENDED_SCENE_SIZE) + continue; + if (x < xEnd && y < yEnd) + continue; + + int dy = tileHeight(heights, entry.plane, x, y) - ownHeight; + for (Pending other : at(entry.plane, x, y)) { + if (other == entry || other.kind != Kind.GROUND || other.region != entry.region) + continue; + merge( + entry, other, + (x - entry.extendedX) * TILE_SIZE, dy, (y - entry.extendedY) * TILE_SIZE, + true + ); + } + } + } + } + + private void merge(Pending a, Pending b, int dx, int dy, int dz, boolean hideSharedFaces) { + pass++; + int shared = 0; + + for (int v = 0; v < a.model.vertexCount; v++) { + VertexNormal aNormal = a.model.vertexNormals[v]; + if (aNormal == null || aNormal.magnitude == 0) + continue; + + int y = a.model.vertexY[v] - dy; + if (y > b.bounds.maxY) + continue; + int x = a.model.vertexX[v] - dx; + if (x < b.bounds.minX || x > b.bounds.maxX) + continue; + int z = a.model.vertexZ[v] - dz; + if (z < b.bounds.minZ || z > b.bounds.maxZ) + continue; + + for (int w = 0; w < b.model.vertexCount; w++) { + VertexNormal bNormal = b.model.vertexNormals[w]; + if (bNormal == null || bNormal.magnitude == 0) + continue; + if (b.model.vertexX[w] != x || b.model.vertexZ[w] != z || b.model.vertexY[w] != y) + continue; + + if (a.merged == null) + a.merged = new VertexNormal[a.model.vertexCount]; + if (b.merged == null) + b.merged = new VertexNormal[b.model.vertexCount]; + + VertexNormal aMerged = a.merged[v]; + if (aMerged == null) + aMerged = a.merged[v] = copyOf(aNormal); + VertexNormal bMerged = b.merged[w]; + if (bMerged == null) + bMerged = b.merged[w] = copyOf(bNormal); + + aMerged.x += bNormal.x; + aMerged.y += bNormal.y; + aMerged.z += bNormal.z; + aMerged.magnitude += bNormal.magnitude; + + bMerged.x += aNormal.x; + bMerged.y += aNormal.y; + bMerged.z += aNormal.z; + bMerged.magnitude += aNormal.magnitude; + + shared++; + a.marks[v] = pass; + b.marks[w] = pass; + } + } + + if (shared < MIN_SHARED_TO_HIDE || !hideSharedFaces) + return; + + hideFullySharedFaces(a); + hideFullySharedFaces(b); + } + + private void hideFullySharedFaces(Pending entry) { + ModelDefinition model = entry.model; + for (int face = 0; face < model.faceCount; face++) { + if (entry.marks[model.faceIndices1[face]] != pass + || entry.marks[model.faceIndices2[face]] != pass + || entry.marks[model.faceIndices3[face]] != pass) + continue; + + if (model.faceRenderTypes == null) + model.faceRenderTypes = new byte[model.faceCount]; + model.faceRenderTypes[face] = FACE_HIDDEN; + } + } + + private void light(Pending entry) { + if (entry.lit) + return; + entry.lit = true; + + BuiltModel model = ModelFactory.light( + entry.model, + entry.object.getAmbient() + 64, + entry.object.getContrast() + 768, + entry.merged + ); + entry.assign.accept(model); + } + + private List at(int plane, int x, int y) { + List found = byTile.get(key(plane, x, y)); + return found == null ? java.util.Collections.emptyList() : found; + } + + private static int tileHeight(int[][][] heights, int plane, int x, int y) { + int[][] plan = heights[plane]; + return plan[x + 1][y + 1] + plan[x][y] + plan[x + 1][y] + plan[x][y + 1] >> 2; + } + + private static VertexNormal copyOf(VertexNormal normal) { + var copy = new VertexNormal(); + copy.x = normal.x; + copy.y = normal.y; + copy.z = normal.z; + copy.magnitude = normal.magnitude; + return copy; + } + + private static int key(int plane, int x, int y) { + return (plane * EXTENDED_SCENE_SIZE + x) * EXTENDED_SCENE_SIZE + y; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ObjectPlacer.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ObjectPlacer.java new file mode 100644 index 0000000..dfa76e1 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/ObjectPlacer.java @@ -0,0 +1,656 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.io.IOException; +import javax.annotation.Nullable; +import net.runelite.api.Model; +import net.runelite.api.Renderable; +import net.runelite.cache.definitions.FrameDefinition; +import net.runelite.cache.definitions.ModelDefinition; +import net.runelite.cache.definitions.ObjectDefinition; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; +import static rs117.hd.dev.sceneloader.scene.SceneBuilder.OFFSET; + +public class ObjectPlacer { + private static final int TILE_SIZE = 128; + private static final int HALF_TILE = TILE_SIZE / 2; + + private static final int MAX_OBJECTS_PER_TILE = 5; + + private static final int WALL = 0; + private static final int WALL_CORNER_A = 1; + private static final int WALL_JOINT = 2; + private static final int WALL_CORNER_B = 3; + private static final int DECOR_AGAINST_WALL = 4; + private static final int DECOR_OFFSET_WALL = 5; + private static final int DECOR_DIAGONAL = 6; + private static final int DECOR_DIAGONAL_OPPOSITE = 7; + private static final int DECOR_DIAGONAL_BOTH = 8; + private static final int WALL_DIAGONAL = 9; + private static final int OBJECT = 10; + private static final int OBJECT_DIAGONAL = 11; + private static final int ROOF_FIRST = 12; + private static final int GROUND_DECORATION = 22; + + private static final int[] WALL_OFFSET_X = { 1, 0, -1, 0 }; + private static final int[] WALL_OFFSET_Y = { 0, -1, 0, 1 }; + private static final int[] CORNER_OFFSET_X = { 1, -1, -1, 1 }; + private static final int[] CORNER_OFFSET_Y = { -1, -1, 1, 1 }; + + private static final int NO_DISPLACEMENT = 16; + private static final int ASSUMED_WALL_DISPLACEMENT = 16; + private static final int ASSUMED_OBJECT_DISPLACEMENT = 8; + + private static final int HASH_TYPE_LOC = 2; + private static final long HASH_NOT_A_DOOR = 0x80000L; + private static final int DIAGONAL_MODEL_ORIENTATION = 256; + private static final int CONFIG_SUPPORTS_ITEMS = 256; + + + private static final int WALL_SHADOW = 50; + private static final int MAX_OBJECT_SHADOW = 30; + private static final int DEFAULT_OBJECT_SHADOW = 15; + + private final Definitions defs; + private final ModelFactory models; + + public ObjectPlacer(Definitions defs, ModelFactory models) { + this.defs = defs; + this.models = models; + } + + public void place(SceneBuilder.Work work, int plane, int sceneX, int sceneY, int id, int rotation, int type) + throws IOException { + ObjectDefinition object = defs.object(id); + if (object == null) + return; + + ObjectDefinition modelObject = object; + BuiltAnimation animation = null; + FrameDefinition[] animationFrames = null; + boolean decidedAtRuntime = object.getConfigChangeDest() != null || object.getAnimationID() != -1; + + if (decidedAtRuntime) { + VariantOptions.Resolution resolution = work.variants.record(object, variantDefs(object)); + if (resolution.hidden) + return; + if (resolution.modelObjectId != -1) { + modelObject = defs.object(resolution.modelObjectId); + if (modelObject == null) + return; + } + + animation = animationFor(object); + if (animation != null) { + animationFrames = framesOf(animation); + if (animationFrames == null) + animation = null; + } + } + + BuiltScene scene = work.scene; + int[][] heights = work.heights[plane]; + + int sizeX = object.getSizeX(); + int sizeY = object.getSizeY(); + if (rotation == 1 || rotation == 3) { + int swap = sizeX; + sizeX = sizeY; + sizeY = swap; + } + + int extendedX = OFFSET + sceneX; + int extendedY = OFFSET + sceneY; + + int sampleWestX, sampleEastX; + if (sceneX + sizeX <= work.maxTile) { + sampleWestX = OFFSET + sceneX + (sizeX >> 1); + sampleEastX = OFFSET + sceneX + (sizeX + 1 >> 1); + } else { + sampleWestX = extendedX; + sampleEastX = extendedX + 1; + } + int sampleSouthY, sampleNorthY; + if (sceneY + sizeY <= work.maxTile) { + sampleSouthY = OFFSET + sceneY + (sizeY >> 1); + sampleNorthY = OFFSET + sceneY + (sizeY + 1 >> 1); + } else { + sampleSouthY = extendedY; + sampleNorthY = extendedY + 1; + } + int height = heights[sampleWestX][sampleSouthY] + heights[sampleWestX][sampleNorthY] + + heights[sampleEastX][sampleSouthY] + heights[sampleEastX][sampleNorthY] >> 2; + + int contourX = (sizeX << 6) + (extendedX << 7); + int contourY = (sizeY << 6) + (extendedY << 7); + + boolean interactableWall = object.getWallOrDoor() != 0 + && sceneX >= 0 && sceneX < 128 && sceneY >= 0 && sceneY < 128; + long hash = hash(plane, sceneX, sceneY, HASH_TYPE_LOC, !interactableWall, id, scene.getWorldViewId()); + + int config = (rotation << 6) + type; + if (object.getSupportsItems() == 1) + config += CONFIG_SUPPORTS_ITEMS; + + boolean smoothSeams = !decidedAtRuntime && modelObject.isMergeNormals(); + + var at = new Placement(work, object, modelObject, animation, animationFrames, + smoothSeams, plane, sceneX, sceneY, + extendedX, extendedY, height, contourX, contourY, rotation, type, hash, config, sizeX, sizeY); + + if (decidedAtRuntime) + work.variants.noteLocation( + object.getId(), + at.sceneX * TILE_SIZE + sizeX * HALF_TILE, at.height, at.sceneY * TILE_SIZE + sizeY * HALF_TILE, + plane, sizeX, sizeY + ); + + if (type == GROUND_DECORATION) { + placeGroundDecoration(at); + } else if (type >= ROOF_FIRST) { + addGameObject(at, model(at, type, rotation), 1, 1, 0); + } else if (type == OBJECT || type == OBJECT_DIAGONAL) { + placeObject(at); + } else if (type == WALL) { + placeWall(at); + } else if (type == WALL_CORNER_A || type == WALL_CORNER_B) { + placeWallCorner(at); + } else if (type == WALL_JOINT) { + placeWallJoint(at); + } else if (type == WALL_DIAGONAL) { + placeDiagonalWall(at); + } else if (type >= DECOR_AGAINST_WALL && type <= DECOR_DIAGONAL_BOTH) { + placeDecoration(at); + } + } + + private void placeGroundDecoration(Placement at) throws IOException { + Slot slot = model(at, GROUND_DECORATION, at.rotation); + if (slot.missing()) + return; + + var object = new BuiltGroundObject( + at.work.scene, at.hash, at.config, + at.sceneX * TILE_SIZE + HALF_TILE, at.sceneY * TILE_SIZE + HALF_TILE, at.height, at.plane, + slot.ready + ); + tileFor(at).setGroundObject(object); + noteDynamic(at, object, slot.ready, object.getX(), object.getZ(), object.getY()); + defer(at, slot, NormalMerger.Kind.GROUND, 1, 1, object::setRenderable); + } + + private void placeObject(Placement at) throws IOException { + Slot slot = model(at, OBJECT, at.rotation); + int modelOrientation = at.type == OBJECT_DIAGONAL ? DIAGONAL_MODEL_ORIENTATION : 0; + + if (addGameObject(at, slot, at.sizeX, at.sizeY, modelOrientation) && at.object.isShadow()) + castObjectShadow(at, slot); + } + + private void placeWall(Placement at) throws IOException { + addWallObject(at, model(at, WALL, at.rotation), Slot.NONE, 1 << at.rotation, 0); + + if (at.object.isShadow()) + castWallShadow(at, true); + displaceDecoration(at, at.object.getDecorDisplacement() + 1); + } + + private void placeWallCorner(Placement at) throws IOException { + addWallObject(at, model(at, at.type, at.rotation), Slot.NONE, 16 << at.rotation, 0); + + if (at.object.isShadow()) + castWallShadow(at, false); + } + + private void placeWallJoint(Placement at) throws IOException { + int otherRotation = at.rotation + 1 & 3; + addWallObject( + at, + model(at, WALL_JOINT, at.rotation + 4), + model(at, WALL_JOINT, otherRotation), + 1 << at.rotation, 1 << otherRotation + ); + displaceDecoration(at, at.object.getDecorDisplacement() + 1); + } + + private void placeDiagonalWall(Placement at) throws IOException { + addGameObject(at, model(at, WALL_DIAGONAL, at.rotation), 1, 1, 0); + displaceDecoration(at, at.object.getDecorDisplacement() / 2 + 1); + } + + private void placeDecoration(Placement at) throws IOException { + int rotation = at.rotation; + + switch (at.type) { + case DECOR_AGAINST_WALL: + addDecorativeObject(at, model(at, DECOR_AGAINST_WALL, rotation), Slot.NONE, + WALL_OFFSET_X[rotation], WALL_OFFSET_Y[rotation], 0, 0); + break; + + case DECOR_OFFSET_WALL: { + int displacement = ASSUMED_WALL_DISPLACEMENT; + var wall = tileFor(at).getWallObject(); + if (wall != null) { + var wallDef = defs.object(wall.getId()); + if (wallDef != null) + displacement = wallDef.getDecorDisplacement(); + } + displacement++; + + addDecorativeObject(at, model(at, DECOR_AGAINST_WALL, rotation), Slot.NONE, + WALL_OFFSET_X[rotation] * displacement, WALL_OFFSET_Y[rotation] * displacement, 0, 0); + break; + } + + case DECOR_DIAGONAL: { + int displacement = objectDisplacement(at) + 1; + addDecorativeObject(at, model(at, DECOR_AGAINST_WALL, rotation + 4), Slot.NONE, + CORNER_OFFSET_X[rotation] * displacement, CORNER_OFFSET_Y[rotation] * displacement, 0, 0); + break; + } + + case DECOR_DIAGONAL_OPPOSITE: { + int otherRotation = rotation + 2 & 3; + addDecorativeObject(at, model(at, DECOR_AGAINST_WALL, otherRotation + 4), Slot.NONE, + CORNER_OFFSET_X[otherRotation], CORNER_OFFSET_Y[otherRotation], 0, 0); + break; + } + + case DECOR_DIAGONAL_BOTH: { + int displacement = objectDisplacement(at) + 1; + int otherRotation = rotation + 2 & 3; + addDecorativeObject( + at, + model(at, DECOR_AGAINST_WALL, rotation + 4), + model(at, DECOR_AGAINST_WALL, otherRotation + 4), + CORNER_OFFSET_X[rotation] * displacement, CORNER_OFFSET_Y[rotation] * displacement, + CORNER_OFFSET_X[otherRotation], CORNER_OFFSET_Y[otherRotation] + ); + break; + } + + default: + break; + } + } + + private int objectDisplacement(Placement at) { + int displacement = ASSUMED_OBJECT_DISPLACEMENT; + for (var object : tileFor(at).getGameObjects()) { + if (object == null) + continue; + var objectDef = defs.object(object.getId()); + if (objectDef != null) + displacement = objectDef.getDecorDisplacement() / 2; + break; + } + return displacement; + } + + private void displaceDecoration(Placement at, int displacement) { + if (at.object.getDecorDisplacement() == NO_DISPLACEMENT) + return; + var decoration = tileFor(at).getDecorativeObject(); + if (decoration instanceof BuiltDecorativeObject) + ((BuiltDecorativeObject) decoration).displace(displacement); + } + + private Slot model(Placement at, int modelType, int modelRotation) throws IOException { + int contour = at.work.hillskew ? at.modelObject.getContouredGround() : -1; + + if (at.smoothSeams) { + ModelDefinition unlit = models.unlitModel(at.modelObject, modelType, modelRotation); + if (unlit == null) + return Slot.NONE; + if (contour >= 0) + ModelFactory.contourDefinition(unlit, at.work.heights[at.plane], at.contourX, at.height, at.contourY, contour); + return Slot.deferred(unlit); + } + + if (at.animation != null) + return animated(at, modelType, modelRotation, contour); + + BuiltModel model = models.model(at.modelObject, modelType, modelRotation); + if (model == null) + return Slot.NONE; + return Slot.ready(contoured(at, model, contour)); + } + + private Slot animated(Placement at, int modelType, int modelRotation, int contour) throws IOException { + FrameDefinition[] frames = at.animationFrames; + assert frames != null && at.animation != null; + + var models = new Model[frames.length]; + boolean any = false; + for (int i = 0; i < frames.length; i++) { + BuiltModel posed = this.models.model(at.modelObject, modelType, modelRotation, frames[i]); + if (posed == null) + continue; + models[i] = contoured(at, posed, contour); + any = true; + } + if (!any) + return Slot.NONE; + + return Slot.ready(new BuiltDynamicObject(at.object.getId(), at.animation, models)); + } + + private BuiltModel contoured(Placement at, BuiltModel model, int contour) { + if (contour < 0) + return model; + return ModelFactory.contour( + model, at.work.heights[at.plane], at.contourX, at.height, at.contourY, contour + ); + } + + private void noteDynamic( + Placement at, net.runelite.api.TileObject owner, @Nullable Renderable renderable, int x, int y, int z + ) { + if (!(renderable instanceof BuiltDynamicObject)) + return; + var dynamic = (BuiltDynamicObject) renderable; + if (!dynamic.hasModel()) + return; + at.work.scene.addDynamic(new BuiltScene.Dynamic(owner, dynamic, 0, x, y, z)); + } + + private void defer( + Placement at, Slot slot, NormalMerger.Kind kind, int sizeX, int sizeY, java.util.function.Consumer assign + ) { + if (slot.deferred == null) + return; + var pending = new NormalMerger.Pending( + slot.deferred, at.modelObject, kind, at.plane, at.extendedX, at.extendedY, sizeX, sizeY, assign + ); + pending.region = at.work.region; + at.work.merger.add(pending); + } + + private BuiltTile tileFor(Placement at) { + return at.work.scene.tile(at.plane, at.extendedX, at.extendedY); + } + + private void ensureColumn(BuiltScene scene, int plane, int x, int y) { + for (int below = plane; below >= 0; below--) + scene.tile(below, x, y); + } + + private boolean addGameObject(Placement at, Slot slot, int sizeX, int sizeY, int modelOrientation) { + if (slot.missing()) + return true; + + BuiltScene scene = at.work.scene; + + for (int x = at.extendedX; x < at.extendedX + sizeX; x++) { + for (int y = at.extendedY; y < at.extendedY + sizeY; y++) { + if (x < 0 || y < 0 || x >= EXTENDED_SCENE_SIZE || y >= EXTENDED_SCENE_SIZE) + return false; + BuiltTile tile = scene.tileOrNull(at.plane, x, y); + if (tile != null && tile.gameObjectCount() >= MAX_OBJECTS_PER_TILE) + return false; + } + } + + var object = new BuiltGameObject( + scene, at.hash, at.config, + at.sceneX * TILE_SIZE + sizeX * HALF_TILE, + at.sceneY * TILE_SIZE + sizeY * HALF_TILE, + at.height, at.plane, + slot.ready, modelOrientation, + at.sceneX, at.sceneY, at.sceneX + sizeX - 1, at.sceneY + sizeY - 1 + ); + + for (int x = at.extendedX; x < at.extendedX + sizeX; x++) { + for (int y = at.extendedY; y < at.extendedY + sizeY; y++) { + ensureColumn(scene, at.plane, x, y); + scene.tile(at.plane, x, y).addGameObject(object); + } + } + + noteDynamic(at, object, slot.ready, object.getX(), object.getZ(), object.getY()); + defer(at, slot, NormalMerger.Kind.GAME, sizeX, sizeY, object::setRenderable); + return true; + } + + private void addWallObject(Placement at, Slot first, Slot second, int orientationA, int orientationB) { + if (first.missing() && second.missing()) + return; + + BuiltScene scene = at.work.scene; + ensureColumn(scene, at.plane, at.extendedX, at.extendedY); + + var object = new BuiltWallObject( + scene, at.hash, at.config, + at.sceneX * TILE_SIZE + HALF_TILE, at.sceneY * TILE_SIZE + HALF_TILE, at.height, at.plane, + first.ready, second.ready, orientationA, orientationB + ); + scene.tile(at.plane, at.extendedX, at.extendedY).setWallObject(object); + + noteDynamic(at, object, first.ready, object.getX(), object.getZ(), object.getY()); + noteDynamic(at, object, second.ready, object.getX(), object.getZ(), object.getY()); + defer(at, first, NormalMerger.Kind.WALL_A, 1, 1, object::setRenderable1); + defer(at, second, NormalMerger.Kind.WALL_B, 1, 1, object::setRenderable2); + } + + private void addDecorativeObject( + Placement at, Slot first, Slot second, + int xOffset, int yOffset, int xOffset2, int yOffset2 + ) { + if (first.missing()) + return; + + BuiltScene scene = at.work.scene; + ensureColumn(scene, at.plane, at.extendedX, at.extendedY); + + var object = new BuiltDecorativeObject( + scene, at.hash, at.config, + at.sceneX * TILE_SIZE + HALF_TILE, at.sceneY * TILE_SIZE + HALF_TILE, at.height, at.plane, + first.ready, second.ready, xOffset, yOffset, xOffset2, yOffset2 + ); + scene.tile(at.plane, at.extendedX, at.extendedY).setDecorativeObject(object); + + noteDynamic(at, object, first.ready, object.getX(), object.getZ(), object.getY()); + noteDynamic(at, object, second.ready, object.getX(), object.getZ(), object.getY()); + defer(at, first, NormalMerger.Kind.GROUND, 1, 1, object::setRenderable); + defer(at, second, NormalMerger.Kind.GROUND, 1, 1, object::setRenderable2); + } + + private void castWallShadow(Placement at, boolean straight) { + byte[][] shadow = at.work.shadow[at.plane]; + int x = at.extendedX; + int y = at.extendedY; + + if (straight) { + switch (at.rotation) { + case 0: + shadow[x][y] = WALL_SHADOW; + shadow[x][y + 1] = WALL_SHADOW; + break; + case 1: + shadow[x][y + 1] = WALL_SHADOW; + shadow[x + 1][y + 1] = WALL_SHADOW; + break; + case 2: + shadow[x + 1][y] = WALL_SHADOW; + shadow[x + 1][y + 1] = WALL_SHADOW; + break; + default: + shadow[x][y] = WALL_SHADOW; + shadow[x + 1][y] = WALL_SHADOW; + break; + } + } else { + switch (at.rotation) { + case 0: + shadow[x][y + 1] = WALL_SHADOW; + break; + case 1: + shadow[x + 1][y + 1] = WALL_SHADOW; + break; + case 2: + shadow[x + 1][y] = WALL_SHADOW; + break; + default: + shadow[x][y] = WALL_SHADOW; + break; + } + } + } + + private void castObjectShadow(Placement at, Slot slot) { + int amount = DEFAULT_OBJECT_SHADOW; + if (slot.ready instanceof BuiltModel) { + var model = (BuiltModel) slot.ready; + model.calculateBoundsCylinder(); + amount = Math.min(model.xyzMag / 4, MAX_OBJECT_SHADOW); + } + + byte[][] shadow = at.work.shadow[at.plane]; + for (int dx = 0; dx <= at.sizeX; dx++) { + for (int dy = 0; dy <= at.sizeY; dy++) { + int x = at.extendedX + dx; + int y = at.extendedY + dy; + if (x < 0 || y < 0 || x >= shadow.length || y >= shadow[0].length) + continue; + if (amount > shadow[x][y]) + shadow[x][y] = (byte) amount; + } + } + } + + public static long hash(int plane, int sceneX, int sceneY, int type, boolean notADoor, int id, int worldViewId) { + long hash = (sceneX & 127L) + | (sceneY & 127L) << 7 + | (plane & 3L) << 14 + | (type & 7L) << 16 + | (id & 0xFFFFFFFFL) << 20 + | (worldViewId & 4095L) << 52; + if (notADoor) + hash |= HASH_NOT_A_DOOR; + return hash; + } + + private static final class Slot { + static final Slot NONE = new Slot(null, null); + + @Nullable + final Renderable ready; + @Nullable + final ModelDefinition deferred; + + private Slot(@Nullable Renderable ready, @Nullable ModelDefinition deferred) { + this.ready = ready; + this.deferred = deferred; + } + + static Slot ready(Renderable renderable) { + return new Slot(renderable, null); + } + + static Slot deferred(ModelDefinition model) { + return new Slot(null, model); + } + + boolean missing() { + return ready == null && deferred == null; + } + } + + /** + * The animation an object plays, which is always the one the id itself names. + * + *

A transform only decides which object supplies the model. The animation stays with the one that + * was placed on the map, even when that one has no model of its own: the game reads the animation once + * when it spawns the object and then transforms afresh every frame purely to find the model to pose. + * Taking it from the transformed object instead leaves anything whose animation lives on the parent + * standing still, which for a model animated by fading its faces also means it never becomes see + * through. + */ + @Nullable + private BuiltAnimation animationFor(ObjectDefinition object) { + int animationId = object.getAnimationID(); + if (animationId == -1) + return null; + + var sequence = defs.sequence(animationId); + if (sequence == null || sequence.frameIDs == null || sequence.frameIDs.length == 0) + return null; + + return new BuiltAnimation(sequence); + } + + @Nullable + private FrameDefinition[] framesOf(BuiltAnimation animation) { + int[] frameIds = animation.definition().frameIDs; + var frames = new FrameDefinition[frameIds.length]; + for (int i = 0; i < frameIds.length; i++) { + frames[i] = defs.frame(frameIds[i]); + if (frames[i] == null) + return null; + } + return frames; + } + + @Nullable + private ObjectDefinition[] variantDefs(ObjectDefinition object) { + int[] variants = object.getConfigChangeDest(); + if (variants == null) + return null; + + var defsForVariants = new ObjectDefinition[variants.length]; + for (int i = 0; i < variants.length; i++) + if (variants[i] != -1) + defsForVariants[i] = defs.object(variants[i]); + return defsForVariants; + } + + private static final class Placement { + final SceneBuilder.Work work; + final ObjectDefinition object; + final ObjectDefinition modelObject; + @Nullable + final BuiltAnimation animation; + @Nullable + final FrameDefinition[] animationFrames; + final boolean smoothSeams; + final int plane; + final int sceneX, sceneY; + final int extendedX, extendedY; + final int height; + final int contourX, contourY; + final int rotation, type; + final long hash; + final int config; + final int sizeX, sizeY; + + Placement( + SceneBuilder.Work work, ObjectDefinition object, ObjectDefinition modelObject, + @Nullable BuiltAnimation animation, @Nullable FrameDefinition[] animationFrames, + boolean smoothSeams, int plane, + int sceneX, int sceneY, int extendedX, int extendedY, + int height, int contourX, int contourY, + int rotation, int type, long hash, int config, int sizeX, int sizeY + ) { + this.work = work; + this.object = object; + this.modelObject = modelObject; + this.animation = animation; + this.animationFrames = animationFrames; + this.smoothSeams = smoothSeams; + this.plane = plane; + this.sceneX = sceneX; + this.sceneY = sceneY; + this.extendedX = extendedX; + this.extendedY = extendedY; + this.height = height; + this.contourX = contourX; + this.contourY = contourY; + this.rotation = rotation; + this.type = type; + this.hash = hash; + this.config = config; + this.sizeX = sizeX; + this.sizeY = sizeY; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/SceneBuilder.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/SceneBuilder.java new file mode 100644 index 0000000..bcf151a --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/SceneBuilder.java @@ -0,0 +1,962 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.io.IOException; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.List; +import javax.annotation.Nullable; +import net.runelite.cache.definitions.ObjectDefinition; +import net.runelite.cache.definitions.OverlayDefinition; +import net.runelite.cache.definitions.UnderlayDefinition; +import net.runelite.cache.region.Location; +import net.runelite.cache.region.Position; +import net.runelite.cache.region.Region; +import rs117.hd.dev.sceneloader.ModelPreview; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; +import static net.runelite.api.Constants.MAX_Z; +import static net.runelite.api.Constants.SCENE_SIZE; +import static rs117.hd.dev.sceneloader.scene.ModelFactory.LOC_OBJECT; + +public class SceneBuilder { + public static final int EXTENDED = EXTENDED_SCENE_SIZE; + public static final int OFFSET = BuiltScene.SCENE_OFFSET; + private static final int HEIGHT_GRID = EXTENDED + 1; + + public static final int NO_COLOR = 12345678; + private static final int HIDDEN_OVERLAY = 0xFF00FF; + + private static final int LIGHT_X = -50; + private static final int LIGHT_Y = -10; + private static final int LIGHT_Z = -50; + private static final int LIGHT_MAGNITUDE = (int) Math.sqrt(5100.0) * 768 >> 8; + private static final int AMBIENT_LIGHT = 96; + + private static final int BLUR_RADIUS = 5; + + private static final int BLANK_SHADOW = 127; + + private static final int BASE_CHUNK_OFFSET = 6; + private static final int BLANK_FILL_CHUNK_LIMIT = 800; + + private final Definitions defs; + private final HslPalette palette; + private final ObjectPlacer placer; + private final ModelFactory factory; + + public SceneBuilder(Definitions defs) { + this(defs, new HslPalette(HslPalette.DEFAULT_BRIGHTNESS)); + } + + public SceneBuilder(Definitions defs, HslPalette palette) { + this.defs = defs; + this.palette = palette; + this.factory = new ModelFactory(defs); + this.placer = new ObjectPlacer(defs, factory); + } + + @Nullable + public ModelPreview.Shape preview(int objectId, int type) throws IOException { + ObjectDefinition object = defs.object(objectId); + if (object == null) + return null; + + int[] types = object.getObjectTypes(); + if (type < 0) + type = types == null || types.length == 0 ? LOC_OBJECT : types[0]; + + BuiltModel model = factory.model(object, type, 0); + if (model == null || model.getFaceCount() == 0) + return null; + + int faceCount = model.getFaceCount(); + int[] colors1 = model.getFaceColors1(); + int[] colors2 = model.getFaceColors2(); + int[] colors3 = model.getFaceColors3(); + short[] textures = model.getFaceTextures(); + byte[] transparencies = model.getFaceTransparencies(); + + var faceColors = new int[faceCount]; + for (int f = 0; f < faceCount; f++) { + if (colors3[f] == -2 || transparencies != null && (transparencies[f] & 0xFF) == 0xFF) { + faceColors[f] = -1; + continue; + } + + int texture = textures == null ? -1 : textures[f]; + if (texture != -1) { + faceColors[f] = palette.toRgb(defs.textureColor(texture)); + } else if (colors3[f] == -1) { + faceColors[f] = palette.toRgb(colors1[f]); + } else { + int a = palette.toRgb(colors1[f]); + int b = palette.toRgb(colors2[f]); + int c = palette.toRgb(colors3[f]); + faceColors[f] = + (((a >> 16 & 0xFF) + (b >> 16 & 0xFF) + (c >> 16 & 0xFF)) / 3) << 16 | + (((a >> 8 & 0xFF) + (b >> 8 & 0xFF) + (c >> 8 & 0xFF)) / 3) << 8 | + ((a & 0xFF) + (b & 0xFF) + (c & 0xFF)) / 3; + } + } + + return new ModelPreview.Shape(model, faceColors); + } + + public BuiltScene build(int worldX, int worldY) throws IOException { + return build(worldX, worldY, 0, 0, new VariantOptions()); + } + + public BuiltScene build(int worldX, int worldY, int expandedChunks, int worldViewId) throws IOException { + return build(worldX, worldY, expandedChunks, worldViewId, new VariantOptions()); + } + + private static int baseOf(int worldTile) { + return ((worldTile >> 3) - BASE_CHUNK_OFFSET) * 8; + } + + public static int[] sceneTiles(int worldX, int worldY, int expandedChunks) { + int baseX = baseOf(worldX); + int baseY = baseOf(worldY); + int minTile = -expandedChunks * 8; + int maxTile = SCENE_SIZE + expandedChunks * 8; + return new int[] { + baseX + minTile, + baseY + minTile, + baseX + maxTile - 1, + baseY + maxTile - 1, + }; + } + + public static int[] regionBlock(int worldX, int worldY, int expandedChunks) { + int[] tiles = sceneTiles(worldX, worldY, expandedChunks); + return new int[] { tiles[0] >> 6, tiles[1] >> 6, tiles[2] >> 6, tiles[3] >> 6 }; + } + + public BuiltScene build( + int worldX, int worldY, int expandedChunks, int worldViewId, VariantOptions variants + ) throws IOException { + variants.startBuild(); + + int baseX = baseOf(worldX); + int baseY = baseOf(worldY); + + int minTile = -expandedChunks * 8; + int maxTile = SCENE_SIZE + expandedChunks * 8; + + List regions = new ArrayList<>(); + List origins = new ArrayList<>(); + List regionIds = new ArrayList<>(); + + int[] block = regionBlock(worldX, worldY, expandedChunks); + int firstRegionX = block[0]; + int firstRegionY = block[1]; + int lastRegionX = block[2]; + int lastRegionY = block[3]; + + for (int regionX = firstRegionX; regionX <= lastRegionX; regionX++) { + for (int regionY = firstRegionY; regionY <= lastRegionY; regionY++) { + regions.add(defs.region(regionX, regionY)); + origins.add(new int[] { (regionX << 6) - baseX, (regionY << 6) - baseY }); + regionIds.add(regionX << 8 | regionY); + } + } + + return assemble( + regions, origins, regionIds, baseX, baseY, worldViewId, variants, minTile, maxTile, + (worldY >> 3) < BLANK_FILL_CHUNK_LIMIT, true, null, null + ); + } + + /** + * How much space to leave between regions that are not neighbours, in tiles. + * + *

Taken off the far side of the region itself rather than added between them. That keeps every + * region on the same sixty four tile pitch, so two that really do adjoin in the world can still be laid + * against each other and drawn whole, while anything unrelated is set apart by this much. A whole + * number of chunks, because a region says where it really is through the instance template, which names + * a whole chunk at a time. + */ + public static final int REGION_GAP = 8; + + /** + * How many regions fit across the scene. + * + *

Three rather than the two that whole regions would allow. A region is sixty four tiles and the + * scene a hundred and eighty four, so three of them only fit if the last gives up the eight tiles it + * cannot have: two at full width and one clipped comes to exactly the scene. + */ + public static final int REGIONS_PER_SIDE = (EXTENDED + REGION_GAP) / Region.X; + + /** + * How many regions may be picked at once. + * + *

Fewer than the nine the scene has room for. Nine is a lot of ground to build and most of them end + * up giving away their edges to make space, so this is held lower on purpose. Raising it to + * {@code REGIONS_PER_SIDE * REGIONS_PER_SIDE} is all that is needed to fill the grid. + */ + public static final int MAX_STITCHED_REGIONS = 5; + + /** One region in a stitched scene: where it was put, and whether its neighbours there are the real ones */ + private static final class Stitched { + final int id; + final int originX, originY; + /** How much ground it covers, before anything beside it is taken into account */ + /** How many of its sixty four tiles are drawn, which is fewer where something unrelated is next to it */ + final int drawnX, drawnY; + /** Which run of adjoining regions it belongs to, so lighting runs across one but not between two */ + final int group; + + Stitched(int id, int originX, int originY, int drawnX, int drawnY, int group) { + this.id = id; + this.originX = originX; + this.originY = originY; + this.drawnX = drawnX; + this.drawnY = drawnY; + this.group = group; + } + } + + public BuiltScene buildStitched(int[] wantedRegions, int worldViewId, VariantOptions variants) + throws IOException { + variants.startBuild(); + + int minTile = -OFFSET; + int maxTile = SCENE_SIZE + OFFSET; + List placed = layOut(wantedRegions); + if (placed.isEmpty()) + return build(3222, 3218, 0, worldViewId, variants); + + List regions = new ArrayList<>(); + List origins = new ArrayList<>(); + List regionIds = new ArrayList<>(); + var drawn = new ArrayList(); + var groups = new ArrayList(); + + for (Stitched entry : placed) { + regions.add(defs.region(entry.id >> 8, entry.id & 0xFF)); + origins.add(new int[] { entry.originX, entry.originY }); + regionIds.add(entry.id); + drawn.add(new int[] { entry.drawnX, entry.drawnY }); + groups.add(entry.group); + } + + int[] first = origins.get(0); + Region firstRegion = regions.get(0); + int baseX = (placed.get(0).id >> 8 << 6) - first[0]; + int baseY = ((placed.get(0).id & 0xFF) << 6) - first[1]; + if (firstRegion != null) { + baseX = firstRegion.getBaseX() - first[0]; + baseY = firstRegion.getBaseY() - first[1]; + } + + BuiltScene scene = assemble( + regions, origins, regionIds, baseX, baseY, worldViewId, variants, minTile, maxTile, + true, true, drawn, groups); + scene.setInstanceTemplateChunks(templateChunks(regionIds, origins)); + return scene; + } + + /** + * Works out where each picked region goes. + * + *

Regions that adjoin each other in the world are gathered into one group and laid out at their true + * offsets, so the group reads as one continuous piece of map. Groups are then packed into the scene with + * a gap between them, since there is nothing continuous about two places that merely got picked + * together. Everything lands on a chunk boundary, which the instance template needs. + * + *

Anything that will not fit is left out rather than overlapped. + */ + /** + * Which of the picked regions will actually fit, in the order they would be laid out. + * + *

Worth asking before building, since whether they fit depends on their shape and not just how many + * there are. Two regions side by side next to two more stacked one above the other needs a hundred and + * ninety two tiles whichever way round it is put, and the scene is a hundred and eighty four. + */ + public static int[] regionsThatFit(int[] wantedRegions) { + var placed = layOut(wantedRegions); + var fitting = new int[placed.size()]; + for (int i = 0; i < fitting.length; i++) + fitting[i] = placed.get(i).id; + return fitting; + } + + private static List layOut(int[] wantedRegions) { + int minTile = -OFFSET; + int span = EXTENDED; + var picked = new ArrayList(); + for (int id : wantedRegions) + if (!picked.contains(id) && picked.size() < MAX_STITCHED_REGIONS) + picked.add(id); + + var pending = new ArrayDeque(groupNeighbours(picked)); + var groups = new ArrayList(); + var offsets = new ArrayList(); + + // Packed left to right, starting a new row when a group will not fit on this one. A group that + // will not fit anywhere is broken up and its regions placed one at a time: they lose the join + // between them, which is a shame, but it beats not showing them at all. A pair side by side next + // to a pair stacked up needs a hundred and ninety two tiles and the scene has a hundred and + // eighty four, so without this the second pair would simply be missing. + int cursorX = 0, cursorY = 0, rowHeight = 0, widest = 0; + while (!pending.isEmpty()) { + int[] group = pending.poll(); + // What it must have: every region at full pitch but the last, which can give up its far edge + int width = group[2] * Region.X - REGION_GAP; + int height = group[3] * Region.Y - REGION_GAP; + + int wrapX = cursorX, wrapY = cursorY, wrapRow = rowHeight; + if (wrapX > 0 && wrapX + width > span) { + wrapX = 0; + wrapY += wrapRow; + wrapRow = 0; + } + + if (width > span || wrapY + height > span) { + var apart = members(picked, group); + if (apart.size() > 1) + for (int i = apart.size() - 1; i >= 0; i--) + pending.addFirst(new int[] { apart.get(i) >> 8, apart.get(i) & 0xFF, 1, 1 }); + continue; + } + + cursorX = wrapX; + cursorY = wrapY; + rowHeight = wrapRow; + + groups.add(group); + offsets.add(new int[] { cursorX, cursorY }); + widest = Math.max(widest, cursorX + width); + rowHeight = Math.max(rowHeight, group[3] * Region.Y); + // On to the next cell, so whatever follows starts a whole region along + cursorX += group[2] * Region.X; + } + int tall = Math.min(cursorY + rowHeight, span); + widest = Math.min(widest, span); + + int leftPad = alignToChunk(minTile + (span - widest) / 2); + int topPad = alignToChunk(minTile + (span - tall) / 2); + + var placed = new ArrayList(); + for (int i = 0; i < groups.size(); i++) { + int[] group = groups.get(i); + int[] offset = offsets.get(i); + int groupX = leftPad + offset[0]; + // Packed downwards, but the scene counts upwards, so the rows are read back the other way + int groupY = topPad + tall - offset[1] - group[3] * Region.Y; + + for (int id : members(picked, group)) { + placed.add(new Stitched( + id, + groupX + ((id >> 8) - group[0]) * Region.X, + groupY + ((id & 0xFF) - group[1]) * Region.Y, + Region.X, Region.Y, i + )); + } + } + return joinUp(placed, minTile + span); + } + + /** + * Works out how much of each region to draw, once everything has been placed. + * + *

A region gives up the far eight tiles of itself to make a space, unless what sits there is the + * region that really does adjoin it, in which case the two are drawn whole and meet seamlessly. Being + * neighbours in the world is not enough on its own: a group that had to be broken up to fit has its + * regions scattered about, and two halves of a pair sitting apart do not share a join. So it is asked + * of the layout rather than of the picking. + * + *

A region with nothing beyond it is drawn whole as well, since there is nothing to be apart from, + * except where the scene runs out first and it is clipped to what is left. + */ + private static List joinUp(List placed, int lastTile) { + var measured = new ArrayList(placed.size()); + for (Stitched entry : placed) { + int drawnX = Region.X, drawnY = Region.Y; + + for (Stitched other : placed) { + boolean east = other.originX == entry.originX + Region.X && other.originY == entry.originY; + boolean north = other.originY == entry.originY + Region.Y && other.originX == entry.originX; + if (east && other.id != entry.id + (1 << 8)) + drawnX = Region.X - REGION_GAP; + if (north && other.id != entry.id + 1) + drawnY = Region.Y - REGION_GAP; + } + + drawnX = Math.min(drawnX, lastTile - entry.originX); + drawnY = Math.min(drawnY, lastTile - entry.originY); + measured.add(new Stitched(entry.id, entry.originX, entry.originY, drawnX, drawnY, entry.group)); + } + return measured; + } + + /** + * Gathers the picked regions into groups that adjoin in the world. + * + * @return one entry per group: its lowest region x and y, then how many regions it spans each way + */ + private static List groupNeighbours(List picked) { + var groups = new ArrayList(); + var taken = new ArrayList(); + + for (int id : picked) { + if (taken.contains(id)) + continue; + + var queue = new ArrayDeque(); + queue.add(id); + taken.add(id); + int minX = id >> 8, maxX = minX, minY = id & 0xFF, maxY = minY; + + while (!queue.isEmpty()) { + int at = queue.poll(); + minX = Math.min(minX, at >> 8); + maxX = Math.max(maxX, at >> 8); + minY = Math.min(minY, at & 0xFF); + maxY = Math.max(maxY, at & 0xFF); + + for (int side : new int[] { 1 << 8, -(1 << 8), 1, -1 }) { + int next = at + side; + if (picked.contains(next) && !taken.contains(next)) { + taken.add(next); + queue.add(next); + } + } + } + + // No more of a group than the scene has room for, since the rest could not be drawn anyway + maxX = Math.min(maxX, minX + REGIONS_PER_SIDE - 1); + maxY = Math.min(maxY, minY + REGIONS_PER_SIDE - 1); + groups.add(new int[] { minX, minY, maxX - minX + 1, maxY - minY + 1 }); + } + return groups; + } + + /** The picked regions inside a group's bounds, bottom row first */ + private static List members(List picked, int[] group) { + var found = new ArrayList(); + for (int id : picked) { + int regionX = id >> 8, regionY = id & 0xFF; + if (regionX >= group[0] && regionX < group[0] + group[2] + && regionY >= group[1] && regionY < group[1] + group[3]) + found.add(id); + } + return found; + } + + /** The nearest chunk boundary at or before a scene tile, counted from the extended scene's own corner */ + private static int alignToChunk(int sceneTile) { + return Math.floorDiv(sceneTile + OFFSET, 8) * 8 - OFFSET; + } + + private static int[][][] templateChunks(List regionIds, List origins) { + int side = BuiltScene.CHUNKS_PER_SIDE; + var chunks = new int[MAX_Z][side][side]; + for (int[][] plane : chunks) + for (int[] column : plane) + java.util.Arrays.fill(column, -1); + + int chunksPerRegion = Region.X / 8; + for (int i = 0; i < regionIds.size(); i++) { + int id = regionIds.get(i); + int regionChunkX = (id >> 8) * chunksPerRegion; + int regionChunkY = (id & 0xFF) * chunksPerRegion; + int[] origin = origins.get(i); + + for (int plane = 0; plane < MAX_Z; plane++) { + for (int cx = 0; cx < chunksPerRegion; cx++) { + for (int cy = 0; cy < chunksPerRegion; cy++) { + int sceneChunkX = (origin[0] + OFFSET) / 8 + cx; + int sceneChunkY = (origin[1] + OFFSET) / 8 + cy; + if (sceneChunkX < 0 || sceneChunkY < 0 || sceneChunkX >= side || sceneChunkY >= side) + continue; + + chunks[plane][sceneChunkX][sceneChunkY] = + plane << 24 | (regionChunkX + cx) << 14 | (regionChunkY + cy) << 3; + } + } + } + } + return chunks; + } + + private BuiltScene assemble( + List regions, List origins, List regionIds, + int baseX, int baseY, int worldViewId, VariantOptions variants, + int minTile, int maxTile, boolean fillBlanks, boolean hillskew, + @Nullable List drawn, @Nullable List groups + ) throws IOException { + int[] mapRegions = new int[regionIds.size()]; + for (int i = 0; i < mapRegions.length; i++) + mapRegions[i] = regionIds.get(i); + + Work work = new Work(new BuiltScene(baseX, baseY, worldViewId, mapRegions), minTile, maxTile, variants); + work.hillskew = hillskew; + work.isolateRegions = drawn != null; + + for (int i = 0; i < regions.size(); i++) { + Region region = regions.get(i); + if (region == null) + continue; + int[] size = drawn == null ? null : drawn.get(i); + readTerrain( + work, region, origins.get(i)[0], origins.get(i)[1], + size == null ? Region.X : size[0], size == null ? Region.Y : size[1] + ); + } + if (fillBlanks) + for (int i = 0; i < regions.size(); i++) + if (regions.get(i) == null) + blank(work, origins.get(i)[0], origins.get(i)[1]); + + for (int i = 0; i < regions.size(); i++) { + Region region = regions.get(i); + if (region == null) + continue; + work.region = groups == null ? 0 : groups.get(i); + int[] size = drawn == null ? null : drawn.get(i); + placeObjects( + work, region, origins.get(i)[0], origins.get(i)[1], + size == null ? Region.X : size[0], size == null ? Region.Y : size[1] + ); + } + + if (!work.merger.isEmpty()) + work.merger.run(work.heights); + + shade(work); + linkBridges(work); + work.scene.buildRoofs(); + + return work.scene; + } + + /** + * Reads one region's terrain into the scene at the place it has been given. + * + *

A tile is drawn between its own corner and the next one along, so the tiles down a region's far + * side read a corner belonging to whatever lies beyond. Where that really is the next region, the + * ground is continuous and the corner holds the one height both of them want, so there is nothing to + * do. Where it is a region from somewhere else entirely, or empty scene, those tiles would be stretched + * from one landscape to the other, which is the wall that appears along such a join. Since the two + * cannot both own the corner, that one row of tiles is left undrawn instead. + * + *

The heights are read either way, one row past the region, so the row behind an undrawn one has a + * corner of its own to sit flat against rather than dropping away to nothing. + * + * @param joinedEast whether the region that really adjoins it to the east is in the scene beside it + * @param joinedNorth the same to the north + */ + private void readTerrain( + Work work, Region region, int originX, int originY, int drawnX, int drawnY + ) { + int edge = work.isolateRegions ? 1 : 0; + boolean joinedEast = drawnX >= Region.X; + boolean joinedNorth = drawnY >= Region.Y; + + for (int plane = 0; plane < MAX_Z; plane++) { + for (int localX = 0; localX < Region.X + edge; localX++) { + int sceneX = originX + localX; + if (sceneX < work.minTile || sceneX >= work.maxTile) + continue; + int x = OFFSET + sceneX; + int sampleX = Math.min(localX, Region.X - 1); + + for (int localY = 0; localY < Region.Y + edge; localY++) { + int sceneY = originY + localY; + if (sceneY < work.minTile || sceneY >= work.maxTile) + continue; + int y = OFFSET + sceneY; + int sampleY = Math.min(localY, Region.Y - 1); + + // Never over a real neighbour's own corner, which it has already read or will read + if (localX < Region.X && localY < Region.Y + || !(joinedEast && localX >= Region.X) + && !(joinedNorth && localY >= Region.Y)) + work.heights[plane][x][y] = region.getTileHeight(plane, sampleX, sampleY); + + if (localX >= drawnX || localY >= drawnY) + continue; + + work.settings[plane][x][y] = region.getTileSetting(plane, localX, localY); + work.underlayIds[plane][x][y] = (short) region.getUnderlayId(plane, localX, localY); + work.overlayIds[plane][x][y] = (short) region.getOverlayId(plane, localX, localY); + work.shapes[plane][x][y] = region.getOverlayPath(plane, localX, localY); + work.rotations[plane][x][y] = region.getOverlayRotation(plane, localX, localY); + } + } + } + } + + private void blank(Work work, int originX, int originY) { + int width = Region.X; + int height = Region.Y; + for (int sceneY = originY; sceneY <= originY + height; sceneY++) { + for (int sceneX = originX; sceneX <= originX + width; sceneX++) { + if (sceneX < work.minTile || sceneX >= work.maxTile || sceneY < work.minTile || sceneY >= work.maxTile) + continue; + + int x = OFFSET + sceneX; + int y = OFFSET + sceneY; + work.shadow[0][x][y] = BLANK_SHADOW; + + if (sceneX == originX && sceneX > 0) + work.heights[0][x][y] = work.heights[0][x - 1][y]; + if (sceneX == originX + width && sceneX < EXTENDED - 1) + work.heights[0][x][y] = work.heights[0][x + 1][y]; + if (sceneY == originY && sceneY > 0) + work.heights[0][x][y] = work.heights[0][x][y - 1]; + if (sceneY == originY + height && sceneY < EXTENDED - 1) + work.heights[0][x][y] = work.heights[0][x][y + 1]; + } + } + } + + /** + * Puts down everything the region has, so long as there is ground under it. + * + *

A region that has given up its far edge to make space keeps its locations there all the same, and + * a wall or a tree standing over the gap with nothing beneath it reads as a fault rather than a gap. + * So the same edge is kept off both. + */ + private void placeObjects(Work work, Region region, int originX, int originY, int drawnX, int drawnY) + throws IOException { + for (Location location : region.getLocations()) { + Position position = location.getPosition(); + int localX = position.getX() - region.getBaseX(); + int localY = position.getY() - region.getBaseY(); + if (localX < 0 || localY < 0 || localX >= drawnX || localY >= drawnY) + continue; + + int sceneX = localX + originX; + int sceneY = localY + originY; + int plane = position.getZ(); + + if (sceneX <= work.minTile || sceneY <= work.minTile || sceneX >= work.maxTile - 1 || sceneY >= work.maxTile - 1) + continue; + if (plane < 0 || plane >= MAX_Z) + continue; + + placer.place(work, plane, sceneX, sceneY, location.getId(), location.getOrientation(), location.getType()); + } + } + + private void light(Work work, int plane) { + byte[][] shadow = work.shadow[plane]; + int[][] heights = work.heights[plane]; + + for (int y = 1; y < EXTENDED - 1; y++) { + for (int x = 1; x < EXTENDED - 1; x++) { + int slopeX = heights[x + 1][y] - heights[x - 1][y]; + int slopeY = heights[x][y + 1] - heights[x][y - 1]; + int length = (int) Math.sqrt(slopeX * slopeX + slopeY * slopeY + 65536); + + int normalX = (slopeX << 8) / length; + int normalY = 65536 / length; + int normalZ = (slopeY << 8) / length; + + int lit = (normalY * LIGHT_Y + normalX * LIGHT_X + normalZ * LIGHT_Z) / LIGHT_MAGNITUDE + AMBIENT_LIGHT; + int shaded = (shadow[x][y] >> 1) + + (shadow[x + 1][y] >> 3) + + (shadow[x][y - 1] >> 2) + + (shadow[x][y + 1] >> 3) + + (shadow[x - 1][y] >> 2); + + work.lightness[x][y] = lit - shaded; + } + } + } + + private void shade(Work work) { + for (int plane = 0; plane < MAX_Z; plane++) { + light(work, plane); + + int[] hues = new int[EXTENDED]; + int[] saturations = new int[EXTENDED]; + int[] lightnesses = new int[EXTENDED]; + int[] multipliers = new int[EXTENDED]; + int[] counts = new int[EXTENDED]; + + for (int x = -BLUR_RADIUS; x < EXTENDED + BLUR_RADIUS; x++) { + for (int y = 0; y < EXTENDED; y++) { + int entering = x + BLUR_RADIUS; + if (entering >= 0 && entering < EXTENDED) { + UnderlayDefinition underlay = underlayAt(work, plane, entering, y); + if (underlay != null) { + hues[y] += underlay.getHue(); + saturations[y] += underlay.getSaturation(); + lightnesses[y] += underlay.getLightness(); + multipliers[y] += underlay.getHueMultiplier(); + counts[y]++; + } + } + + int leaving = x - BLUR_RADIUS; + if (leaving >= 0 && leaving < EXTENDED) { + UnderlayDefinition underlay = underlayAt(work, plane, leaving, y); + if (underlay != null) { + hues[y] -= underlay.getHue(); + saturations[y] -= underlay.getSaturation(); + lightnesses[y] -= underlay.getLightness(); + multipliers[y] -= underlay.getHueMultiplier(); + counts[y]--; + } + } + } + + if (x < 1 || x >= EXTENDED - 1) + continue; + + int hue = 0, saturation = 0, lightness = 0, multiplier = 0, count = 0; + for (int y = -BLUR_RADIUS; y < EXTENDED + BLUR_RADIUS; y++) { + int entering = y + BLUR_RADIUS; + if (entering >= 0 && entering < EXTENDED) { + hue += hues[entering]; + saturation += saturations[entering]; + lightness += lightnesses[entering]; + multiplier += multipliers[entering]; + count += counts[entering]; + } + + int leaving = y - BLUR_RADIUS; + if (leaving >= 0 && leaving < EXTENDED) { + hue -= hues[leaving]; + saturation -= saturations[leaving]; + lightness -= lightnesses[leaving]; + multiplier -= multipliers[leaving]; + count -= counts[leaving]; + } + + if (y < 1 || y >= EXTENDED - 1) + continue; + + emit(work, plane, x, y, hue, saturation, lightness, multiplier, count); + } + } + } + } + + @Nullable + private UnderlayDefinition underlayAt(Work work, int plane, int x, int y) { + int id = work.underlayIds[plane][x][y] & 0x7FFF; + return id > 0 ? defs.underlay(id - 1) : null; + } + + private void emit(Work work, int plane, int x, int y, int hue, int saturation, int lightness, int multiplier, int count) { + int underlayId = work.underlayIds[plane][x][y] & 0x7FFF; + int overlayId = work.overlayIds[plane][x][y] & 0x7FFF; + if (underlayId == 0 && overlayId == 0) + return; + + int[][] heights = work.heights[plane]; + int southWestY = heights[x][y]; + int southEastY = heights[x + 1][y]; + int northEastY = heights[x + 1][y + 1]; + int northWestY = heights[x][y + 1]; + + int southWestLight = work.lightness[x][y]; + int southEastLight = work.lightness[x + 1][y]; + int northEastLight = work.lightness[x + 1][y + 1]; + int northWestLight = work.lightness[x][y + 1]; + + int underlayHsl = -1; + if (underlayId > 0 && count > 0 && multiplier > 0) + underlayHsl = packHsl(hue * 256 / multiplier, saturation / count, lightness / count); + + int underlayRgb = underlayHsl == -1 ? 0 : palette.toRgb(shadeUnderlay(underlayHsl, AMBIENT_LIGHT)); + + if (overlayId == 0) { + addTile( + work, plane, x, y, 0, 0, -1, + southWestY, southEastY, northEastY, northWestY, + shadeUnderlay(underlayHsl, southWestLight), + shadeUnderlay(underlayHsl, southEastLight), + shadeUnderlay(underlayHsl, northEastLight), + shadeUnderlay(underlayHsl, northWestLight), + 0, 0, 0, 0, + underlayRgb, 0 + ); + return; + } + + int shape = work.shapes[plane][x][y] + 1; + int rotation = work.rotations[plane][x][y]; + + OverlayDefinition overlay = defs.overlay(overlayId - 1); + int texture = overlay == null ? -1 : overlay.getTexture(); + + int overlayHsl; + int flatHsl; + if (texture >= 0) { + flatHsl = defs.textureColor(texture); + overlayHsl = -1; + } else if (overlay == null || overlay.getRgbColor() == HIDDEN_OVERLAY) { + overlayHsl = -2; + flatHsl = -2; + texture = -1; + } else { + overlayHsl = packHsl(overlay.getHue(), overlay.getSaturation(), overlay.getLightness()); + flatHsl = overlayHsl; + } + + int overlayRgb = flatHsl == -2 ? 0 : palette.toRgb(shadeOverlay(flatHsl, AMBIENT_LIGHT)); + if (overlay != null && overlay.getSecondaryRgbColor() != -1) { + int secondary = packHsl(overlay.getOtherHue(), overlay.getOtherSaturation(), overlay.getOtherLightness()); + overlayRgb = palette.toRgb(shadeOverlay(secondary, AMBIENT_LIGHT)); + } + + addTile( + work, plane, x, y, shape, rotation, texture, + southWestY, southEastY, northEastY, northWestY, + shadeUnderlay(underlayHsl, southWestLight), + shadeUnderlay(underlayHsl, southEastLight), + shadeUnderlay(underlayHsl, northEastLight), + shadeUnderlay(underlayHsl, northWestLight), + shadeOverlay(overlayHsl, southWestLight), + shadeOverlay(overlayHsl, southEastLight), + shadeOverlay(overlayHsl, northEastLight), + shadeOverlay(overlayHsl, northWestLight), + underlayRgb, overlayRgb + ); + } + + private void addTile( + Work work, int plane, int x, int y, int shape, int rotation, int texture, + int southWestY, int southEastY, int northEastY, int northWestY, + int southWestU, int southEastU, int northEastU, int northWestU, + int southWestO, int southEastO, int northEastO, int northWestO, + int underlayRgb, int overlayRgb + ) { + for (int below = plane; below >= 0; below--) + work.scene.tile(below, x, y); + + BuiltTile tile = work.scene.tile(plane, x, y); + + if (shape == 0) { + tile.setSceneTilePaint(new BuiltTilePaint( + southWestU, southEastU, northEastU, northWestU, -1, underlayRgb, false)); + } else if (shape == 1) { + boolean flat = southWestY == southEastY && southWestY == northEastY && southWestY == northWestY; + tile.setSceneTilePaint(new BuiltTilePaint( + southWestO, southEastO, northEastO, northWestO, texture, overlayRgb, flat)); + } else { + tile.setSceneTileModel(new BuiltTileModel( + shape, rotation, texture, x - OFFSET, y - OFFSET, + southWestY, southEastY, northEastY, northWestY, + southWestU, southEastU, northEastU, northWestU, + southWestO, southEastO, northEastO, northWestO, + underlayRgb, Math.max(1, overlayRgb) + )); + } + } + + private void linkBridges(Work work) { + for (int x = 0; x < EXTENDED; x++) { + for (int y = 0; y < EXTENDED; y++) { + if ((work.settings[1][x][y] & 2) != 2) + continue; + + BuiltScene scene = work.scene; + BuiltTile under = scene.tileOrNull(0, x, y); + + for (int plane = 0; plane < MAX_Z - 1; plane++) { + BuiltTile above = scene.tileOrNull(plane + 1, x, y); + scene.setTile(plane, x, y, above); + if (above != null) + above.setPlane(plane); + } + scene.setTile(MAX_Z - 1, x, y, null); + + if (under != null) + under.setPlane(MAX_Z - 1); + + for (int plane = 0; plane < MAX_Z; plane++) { + BuiltTile tile = scene.tileOrNull(plane, x, y); + if (tile != null) + tile.setOnBridge(true); + } + if (under != null) + under.setOnBridge(true); + + scene.tile(0, x, y).setBridge(under); + } + } + } + + public static int packHsl(int hue, int saturation, int lightness) { + if (lightness > 179) + saturation /= 2; + if (lightness > 192) + saturation /= 2; + if (lightness > 217) + saturation /= 2; + if (lightness > 243) + saturation /= 2; + return (hue / 4 << 10) + (saturation / 32 << 7) + lightness / 2; + } + + public static int shadeUnderlay(int hsl, int light) { + if (hsl == -1) + return NO_COLOR; + return applyLight(hsl, light); + } + + public static int shadeOverlay(int hsl, int light) { + if (hsl == -2) + return NO_COLOR; + if (hsl == -1) + return clampLight(light); + return applyLight(hsl, light); + } + + private static int applyLight(int hsl, int light) { + return (hsl & 0xFF80) + clampLight((hsl & 0x7F) * light / 128); + } + + private static int clampLight(int light) { + if (light < 2) + return 2; + return Math.min(light, 126); + } + + static final class Work { + final BuiltScene scene; + final int minTile, maxTile; + + final int[][][] heights; + final byte[][][] settings; + final short[][][] underlayIds; + final short[][][] overlayIds; + final byte[][][] shapes; + + final byte[][][] rotations = new byte[MAX_Z][EXTENDED][EXTENDED]; + final byte[][][] shadow = new byte[MAX_Z][HEIGHT_GRID][HEIGHT_GRID]; + final int[][] lightness = new int[HEIGHT_GRID][HEIGHT_GRID]; + final NormalMerger merger = new NormalMerger(); + final VariantOptions variants; + /** + * Whether models are bent to follow the ground they stand on. + * + *

Off for regions laid side by side. Bending reaches across tile corners, and the corner where + * two regions meet belongs to both of them while the ground either side of it does not, so anything + * standing near the join gets stretched between two unrelated landscapes. + */ + boolean hillskew = true; + /** Which region's locations are being placed, so their lighting does not reach into another's */ + int region; + /** Whether the regions are unrelated places laid side by side rather than real neighbours */ + boolean isolateRegions; + + Work(BuiltScene scene, int minTile, int maxTile, VariantOptions variants) { + this.scene = scene; + this.minTile = minTile; + this.maxTile = maxTile; + this.variants = variants; + heights = scene.getTileHeights(); + settings = scene.getExtendedTileSettings(); + underlayIds = scene.getUnderlayIds(); + overlayIds = scene.getOverlayIds(); + shapes = scene.getTileShapes(); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantObject.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantObject.java new file mode 100644 index 0000000..dacf09c --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantObject.java @@ -0,0 +1,77 @@ +package rs117.hd.dev.sceneloader.scene; + +import javax.annotation.Nullable; + +public class VariantObject { + public static final class Placed { + public final int x, y, z; + public final int plane; + public final int sizeX, sizeY; + + public Placed(int x, int y, int z, int plane, int sizeX, int sizeY) { + this.x = x; + this.y = y; + this.z = z; + this.plane = plane; + this.sizeX = sizeX; + this.sizeY = sizeY; + } + } + + public final java.util.List placements = new java.util.ArrayList<>(); + + public final int baseId; + public final String name; + public int count; + public int appliedId = -1; + + public final boolean animated; + public final int animationId; + public final int[] variantIds; + public final String[] variantNames; + + @Nullable + public String gameval; + @Nullable + public String[] variantGamevals; + + VariantObject(int baseId, String name, int animationId, int[] variantIds, String[] variantNames) { + this.baseId = baseId; + this.name = name; + this.animationId = animationId; + this.animated = animationId != -1; + this.variantIds = variantIds; + this.variantNames = variantNames; + } + + public boolean hasVariants() { + return variantIds.length > 0; + } + + public int firstVisibleVariant() { + for (int i = 0; i < variantIds.length; i++) + if (variantIds[i] != -1) + return i; + return -1; + } + + @Nullable + public String variantLabel(int index) { + if (index < 0 || index >= variantNames.length) + return null; + String gameval = variantGamevals == null || index >= variantGamevals.length ? null : variantGamevals[index]; + return gameval == null ? variantNames[index] : gameval + " (" + variantIds[index] + ")"; + } + + public String label() { + String shown = name == null || name.isEmpty() || "null".equals(name) ? gameval : name; + if (shown == null || shown.isEmpty()) + shown = "Object"; + return shown + " (" + baseId + ") x" + count; + } + + @Override + public String toString() { + return label(); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantOptions.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantOptions.java new file mode 100644 index 0000000..c451151 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/scene/VariantOptions.java @@ -0,0 +1,106 @@ +package rs117.hd.dev.sceneloader.scene; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import javax.annotation.Nullable; +import net.runelite.cache.definitions.ObjectDefinition; + +public class VariantOptions { + public static final int HIDDEN = -1; + public static final int DEFAULT = -2; + + private final Map choices = new ConcurrentHashMap<>(); + private final Map found = new LinkedHashMap<>(); + + public int choiceFor(int baseId) { + return choices.getOrDefault(baseId, DEFAULT); + } + + public void setChoice(int baseId, int choice) { + choices.put(baseId, choice); + } + + public synchronized List getFound() { + var sorted = new ArrayList(); + for (VariantObject entry : found.values()) + if (entry.hasVariants()) + sorted.add(entry); + sorted.sort((a, b) -> b.count - a.count); + return sorted; + } + + synchronized void noteLocation(int baseId, int x, int y, int z, int plane, int sizeX, int sizeY) { + VariantObject entry = found.get(baseId); + if (entry != null) + entry.placements.add(new VariantObject.Placed(x, y, z, plane, sizeX, sizeY)); + } + + synchronized void startBuild() { + found.clear(); + } + + synchronized Resolution record(ObjectDefinition object, @Nullable ObjectDefinition[] variantDefs) { + int baseId = object.getId(); + VariantObject entry = found.get(baseId); + + if (entry == null) { + int[] variantIds = object.getConfigChangeDest() == null ? new int[0] : object.getConfigChangeDest(); + var names = new String[variantIds.length]; + for (int i = 0; i < variantIds.length; i++) { + if (variantIds[i] == -1) { + names[i] = "Nothing"; + } else { + ObjectDefinition def = variantDefs == null ? null : variantDefs[i]; + String name = def == null ? null : def.getName(); + boolean unnamed = name == null || name.isEmpty() || "null".equals(name); + names[i] = (unnamed ? "Form" : name) + " (" + variantIds[i] + ")"; + } + } + entry = new VariantObject(baseId, object.getName(), object.getAnimationID(), variantIds, names); + found.put(baseId, entry); + } + entry.count++; + + int choice = choiceFor(baseId); + if (choice == HIDDEN) { + entry.appliedId = -1; + return Resolution.HIDE; + } + + if (!entry.hasVariants()) { + entry.appliedId = baseId; + return Resolution.OWN_MODELS; + } + + int index = choice == DEFAULT ? entry.firstVisibleVariant() : choice; + if (index < 0 || index >= entry.variantIds.length) + index = entry.firstVisibleVariant(); + if (index < 0 || entry.variantIds[index] == -1) { + entry.appliedId = -1; + return Resolution.HIDE; + } + + entry.appliedId = entry.variantIds[index]; + return Resolution.variant(entry.appliedId); + } + + static final class Resolution { + static final Resolution HIDE = new Resolution(true, -1); + static final Resolution OWN_MODELS = new Resolution(false, -1); + + final boolean hidden; + final int modelObjectId; + + private Resolution(boolean hidden, int modelObjectId) { + this.hidden = hidden; + this.modelObjectId = modelObjectId; + } + + static Resolution variant(int objectId) { + return new Resolution(false, objectId); + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/FlyCamera.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/FlyCamera.java new file mode 100644 index 0000000..3abc7bc --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/FlyCamera.java @@ -0,0 +1,236 @@ +package rs117.hd.dev.sceneloader.standalone; + +import java.awt.event.KeyEvent; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +public final class FlyCamera { + private static final int ANGLE_UNITS = 16384; + private static final float RADIANS_PER_UNIT = (float) (2 * Math.PI / ANGLE_UNITS); + private static final int QUARTER_TURN = ANGLE_UNITS / 4; + + private static final float CLIENT_FRAMES_PER_SECOND = 50; + + private static final int NORMAL_SPEED = 12; + private static final int SLOW_SPEED = 6; + private static final int SPEED_FRACTION = 16; + private static final float SPEED_GAINED_PER_FRAME = 1 / 8f; + private static final float SPEED_KEPT_PER_FRAME = 0.9f; + + private static final float MIN_PITCH = 1 * RADIANS_PER_UNIT; + private static final float MAX_PITCH = 4160 * RADIANS_PER_UNIT; + + private static final int YAW_TURN_UNITS = 24 << 3; + private static final int PITCH_TURN_UNITS = 12 << 3; + private static final float TURN_GAP_CLOSED_PER_FRAME = 0.5f; + + private static final float DRAG_UNITS_PER_PIXEL = 8; + + private static final float MAX_STEP_SECONDS = 0.1f; + + private static final float VIEWING_DISTANCE = 6 * 128; + private static final float AIM_ABOVE_GROUND = 128; + + private final float[] position = new float[3]; + private float yaw, pitch = 1024 * RADIANS_PER_UNIT; + private float speed = 1; + + private final Set heldKeys = ConcurrentHashMap.newKeySet(); + + private float travelSpeed; + private int travelHeading = -1; + private int travelVertical; + private float yawSpeed, pitchSpeed; + + public float[] getPosition() { + return position; + } + + public float getYaw() { + return yaw; + } + + public float getPitch() { + return pitch; + } + + public void setSpeed(float speed) { + this.speed = speed; + } + + public void placeAt(float x, float y, float z, float yaw, float pitch) { + position[0] = x; + position[1] = y; + position[2] = z; + this.yaw = yaw; + this.pitch = clampPitch(pitch); + stop(); + } + + public void goTo(float x, float y, float z) { + float level = (float) Math.cos(pitch); + float forwardX = -(float) Math.sin(yaw) * level; + float forwardZ = (float) Math.cos(yaw) * level; + float forwardY = (float) Math.sin(pitch); + + float aimY = y - AIM_ABOVE_GROUND; + position[0] = x - forwardX * VIEWING_DISTANCE; + position[1] = aimY - forwardY * VIEWING_DISTANCE; + position[2] = z - forwardZ * VIEWING_DISTANCE; + stop(); + } + + private void stop() { + travelSpeed = 0; + travelHeading = -1; + travelVertical = 0; + yawSpeed = 0; + pitchSpeed = 0; + } + + public void keyPressed(int keyCode) { + heldKeys.add(keyCode); + } + + public void keyReleased(int keyCode) { + heldKeys.remove(keyCode); + } + + public void releaseEverything() { + heldKeys.clear(); + stop(); + } + + public void drag(int dx, int dy) { + turnUnits(-dx * DRAG_UNITS_PER_PIXEL, dy * DRAG_UNITS_PER_PIXEL); + } + + public void step(float seconds) { + if (seconds <= 0) + return; + + float frames = Math.min(seconds, MAX_STEP_SECONDS) * CLIENT_FRAMES_PER_SECOND; + turnWithKeys(frames); + travel(frames); + } + + + private void turnWithKeys(float frames) { + int wantedYaw = heldKeys.contains(KeyEvent.VK_LEFT) ? -YAW_TURN_UNITS + : heldKeys.contains(KeyEvent.VK_RIGHT) ? YAW_TURN_UNITS : 0; + int wantedPitch = heldKeys.contains(KeyEvent.VK_UP) ? PITCH_TURN_UNITS + : heldKeys.contains(KeyEvent.VK_DOWN) ? -PITCH_TURN_UNITS : 0; + + float closed = 1 - (float) Math.pow(1 - TURN_GAP_CLOSED_PER_FRAME, frames); + yawSpeed += (wantedYaw - yawSpeed) * closed; + pitchSpeed += (wantedPitch - pitchSpeed) * closed; + + turnUnits(yawSpeed / 2 * frames, pitchSpeed / 2 * frames); + } + + private void travel(float frames) { + int heading = headingOf(heldKeys); + int vertical = verticalOf(heldKeys); + + float wanted = 0; + if (heading >= 0 || vertical != 0) { + int perFrame = heldKeys.contains(KeyEvent.VK_CONTROL) ? SLOW_SPEED : NORMAL_SPEED; + wanted = perFrame * speed * SPEED_FRACTION; + travelHeading = heading; + travelVertical = vertical; + } + + if (travelSpeed < wanted) { + travelSpeed = Math.min(wanted, travelSpeed + wanted * SPEED_GAINED_PER_FRAME * frames); + } else if (travelSpeed > wanted) { + travelSpeed *= (float) Math.pow(SPEED_KEPT_PER_FRAME, frames); + if (travelSpeed < 1) { + travelSpeed = 0; + travelHeading = -1; + travelVertical = 0; + } + } + if (travelSpeed <= 0) + return; + + float distance = travelSpeed / SPEED_FRACTION * frames; + if (travelHeading >= 0) { + float angle = (travelHeading - yaw / RADIANS_PER_UNIT) * RADIANS_PER_UNIT; + position[0] += distance * (float) Math.sin(angle); + position[2] += distance * (float) Math.cos(angle); + } + position[1] += travelVertical * distance; + } + + static int headingOf(Set held) { + int heading = -1; + if (held.contains(KeyEvent.VK_W)) { + heading = 0; + } else if (held.contains(KeyEvent.VK_S)) { + heading = QUARTER_TURN * 2; + } + + if (held.contains(KeyEvent.VK_A)) { + heading = heading == 0 ? QUARTER_TURN * 7 / 2 + : heading == QUARTER_TURN * 2 ? QUARTER_TURN * 5 / 2 + : QUARTER_TURN * 3; + } else if (held.contains(KeyEvent.VK_D)) { + heading = heading == 0 ? QUARTER_TURN / 2 + : heading == QUARTER_TURN * 2 ? QUARTER_TURN * 3 / 2 + : QUARTER_TURN; + } + return heading; + } + + static int verticalOf(Set held) { + boolean up = held.contains(KeyEvent.VK_R) || held.contains(KeyEvent.VK_E) + || held.contains(KeyEvent.VK_SPACE); + boolean down = held.contains(KeyEvent.VK_F) || held.contains(KeyEvent.VK_Q) + || held.contains(KeyEvent.VK_SHIFT); + if (up == down) + return 0; + return up ? -1 : 1; + } + + private void turnUnits(float yawUnits, float pitchUnits) { + if (yawUnits == 0 && pitchUnits == 0) + return; + yaw += yawUnits * RADIANS_PER_UNIT; + pitch = clampPitch(pitch + pitchUnits * RADIANS_PER_UNIT); + } + + private static float clampPitch(float pitch) { + return Math.max(MIN_PITCH, Math.min(MAX_PITCH, pitch)); + } + + public static boolean isCameraKey(int keyCode) { + switch (keyCode) { + case KeyEvent.VK_W: + case KeyEvent.VK_A: + case KeyEvent.VK_S: + case KeyEvent.VK_D: + case KeyEvent.VK_Q: + case KeyEvent.VK_E: + case KeyEvent.VK_R: + case KeyEvent.VK_F: + case KeyEvent.VK_SPACE: + case KeyEvent.VK_SHIFT: + case KeyEvent.VK_CONTROL: + case KeyEvent.VK_LEFT: + case KeyEvent.VK_RIGHT: + case KeyEvent.VK_UP: + case KeyEvent.VK_DOWN: + return true; + default: + return false; + } + } + + public String describe() { + return String.format( + "%.0f, %.0f, %.0f yaw %.0f° pitch %.0f°", + position[0], position[1], position[2], + Math.toDegrees(yaw) % 360, Math.toDegrees(pitch) + ); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdRuntime.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdRuntime.java new file mode 100644 index 0000000..2e56eb2 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdRuntime.java @@ -0,0 +1,369 @@ +package rs117.hd.dev.sceneloader.standalone; + +import com.google.gson.Gson; +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.name.Names; +import java.awt.Canvas; +import java.awt.Image; +import java.util.HashSet; +import java.util.Set; +import java.util.function.Consumer; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import javax.annotation.Nullable; +import lombok.extern.slf4j.Slf4j; +import net.runelite.api.Client; +import net.runelite.api.GameState; +import net.runelite.api.Projection; +import net.runelite.api.WorldView; +import net.runelite.api.events.BeforeRender; +import net.runelite.api.events.ClientTick; +import net.runelite.api.events.GameStateChanged; +import net.runelite.api.events.GameTick; +import net.runelite.api.hooks.DrawCallbacks; +import net.runelite.client.callback.ClientThread; +import net.runelite.client.callback.RenderCallbackManager; +import net.runelite.client.chat.ChatMessageManager; +import net.runelite.client.config.ConfigManager; +import net.runelite.client.events.ConfigChanged; +import net.runelite.client.eventbus.EventBus; +import net.runelite.client.input.KeyManager; +import net.runelite.client.input.MouseManager; +import net.runelite.client.plugins.Plugin; +import net.runelite.client.plugins.PluginManager; +import net.runelite.client.ui.ClientUI; +import net.runelite.client.ui.DrawManager; +import net.runelite.client.ui.components.colorpicker.ColorPickerManager; +import net.runelite.client.ui.overlay.OverlayManager; +import rs117.hd.HdPlugin; +import rs117.hd.HdPluginConfig; +import rs117.hd.overlays.FrameTimer; +import rs117.hd.dev.sceneloader.scene.BuiltScene; +import rs117.hd.dev.sceneloader.scene.Definitions; +import rs117.hd.renderer.Renderer; +import rs117.hd.renderer.zone.ZoneRenderer; + +import static net.runelite.api.Constants.MAX_Z; +import static rs117.hd.renderer.zone.SceneManager.NUM_ZONES; +import rs117.hd.dev.sceneloader.standalone.client.CacheTextureProvider; +import rs117.hd.dev.sceneloader.standalone.client.Fake; +import rs117.hd.dev.sceneloader.standalone.client.FakeClient; +import rs117.hd.dev.sceneloader.standalone.client.FakeObjects; + +@Slf4j +public final class HdRuntime { + private final Canvas canvas; + private final Definitions defs; + private final Textures textures; + private final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(runnable -> { + var thread = new Thread(runnable, "117 HD standalone"); + thread.setDaemon(true); + return thread; + }); + + private final FakeClient clientState; + private final Client client; + private final InlineClientThread clientThread = new InlineClientThread(); + private final EventBus eventBus = new EventBus(); + private final DrawManager drawManager = new DrawManager(); + private final HdSettings settings; + + private Injector injector; + private HdPlugin plugin; + + @Nullable + private BuiltScene scene; + @Nullable + private Renderer handedTo; + + private int level; + private boolean planesBelow = true; + private boolean showRoofs; + private Set roofIds = Set.of(); + + public HdRuntime(Canvas canvas, Definitions defs, Textures textures, HdSettings settings) { + this.canvas = canvas; + this.defs = defs; + this.textures = textures; + this.settings = settings; + + var provider = new CacheTextureProvider(defs, textures); + clientState = new FakeClient(canvas, provider.asProvider(), new FakeObjects(defs)); + client = Fake.of(Client.class, clientState); + } + + public HdPlugin getPlugin() { + return plugin; + } + + public FrameTimer frameTimer() { + return injector.getInstance(FrameTimer.class); + } + + public void nextFrameTo(Consumer whenDrawn) { + drawManager.requestNextFrameListener(whenDrawn); + } + + public boolean isReady() { + return plugin != null && plugin.renderer != null && clientThread.watchedFinished(); + } + + public void setLevels(int level, boolean planesBelow, boolean showRoofs) { + this.level = Math.max(0, Math.min(MAX_Z - 1, level)); + this.planesBelow = planesBelow; + this.showRoofs = showRoofs; + } + + public void start() throws Exception { + Thread owner = Thread.currentThread(); + clientState.ownedBy(owner); + clientThread.ownedBy(owner); + + plugin = new HdPlugin(); + injector = Guice.createInjector(new Bindings()); + injector.injectMembers(plugin); + + var injectorField = Plugin.class.getDeclaredField("injector"); + injectorField.setAccessible(true); + injectorField.set(plugin, injector); + + eventBus.register(plugin); + settings.whenChanged(this::settingChanged); + + var startUp = HdPlugin.class.getDeclaredMethod("startUp"); + startUp.setAccessible(true); + clientThread.watchNext(); + startUp.invoke(plugin); + + eventBus.post(gameStateChanged(GameState.LOGGED_IN)); + } + + private void settingChanged(String key) { + var event = new ConfigChanged(); + event.setGroup(HdPluginConfig.CONFIG_GROUP); + event.setKey(key); + eventBus.post(event); + } + + public void stop() { + if (plugin == null) + return; + try { + var shutDown = HdPlugin.class.getDeclaredMethod("shutDown"); + shutDown.setAccessible(true); + shutDown.invoke(plugin); + } catch (Exception ex) { + log.warn("Could not stop the plugin cleanly", ex); + } + executor.shutdownNow(); + } + + public void setScene(@Nullable BuiltScene scene) { + this.scene = scene; + handedTo = null; + roofIds = scene == null ? Set.of() : roofIdsOf(scene); + clientState.setScene(scene); + } + + public void frame(float[] cameraPosition, float yaw, float pitch) { + clientThread.runPending(); + clientState.sizeUi(Math.max(1, canvas.getWidth()), Math.max(1, canvas.getHeight())); + clientState.setCamera(cameraPosition, yaw, pitch, level); + clientState.tick(); + + eventBus.post(new ClientTick()); + eventBus.post(new BeforeRender()); + + if (!isReady()) + return; + + Renderer renderer = plugin.renderer; + var scene = this.scene; + if (scene == null) { + renderer.draw(0); + return; + } + + if (handedTo != renderer) { + handOver(renderer, scene); + handedTo = renderer; + } + + if (clientState.getGameCycle() % 30 == 0) + eventBus.post(new GameTick()); + + Projection projection = renderer instanceof ZoneRenderer ? ((ZoneRenderer) renderer).sceneCamera : null; + int minLevel = planesBelow ? 0 : level; + var hiddenRoofs = showRoofs ? Set.of() : roofIds; + + renderer.preSceneDraw( + scene, null, + cameraPosition[0], cameraPosition[1], cameraPosition[2], pitch, yaw, + minLevel, level, MAX_Z - 1, hiddenRoofs + ); + + if (plugin.sceneViewport != null) { + drawDynamics(renderer, projection, scene, minLevel, hiddenRoofs); + + for (int zx = 0; zx < NUM_ZONES; zx++) + for (int zz = 0; zz < NUM_ZONES; zz++) + renderer.drawZoneOpaque(projection, scene, zx, zz); + renderer.drawPass(projection, scene, DrawCallbacks.PASS_OPAQUE); + + renderer.drawPass(projection, scene, DrawCallbacks.PRE_PASS_ALPHA); + int[] order = zonesFurthestFirst(cameraPosition); + for (int at = minLevel; at < MAX_Z; at++) + for (int zone : order) + renderer.drawZoneAlpha(projection, scene, at, zone >> 8, zone & 0xFF); + renderer.drawPass(projection, scene, DrawCallbacks.PASS_ALPHA); + + renderer.postSceneDraw(scene); + } + + renderer.draw(0); + } + + private void handOver(Renderer renderer, BuiltScene scene) { + WorldView worldView = client.getTopLevelWorldView(); + renderer.loadScene(worldView, scene); + renderer.swapScene(scene); + + for (int x = 0; x < NUM_ZONES; x++) + for (int z = 0; z < NUM_ZONES; z++) + renderer.invalidateZone(scene, x, z); + + log.debug("Handed over a scene at {}, {}", scene.getBaseX(), scene.getBaseY()); + } + + private void drawDynamics( + Renderer renderer, @Nullable Projection projection, BuiltScene scene, + int minLevel, Set hiddenRoofs + ) { + if (projection == null || scene.getDynamics().isEmpty()) + return; + + int cycle = clientState.getGameCycle(); + int[][][] roofs = scene.getRoofs(); + + for (var dynamic : scene.getDynamics()) { + if (!isShown(dynamic, roofs, minLevel, hiddenRoofs)) + continue; + + var model = dynamic.renderable.modelAt(cycle); + if (model == null) + continue; + renderer.drawDynamic( + -1, projection, scene, dynamic.tileObject, dynamic.renderable, model, + dynamic.orientation, dynamic.x, dynamic.y, dynamic.z + ); + } + } + + private boolean isShown(BuiltScene.Dynamic dynamic, int[][][] roofs, int minLevel, Set hiddenRoofs) { + int objectLevel = dynamic.tileObject.getPlane(); + if (objectLevel < minLevel) + return false; + if (objectLevel <= level || objectLevel >= MAX_Z || hiddenRoofs.isEmpty()) + return true; + + int tileX = (dynamic.x >> 7) + BuiltScene.SCENE_OFFSET; + int tileZ = (dynamic.z >> 7) + BuiltScene.SCENE_OFFSET; + var plan = roofs[objectLevel]; + if (tileX < 0 || tileX >= plan.length || tileZ < 0 || tileZ >= plan[tileX].length) + return true; + + int roofId = plan[tileX][tileZ]; + return roofId == 0 || !hiddenRoofs.contains(roofId); + } + + private int[] zoneOrder; + private long[] zoneDistance; + + private int[] zonesFurthestFirst(float[] cameraPosition) { + int count = NUM_ZONES * NUM_ZONES; + if (zoneOrder == null) { + zoneOrder = new int[count]; + zoneDistance = new long[count]; + } + + int offset = BuiltScene.SCENE_OFFSET; + for (int zx = 0, at = 0; zx < NUM_ZONES; zx++) { + for (int zz = 0; zz < NUM_ZONES; zz++, at++) { + float x = (zx * 8 - offset) * 128 + 512; + float z = (zz * 8 - offset) * 128 + 512; + float dx = x - cameraPosition[0]; + float dz = z - cameraPosition[2]; + zoneOrder[at] = zx << 8 | zz; + zoneDistance[at] = (long) (dx * dx + dz * dz); + } + } + + for (int i = 1; i < count; i++) { + int zone = zoneOrder[i]; + long distance = zoneDistance[i]; + int j = i - 1; + while (j >= 0 && zoneDistance[j] < distance) { + zoneOrder[j + 1] = zoneOrder[j]; + zoneDistance[j + 1] = zoneDistance[j]; + j--; + } + zoneOrder[j + 1] = zone; + zoneDistance[j + 1] = distance; + } + return zoneOrder; + } + + private static Set roofIdsOf(BuiltScene scene) { + var ids = new HashSet(); + for (int[][] plane : scene.getRoofs()) + for (int[] column : plane) + for (int roofId : column) + if (roofId > 0) + ids.add(roofId); + return ids; + } + + private static GameStateChanged gameStateChanged(GameState state) { + var event = new GameStateChanged(); + event.setGameState(state); + return event; + } + + private final class Bindings extends AbstractModule { + @Override + protected void configure() { + bind(HdPlugin.class).toInstance(plugin); + bind(Client.class).toInstance(client); + + bindConstant().annotatedWith(Names.named("developerMode")).to(true); + bindConstant().annotatedWith(Names.named("safeMode")).to(false); + bindConstant().annotatedWith(Names.named("disableTelemetry")).to(true); + bindConstant().annotatedWith(Names.named("insecureWriteCredentials")).to(false); + bind(ClientThread.class).toInstance(clientThread); + bind(EventBus.class).toInstance(eventBus); + bind(DrawManager.class).toInstance(drawManager); + bind(RenderCallbackManager.class).toInstance(new RenderCallbackManager()); + bind(HdPluginConfig.class).toInstance(settings.asConfig()); + bind(Gson.class).toInstance(new Gson()); + bind(ScheduledExecutorService.class).toInstance(executor); + + bind(ConfigManager.class).toInstance(nothing(ConfigManager.class)); + bind(ClientUI.class).toInstance(nothing(ClientUI.class)); + + var plugins = nothing(PluginManager.class); + org.mockito.Mockito.when(plugins.isPluginEnabled(org.mockito.ArgumentMatchers.any())).thenReturn(true); + bind(PluginManager.class).toInstance(plugins); + bind(OverlayManager.class).toInstance(nothing(OverlayManager.class)); + bind(KeyManager.class).toInstance(nothing(KeyManager.class)); + bind(MouseManager.class).toInstance(nothing(MouseManager.class)); + bind(ColorPickerManager.class).toInstance(nothing(ColorPickerManager.class)); + bind(ChatMessageManager.class).toInstance(nothing(ChatMessageManager.class)); + } + } + + private static T nothing(Class type) { + return org.mockito.Mockito.mock(type); + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdSettings.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdSettings.java new file mode 100644 index 0000000..76f3df0 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/HdSettings.java @@ -0,0 +1,104 @@ +package rs117.hd.dev.sceneloader.standalone; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import lombok.extern.slf4j.Slf4j; +import rs117.hd.HdPluginConfig; +import rs117.hd.dev.sceneloader.standalone.client.Fake; + +@Slf4j +public final class HdSettings { + private final Map values = new ConcurrentHashMap<>(); + private final HdPluginConfig config; + + @Nullable + private volatile Consumer listener; + + public HdSettings() { + config = (HdPluginConfig) Proxy.newProxyInstance( + HdPluginConfig.class.getClassLoader(), + new Class[] { HdPluginConfig.class }, + this::answer + ); + } + + public HdPluginConfig asConfig() { + return config; + } + + public void whenChanged(Consumer listener) { + this.listener = listener; + } + + public void set(String name, String value) { + values.put(name, value); + } + + public void change(String name, String key, String value) { + values.put(name, value); + var told = listener; + if (told != null) + told.accept(key); + } + + private Object answer(Object proxy, Method method, Object[] args) throws Throwable { + String asked = values.get(method.getName()); + if (asked != null && method.getParameterCount() == 0) { + Object value = read(method.getReturnType(), asked); + if (value != null) + return value; + log.warn("Could not read {} as a {}", asked, method.getReturnType().getSimpleName()); + } + + if (method.isDefault()) + return Fake.callDefault(proxy, method, args); + + switch (method.getName()) { + case "toString": + if (method.getParameterCount() == 0) + return "HdPluginConfig(defaults)"; + break; + case "equals": + if (method.getParameterCount() == 1) + return proxy == args[0]; + break; + case "hashCode": + if (method.getParameterCount() == 0) + return System.identityHashCode(proxy); + break; + default: + break; + } + + return Fake.blank(method.getReturnType()); + } + + @Nullable + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static Object read(Class wanted, String value) { + try { + if (wanted.isEnum()) + return Enum.valueOf((Class) wanted, value.toUpperCase()); + if (wanted == boolean.class || wanted == Boolean.class) + return Boolean.parseBoolean(value); + if (wanted == int.class || wanted == Integer.class) + return Integer.parseInt(value); + if (wanted == long.class || wanted == Long.class) + return Long.parseLong(value); + if (wanted == float.class || wanted == Float.class) + return Float.parseFloat(value); + if (wanted == double.class || wanted == Double.class) + return Double.parseDouble(value); + if (wanted == String.class) + return value; + } catch (IllegalArgumentException ex) { + return null; + } + return null; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/InlineClientThread.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/InlineClientThread.java new file mode 100644 index 0000000..5618b24 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/InlineClientThread.java @@ -0,0 +1,106 @@ +package rs117.hd.dev.sceneloader.standalone; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BooleanSupplier; +import lombok.extern.slf4j.Slf4j; +import net.runelite.client.callback.ClientThread; + +@Slf4j +public final class InlineClientThread extends ClientThread { + private final List pending = new ArrayList<>(); + private volatile Thread owner; + + private boolean watching; + private volatile boolean watchedFinished; + + public void ownedBy(Thread owner) { + this.owner = owner; + } + + public void watchNext() { + watching = true; + watchedFinished = false; + } + + public boolean watchedFinished() { + return watchedFinished; + } + + @Override + public void invoke(Runnable runnable) { + invoke(() -> { + runnable.run(); + return true; + }); + } + + @Override + public void invoke(BooleanSupplier work) { + BooleanSupplier watched = watch(work); + if (Thread.currentThread() != owner) { + invokeLater(watched); + return; + } + if (!watched.getAsBoolean()) + invokeLater(watched); + } + + private BooleanSupplier watch(BooleanSupplier work) { + if (!watching) + return work; + watching = false; + return () -> { + boolean finished = work.getAsBoolean(); + if (finished) + watchedFinished = true; + return finished; + }; + } + + @Override + public void invokeLater(Runnable runnable) { + invokeLater(() -> { + runnable.run(); + return true; + }); + } + + @Override + public void invokeLater(BooleanSupplier work) { + synchronized (pending) { + pending.add(work); + } + } + + @Override + public void invokeAtTickEnd(Runnable runnable) { + invokeLater(runnable); + } + + public void runPending() { + List due; + synchronized (pending) { + if (pending.isEmpty()) + return; + due = new ArrayList<>(pending); + pending.clear(); + } + + var again = new ArrayList(); + for (BooleanSupplier work : due) { + try { + if (!work.getAsBoolean()) + again.add(work); + } catch (Throwable ex) { + log.warn("Something the plugin put off went wrong", ex); + } + } + + if (!again.isEmpty()) { + synchronized (pending) { + pending.addAll(again); + } + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/Textures.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/Textures.java new file mode 100644 index 0000000..185c1c9 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/Textures.java @@ -0,0 +1,90 @@ +package rs117.hd.dev.sceneloader.standalone; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; +import lombok.extern.slf4j.Slf4j; +import net.runelite.cache.SpriteManager; +import net.runelite.cache.definitions.SpriteDefinition; +import net.runelite.cache.definitions.TextureDefinition; +import net.runelite.cache.definitions.providers.SpriteProvider; +import rs117.hd.dev.sceneloader.scene.Definitions; + +@Slf4j +public final class Textures { + public static final int SIZE = 128; + + private final Definitions defs; + private final SpriteManager sprites; + private final Map> atBrightness = new HashMap<>(); + + public Textures(Definitions defs) throws IOException { + this.defs = defs; + sprites = new SpriteManager(defs.getStore()); + sprites.load(); + } + + @Nullable + public int[] get(int textureId, double brightness) { + var byId = atBrightness.computeIfAbsent(brightness, b -> new HashMap<>()); + if (byId.containsKey(textureId)) + return byId.get(textureId); + + int[] built = null; + try { + built = build(textureId, brightness); + } catch (Exception | Error ex) { + log.debug("Ignoring texture {}, which would not build", textureId, ex); + } + byId.put(textureId, built); + return built; + } + + @Nullable + private int[] build(int textureId, double brightness) { + TextureDefinition texture = defs.texture(textureId); + if (texture == null) + return null; + + var lender = new Lender(); + try { + texture.method2680(brightness, SIZE, lender); + return texture.pixels == null ? null : texture.pixels.clone(); + } finally { + lender.putBack(); + texture.pixels = null; + } + } + + public List ids() { + var ids = new ArrayList(); + for (var texture : defs.textures()) + ids.add(texture.getId()); + return ids; + } + + private final class Lender implements SpriteProvider { + private final List lent = new ArrayList<>(); + private final List palettes = new ArrayList<>(); + + @Override + public SpriteDefinition provide(int spriteId, int frameId) { + SpriteDefinition sprite = sprites.findSprite(spriteId, frameId); + if (sprite != null && sprite.palette != null) { + lent.add(sprite); + palettes.add(sprite.palette.clone()); + } + return sprite; + } + + void putBack() { + for (int i = 0; i < lent.size(); i++) { + int[] was = palettes.get(i); + System.arraycopy(was, 0, lent.get(i).palette, 0, was.length); + } + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/CacheTextureProvider.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/CacheTextureProvider.java new file mode 100644 index 0000000..6899161 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/CacheTextureProvider.java @@ -0,0 +1,97 @@ +package rs117.hd.dev.sceneloader.standalone.client; + +import javax.annotation.Nullable; +import net.runelite.api.Texture; +import net.runelite.api.TextureProvider; +import rs117.hd.dev.sceneloader.scene.Definitions; +import rs117.hd.dev.sceneloader.scene.HslPalette; +import rs117.hd.dev.sceneloader.standalone.Textures; + +public final class CacheTextureProvider { + private final Definitions defs; + private final Textures textures; + + private final Texture[] byId; + private double brightness = HslPalette.DEFAULT_BRIGHTNESS; + + public CacheTextureProvider(Definitions defs, Textures textures) { + this.defs = defs; + this.textures = textures; + + int highest = 0; + for (int id : textures.ids()) + highest = Math.max(highest, id); + + byId = new Texture[highest + 1]; + for (int id : textures.ids()) + byId[id] = Fake.of(Texture.class, new OneTexture(id)); + } + + public TextureProvider asProvider() { + return Fake.of(TextureProvider.class, this); + } + + public double getBrightness() { + return brightness; + } + + public void setBrightness(double brightness) { + this.brightness = brightness; + } + + public Texture[] getTextures() { + return byId; + } + + @Nullable + public int[] load(int id) { + return textures.get(id, brightness); + } + + public int getDefaultColor(int id) { + return defs.textureColor(id); + } + + private final class OneTexture { + private final int id; + private float u, v; + + OneTexture(int id) { + this.id = id; + } + + public int[] getPixels() { + return load(id); + } + + public int getAnimationDirection() { + var definition = defs.texture(id); + return definition == null ? 0 : definition.animationDirection; + } + + public int getAnimationSpeed() { + var definition = defs.texture(id); + return definition == null ? 0 : definition.animationSpeed; + } + + public boolean isLoaded() { + return true; + } + + public float getU() { + return u; + } + + public void setU(float u) { + this.u = u; + } + + public float getV() { + return v; + } + + public void setV(float v) { + this.v = v; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/Fake.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/Fake.java new file mode 100644 index 0000000..432d904 --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/Fake.java @@ -0,0 +1,128 @@ +package rs117.hd.dev.sceneloader.standalone.client; + +import java.lang.invoke.MethodHandles; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; +import java.util.HashMap; +import java.util.Map; + +public final class Fake { + private Fake() {} + + @SuppressWarnings("unchecked") + public static T of(Class wanted, Object answers) { + var byName = new HashMap(); + for (Method method : answers.getClass().getMethods()) + if (method.getDeclaringClass() != Object.class) + byName.putIfAbsent(key(method), method); + + return (T) Proxy.newProxyInstance( + wanted.getClassLoader(), + new Class[] { wanted }, + new Answers(wanted, answers, byName) + ); + } + + private static String key(Method method) { + return method.getName() + "/" + method.getParameterCount(); + } + + private static final class Answers implements InvocationHandler { + private final Class wanted; + private final Object answers; + private final Map byName; + + Answers(Class wanted, Object answers, Map byName) { + this.wanted = wanted; + this.answers = answers; + this.byName = byName; + } + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + switch (method.getName()) { + case "equals": + if (method.getParameterCount() == 1) + return proxy == args[0]; + break; + case "hashCode": + if (method.getParameterCount() == 0) + return System.identityHashCode(proxy); + break; + case "toString": + if (method.getParameterCount() == 0) + return "Fake" + wanted.getSimpleName(); + break; + default: + break; + } + + Method mine = byName.get(key(method)); + if (mine != null) { + try { + return asKindOf(method.getReturnType(), mine.invoke(answers, args)); + } catch (InvocationTargetException ex) { + throw ex.getCause(); + } + } + + if (method.isDefault()) + return callDefault(proxy, method, args); + + return blank(method.getReturnType()); + } + } + + public static Object callDefault(Object proxy, Method method, Object[] args) throws Throwable { + Class owner = method.getDeclaringClass(); + return MethodHandles + .privateLookupIn(owner, MethodHandles.lookup()) + .unreflectSpecial(method, owner) + .bindTo(proxy) + .invokeWithArguments(args == null ? new Object[0] : args); + } + + private static Object asKindOf(Class wanted, Object answer) { + if (!(answer instanceof Number) || !wanted.isPrimitive()) + return answer; + + Number number = (Number) answer; + if (wanted == float.class) + return number.floatValue(); + if (wanted == double.class) + return number.doubleValue(); + if (wanted == long.class) + return number.longValue(); + if (wanted == int.class) + return number.intValue(); + if (wanted == short.class) + return number.shortValue(); + if (wanted == byte.class) + return number.byteValue(); + return answer; + } + + public static Object blank(Class type) { + if (!type.isPrimitive()) + return null; + if (type == boolean.class) + return false; + if (type == void.class) + return null; + if (type == char.class) + return (char) 0; + if (type == byte.class) + return (byte) 0; + if (type == short.class) + return (short) 0; + if (type == int.class) + return 0; + if (type == long.class) + return 0L; + if (type == float.class) + return 0f; + return 0d; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeClient.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeClient.java new file mode 100644 index 0000000..23f386f --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeClient.java @@ -0,0 +1,301 @@ +package rs117.hd.dev.sceneloader.standalone.client; + +import java.awt.Canvas; +import java.awt.Dimension; +import java.util.Collections; +import java.util.Iterator; +import javax.annotation.Nullable; +import net.runelite.api.BufferProvider; +import net.runelite.api.Client; +import net.runelite.api.GameState; +import net.runelite.api.IndexedObjectSet; +import net.runelite.api.Point; +import net.runelite.api.Scene; +import net.runelite.api.TextureProvider; +import net.runelite.api.WorldView; +import net.runelite.api.hooks.DrawCallbacks; +import rs117.hd.dev.sceneloader.scene.BuiltScene; + +public final class FakeClient { + public static final int ZOOM = 512; + + private final Canvas canvas; + private final TextureProvider textureProvider; + private final FakeObjects objects; + + private final FakeWorldView topLevel = new FakeWorldView(); + private final WorldView worldView = Fake.of(WorldView.class, topLevel); + + private int[] uiPixels = new int[0]; + private int uiWidth, uiHeight; + private final BufferProvider bufferProvider = Fake.of(BufferProvider.class, new Object() { + public int[] getPixels() { + return uiPixels; + } + + public int getWidth() { + return uiWidth; + } + + public int getHeight() { + return uiHeight; + } + }); + + private Thread clientThread; + private DrawCallbacks drawCallbacks; + private GameState gameState = GameState.LOGGED_IN; + private int gpuFlags; + private int gameCycle; + + private final float[] camera = new float[3]; + private float cameraPitch, cameraYaw; + private int plane; + + public FakeClient(Canvas canvas, TextureProvider textureProvider, FakeObjects objects) { + this.canvas = canvas; + this.textureProvider = textureProvider; + this.objects = objects; + } + + public void ownedBy(Thread thread) { + clientThread = thread; + } + + public void setScene(@Nullable BuiltScene scene) { + topLevel.scene = scene; + } + + public void setCamera(float[] position, float yaw, float pitch, int plane) { + System.arraycopy(position, 0, camera, 0, 3); + cameraYaw = yaw; + cameraPitch = pitch; + this.plane = plane; + topLevel.plane = plane; + } + + public void tick() { + gameCycle++; + } + + public void sizeUi(int width, int height) { + if (uiWidth == width && uiHeight == height) + return; + uiWidth = width; + uiHeight = height; + uiPixels = new int[Math.max(1, width * height)]; + } + + public DrawCallbacks getDrawCallbacks() { + return drawCallbacks; + } + + public Canvas getCanvas() { + return canvas; + } + + public int getCanvasWidth() { + return Math.max(1, canvas.getWidth()); + } + + public int getCanvasHeight() { + return Math.max(1, canvas.getHeight()); + } + + public boolean isResized() { + return true; + } + + public boolean isStretchedEnabled() { + return false; + } + + public Dimension getStretchedDimensions() { + return new Dimension(getCanvasWidth(), getCanvasHeight()); + } + + public int getViewportWidth() { + return getCanvasWidth(); + } + + public int getViewportHeight() { + return getCanvasHeight(); + } + + public int getViewportXOffset() { + return 0; + } + + public int getViewportYOffset() { + return 0; + } + + public int getCenterX() { + return getCanvasWidth() / 2; + } + + public int getCenterY() { + return getCanvasHeight() / 2; + } + + public int getScale() { + return ZOOM; + } + + public int get3dZoom() { + return ZOOM; + } + + public int getRasterizer3D_clipNegativeMidX() { + return -getCenterX(); + } + + public int getRasterizer3D_clipNegativeMidY() { + return -getCenterY(); + } + + public int getRasterizer3D_clipMidX2() { + return getCanvasWidth() - getCenterX(); + } + + public int getRasterizer3D_clipMidY2() { + return getCanvasHeight() - getCenterY(); + } + + public BufferProvider getBufferProvider() { + return bufferProvider; + } + + public TextureProvider getTextureProvider() { + return textureProvider; + } + + public boolean isClientThread() { + return Thread.currentThread() == clientThread; + } + + public GameState getGameState() { + return gameState; + } + + public void setGameState(GameState gameState) { + this.gameState = gameState; + } + + public int getGameCycle() { + return gameCycle; + } + + public WorldView getTopLevelWorldView() { + return worldView; + } + + public WorldView getWorldView(int id) { + return id == WorldView.TOPLEVEL || id == -1 ? worldView : null; + } + + public Scene getScene() { + return topLevel.scene; + } + + public int getPlane() { + return plane; + } + + public int[] getMapRegions() { + return topLevel.scene == null ? new int[0] : topLevel.scene.getMapRegions(); + } + + public int getCameraX() { + return (int) camera[0]; + } + + public int getCameraY() { + return (int) camera[1]; + } + + public int getCameraZ() { + return (int) camera[2]; + } + + public float getCameraFocalPointX() { + return camera[0]; + } + + public float getCameraFocalPointY() { + return camera[1]; + } + + public float getCameraFocalPointZ() { + return camera[2]; + } + + public float getCameraFpX() { + return camera[0]; + } + + public float getCameraFpY() { + return camera[1]; + } + + public float getCameraFpZ() { + return camera[2]; + } + + public float getCameraFpPitch() { + return cameraPitch; + } + + public float getCameraFpYaw() { + return cameraYaw; + } + + public int getCameraYaw() { + return (int) (cameraYaw / (2 * Math.PI) * 2048) & 2047; + } + + public int getCameraPitch() { + return (int) (cameraPitch / (2 * Math.PI) * 2048); + } + + public void setDrawCallbacks(DrawCallbacks drawCallbacks) { + this.drawCallbacks = drawCallbacks; + } + + public void setGpuFlags(int gpuFlags) { + this.gpuFlags = gpuFlags; + } + + public int getGpuFlags() { + return gpuFlags; + } + + public Point getMouseCanvasPosition() { + return new Point(-1, -1); + } + + @Nullable + public net.runelite.api.ObjectComposition getObjectDefinition(int id) { + return objects.get(id); + } + + public int getSkyboxColor() { + return 0; + } + + public java.util.List getDBTableRows(int table) { + return java.util.List.of(); + } + + public static final IndexedObjectSet NOBODY = new IndexedObjectSet<>() { + @Override + public Object byIndex(int index) { + return null; + } + + @Override + public Iterator iterator() { + return Collections.emptyIterator(); + } + }; +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeObjects.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeObjects.java new file mode 100644 index 0000000..a694d2b --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeObjects.java @@ -0,0 +1,82 @@ +package rs117.hd.dev.sceneloader.standalone.client; + +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; +import net.runelite.api.ObjectComposition; +import rs117.hd.dev.sceneloader.scene.Definitions; + +public final class FakeObjects { + private final Definitions defs; + private final Map byId = new HashMap<>(); + + public FakeObjects(Definitions defs) { + this.defs = defs; + } + + @Nullable + public ObjectComposition get(int id) { + if (byId.containsKey(id)) + return byId.get(id); + + var definition = defs.object(id); + ObjectComposition composition = definition == null ? null : Fake.of(ObjectComposition.class, new OneObject(id)); + byId.put(id, composition); + return composition; + } + + private final class OneObject { + private final int id; + + OneObject(int id) { + this.id = id; + } + + public int getId() { + return id; + } + + public String getName() { + var definition = defs.object(id); + return definition == null ? "null" : definition.getName(); + } + + public int getSizeX() { + var definition = defs.object(id); + return definition == null ? 1 : definition.getSizeX(); + } + + public int getSizeY() { + var definition = defs.object(id); + return definition == null ? 1 : definition.getSizeY(); + } + + public int getVarbitId() { + var definition = defs.object(id); + return definition == null ? -1 : definition.getVarbitID(); + } + + public int getVarPlayerId() { + var definition = defs.object(id); + return definition == null ? -1 : definition.getVarpID(); + } + + @Nullable + public int[] getImpostorIds() { + var definition = defs.object(id); + return definition == null ? null : definition.getConfigChangeDest(); + } + + @Nullable + public ObjectComposition getImpostor() { + int[] forms = getImpostorIds(); + if (forms == null) + return null; + + for (int form : forms) + if (form != -1) + return FakeObjects.this.get(form); + return null; + } + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeWorldView.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeWorldView.java new file mode 100644 index 0000000..f9fe21b --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/client/FakeWorldView.java @@ -0,0 +1,60 @@ +package rs117.hd.dev.sceneloader.standalone.client; + +import javax.annotation.Nullable; +import net.runelite.api.IndexedObjectSet; +import net.runelite.api.Scene; +import net.runelite.api.WorldView; +import rs117.hd.dev.sceneloader.scene.BuiltScene; + +import static net.runelite.api.Constants.EXTENDED_SCENE_SIZE; + +public final class FakeWorldView { + @Nullable + BuiltScene scene; + int plane; + + public int getId() { + return WorldView.TOPLEVEL; + } + + public boolean isTopLevel() { + return true; + } + + @Nullable + public Scene getScene() { + return scene; + } + + public int getPlane() { + return plane; + } + + public int getSizeX() { + return EXTENDED_SCENE_SIZE; + } + + public int getSizeY() { + return EXTENDED_SCENE_SIZE; + } + + public int getBaseX() { + return scene == null ? 0 : scene.getBaseX(); + } + + public int getBaseY() { + return scene == null ? 0 : scene.getBaseY(); + } + + public IndexedObjectSet players() { + return FakeClient.NOBODY; + } + + public IndexedObjectSet npcs() { + return FakeClient.NOBODY; + } + + public IndexedObjectSet worldEntities() { + return FakeClient.NOBODY; + } +} diff --git a/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/headless/HdBenchmark.java b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/headless/HdBenchmark.java new file mode 100644 index 0000000..9df249e --- /dev/null +++ b/Tools/Dev/java/rs117/hd/dev/sceneloader/standalone/headless/HdBenchmark.java @@ -0,0 +1,457 @@ +package rs117.hd.dev.sceneloader.standalone.headless; + +import java.awt.BorderLayout; +import java.awt.Canvas; +import java.awt.Dimension; +import java.awt.GraphicsEnvironment; +import java.io.BufferedWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import javax.annotation.Nullable; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; +import lombok.extern.slf4j.Slf4j; +import rs117.hd.dev.sceneloader.scene.BuiltScene; +import rs117.hd.dev.sceneloader.scene.Definitions; +import rs117.hd.dev.sceneloader.scene.SceneBuilder; +import rs117.hd.dev.sceneloader.scene.VariantOptions; +import rs117.hd.overlays.FrameTimings; +import rs117.hd.overlays.Timer; + +import static net.runelite.api.Perspective.LOCAL_TILE_SIZE; +import rs117.hd.dev.sceneloader.standalone.FlyCamera; +import rs117.hd.dev.sceneloader.standalone.HdRuntime; +import rs117.hd.dev.sceneloader.standalone.HdSettings; +import rs117.hd.dev.sceneloader.standalone.Textures; + +@Slf4j +public final class HdBenchmark { + private static final String USAGE = + "Usage: HdBenchmark [--x 3222] [--y 3218] [--chunks 0] [--region 12850] [--plane 0] [--roofs]\n" + + " [--cache ] [--width 1280] [--height 800] [--config name=value,...]\n" + + " [--out ] [--warmup 3] [--spin 12] [--hold 3]\n" + + " [--above 2400] [--pitch 50] [--hidden] [--name