diff options
| author | Eugen Wissner <belka@caraus.de> | 2026-01-18 11:32:24 +0100 |
|---|---|---|
| committer | Eugen Wissner <belka@caraus.de> | 2026-01-18 11:32:24 +0100 |
| commit | 2499f8471ca63ad5c1a6abf21de60867e1f96289 (patch) | |
| tree | df76977b65999829fc0ebca7c24c23f357299f9a /Занимательное программирование/4/5_3d/src/main/java/net/caraus | |
| parent | b7a63ee8956d977ad3364a1d8f509e307232a22a (diff) | |
| download | book-exercises-2499f8471ca63ad5c1a6abf21de60867e1f96289.tar.gz | |
Закончил 4-ю главу
Diffstat (limited to 'Занимательное программирование/4/5_3d/src/main/java/net/caraus')
9 files changed, 801 insertions, 0 deletions
diff --git a/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/KruskalMaze.java b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/KruskalMaze.java new file mode 100644 index 0000000..513a998 --- /dev/null +++ b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/KruskalMaze.java @@ -0,0 +1,124 @@ +package net.caraus.labyrinth; + +import java.util.ArrayList; +import java.util.Random; + +public final class KruskalMaze { + private Maze theMaze; + private int[][] mark; + + public KruskalMaze(int width, int height) { + this.theMaze = new Maze(width, height); + } + + private void breakWall(Wall wall) { + if (wall.delta().x() == -1) { + this.theMaze.at(wall.xy()).leftWall(false); + } else if (wall.delta().x() == 1) { + this.theMaze.at(wall.xy().x() + 1, wall.xy().y()).leftWall(false); + } else if (wall.delta().y() == -1) { + this.theMaze.at(wall.xy()).upWall(false); + } else { + this.theMaze.at(wall.xy().x(), wall.xy().y() + 1).upWall(false); + } + } + + public boolean isConnected(Point start, Point finish) { + this.mark = new int[this.theMaze.width()][this.theMaze.height()]; // Метки локаций. + + for (int x = 0; x < this.theMaze.width(); ++x) { + for (int y = 0; y < this.theMaze.height(); ++y) { + this.mark[x][y] = 0; + } + } + this.mark[start.x()][start.y()] = 1; + + return solve(start, finish); + } + + private boolean solve(Point start, Point finish) { + // Используем алгоритм волновой трассировки. + int n = 1; + + // Локации со следующим N. + ArrayList<Point> locations = new ArrayList<>(); + locations.add(start); + + do { + ArrayList<Point> nextLocations = new ArrayList<>(); + // Посетить локации, помеченные числом N. + for (var nLocation : locations) { + // Просмотр соседей. + for (int i = 0; i < 4; ++i) { + var neighbour = new Point(nLocation.x() + Maze.DX[i], nLocation.y() + Maze.DY[i]); + + if (this.theMaze.canGo(nLocation, i) && this.mark[neighbour.x()][neighbour.y()] == 0) { + // Локация доступна и помечена нулем. + // Есть шанс найти решения. + nextLocations.add(neighbour); + this.mark[neighbour.x()][neighbour.y()] = n + 1; + + if (neighbour.x() == finish.x() && neighbour.y() == finish.y()) { + return true; + } + } + } + } + locations = nextLocations; + ++n; + } while (!locations.isEmpty()); + + return false; + } + + public Maze generate() { + final var wallCount = (this.theMaze.width() - 1) * this.theMaze.height() + + (this.theMaze.height() - 1) * this.theMaze.width(); + ArrayList<Wall> walls = new ArrayList<>(wallCount); + ArrayList<Double> temp = new ArrayList<>(wallCount); + var random = new Random(); + + // Заполнение массива Temp случайными числами. + for (int i = 0; i < wallCount; ++i) { + temp.add(random.nextDouble()); + } + // Заполнение массива стен. + // Сначала все горизонтальные. + for (var i = 1; i < this.theMaze.width(); ++i) { + for (var j = 0; j < this.theMaze.height(); ++j) { + walls.add(new Wall(new Point(i, j), new Point(-1, 0))); + } + } + // Затем все вертикальные. + for (var i = 0; i < this.theMaze.width(); ++i) { + for (var j = 1; j < this.theMaze.height(); ++j) { + walls.add(new Wall(new Point(i, j), new Point(0, -1))); + } + } + for (var i = 0; i < wallCount; ++i) { + for (var j = i; j < wallCount; ++j) { + // Перемешиваем массив стен. + if (temp.get(i) > temp.get(j)) { + var tempr = temp.get(i); + temp.set(i, temp.get(j)); + temp.set(j, tempr); + + var tempw = walls.get(i); + walls.set(i, walls.get(j)); + walls.set(j, tempw); + } + } + } + var locations = this.theMaze.width() * this.theMaze.height(); + int i = 0; + while (locations > 1) { + var curWall = walls.get(i); + ++i; + if (!isConnected(curWall.xy(), curWall.end())) { + breakWall(curWall); + --locations; + } + } + return this.theMaze; + } +} diff --git a/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Location.java b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Location.java new file mode 100644 index 0000000..97077be --- /dev/null +++ b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Location.java @@ -0,0 +1,32 @@ +package net.caraus.labyrinth; + +public class Location { + private boolean leftWall; + private boolean upWall; + + Location(boolean leftWall, boolean upWall) { + this.leftWall = leftWall; + this.upWall = upWall; + } + + public boolean leftWall() { + return this.leftWall; + } + + public void leftWall(boolean leftWall) { + this.leftWall = leftWall; + } + + public boolean upWall() { + return this.upWall; + } + + public void upWall(boolean upWall) { + this.upWall = upWall; + } + + @Override + public String toString() { + return String.format("(%s, %s)", leftWall, upWall); + } +} diff --git a/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Main.java b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Main.java new file mode 100644 index 0000000..35a6c01 --- /dev/null +++ b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Main.java @@ -0,0 +1,167 @@ +package net.caraus.labyrinth; + +import com.badlogic.gdx.ApplicationListener; +import com.badlogic.gdx.Gdx; +import com.badlogic.gdx.graphics.Color; +import com.badlogic.gdx.graphics.GL32; +import com.badlogic.gdx.graphics.PerspectiveCamera; +import com.badlogic.gdx.graphics.VertexAttributes.Usage; +import com.badlogic.gdx.graphics.g3d.Material; +import com.badlogic.gdx.graphics.g3d.Model; +import com.badlogic.gdx.graphics.g3d.ModelBatch; +import com.badlogic.gdx.graphics.g3d.ModelInstance; +import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute; +import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; +import com.badlogic.gdx.graphics.g3d.utils.MeshPartBuilder; +import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; +import com.badlogic.gdx.graphics.glutils.ShapeRenderer; +import static com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType; +import com.badlogic.gdx.math.Vector3; +import com.badlogic.gdx.utils.ScreenUtils; + +public class Main implements ApplicationListener { + + public ModelBatch modelBatch; + public Model model; + public ModelInstance instance; + public MazeInputProcessor camController; + public ShapeRenderer shapeRenderer; + public Maze maze; + + private static final float WALL_SIZE = 5; + + @Override + public void create() { + this.modelBatch = new ModelBatch(); + this.shapeRenderer = new ShapeRenderer(); + var cam = new PerspectiveCamera(67, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + + cam.position.set(0f, 0f, 0f); + cam.lookAt(0, WALL_SIZE, 0); + cam.near = 1f; + cam.far = 300f; + cam.update(); + + this.maze = new KruskalMaze(15, 9).generate(); + this.camController = new MazeInputProcessor(this.maze, cam, WALL_SIZE); + Gdx.input.setInputProcessor(camController); + + ModelBuilder worldBuilder = new ModelBuilder(); + worldBuilder.begin(); + + for (var x = 0; x < this.maze.width(); ++x) { + for (var y = 0; y < this.maze.height(); ++y) { + buildLocation(worldBuilder, x, y); + } + buildLocation(worldBuilder, new Location(false, true), + new Vector3(x * WALL_SIZE * 2, this.maze.height() * WALL_SIZE * 2, 0), + String.format("lx%dy%d", x, this.maze.height())); + } + for (var y = 0; y < this.maze.height(); ++y) { + buildLocation(worldBuilder, new Location(true, false), + new Vector3(this.maze.width() * WALL_SIZE * 2, y * WALL_SIZE * 2, 0), + String.format("lx%dy%d", this.maze.width(), y)); + } + buildFloor(worldBuilder); + this.model = worldBuilder.end(); + this.instance = new ModelInstance(this.model); + } + + private static Vector3 makeTranslation(int x, int y) { + return new Vector3(x * WALL_SIZE * 2, y * WALL_SIZE * 2, 0); + } + + // Пол. + private void buildFloor(ModelBuilder worldBuilder) { + MeshPartBuilder meshBuilder = worldBuilder.part("floor", + GL32.GL_TRIANGLES, Usage.Position | Usage.Normal, + new Material(ColorAttribute.createDiffuse(Color.ORANGE))); + + var farX = -WALL_SIZE + this.maze.width() * WALL_SIZE * 2; + var farY = -WALL_SIZE + this.maze.height() * WALL_SIZE * 2; + + meshBuilder.rect(new MeshPartBuilder.VertexInfo().setPos(-WALL_SIZE, -WALL_SIZE, -WALL_SIZE), + new MeshPartBuilder.VertexInfo().setPos(farX, -WALL_SIZE, -WALL_SIZE), + new MeshPartBuilder.VertexInfo().setPos(farX, farY, -WALL_SIZE), + new MeshPartBuilder.VertexInfo().setPos(-WALL_SIZE, farY, -WALL_SIZE)); + } + + private static void buildLocation(ModelBuilder worldBuilder, + Location builtLocation, Vector3 translation, String partName) { + var corner00 = new Vector3(); + var corner10 = new Vector3(); + var corner11 = new Vector3(); + var corner01 = new Vector3(); + + MeshPartBuilder meshBuilder = worldBuilder.part(partName, + GL32.GL_TRIANGLES, Usage.Position | Usage.Normal, new Material(new BlendingAttribute(0.9f))); + + if (builtLocation.leftWall()) { + meshBuilder.rect(corner00.set(-WALL_SIZE, -WALL_SIZE, -WALL_SIZE).add(translation), + corner10.set(-WALL_SIZE, WALL_SIZE, -WALL_SIZE).add(translation), + corner11.set(-WALL_SIZE, WALL_SIZE, WALL_SIZE).add(translation), + corner01.set(-WALL_SIZE, -WALL_SIZE, WALL_SIZE).add(translation), + null); + meshBuilder.rect(corner01.set(-WALL_SIZE, -WALL_SIZE, WALL_SIZE).add(translation), + corner11.set(-WALL_SIZE, WALL_SIZE, WALL_SIZE).add(translation), + corner10.set(-WALL_SIZE, WALL_SIZE, -WALL_SIZE).add(translation), + corner00.set(-WALL_SIZE, -WALL_SIZE, -WALL_SIZE).add(translation), + null); + } + if (builtLocation.upWall()) { + meshBuilder.rect(corner00.set(-WALL_SIZE, -WALL_SIZE, -WALL_SIZE).add(translation), + corner10.set(WALL_SIZE, -WALL_SIZE, -WALL_SIZE).add(translation), + corner11.set(WALL_SIZE, -WALL_SIZE, WALL_SIZE).add(translation), + corner01.set(-WALL_SIZE, -WALL_SIZE, WALL_SIZE).add(translation), + null); + meshBuilder.rect(corner01.set(-WALL_SIZE, -WALL_SIZE, WALL_SIZE).add(translation), + corner11.set(WALL_SIZE, -WALL_SIZE, WALL_SIZE).add(translation), + corner10.set(WALL_SIZE, -WALL_SIZE, -WALL_SIZE).add(translation), + corner00.set(-WALL_SIZE, -WALL_SIZE, -WALL_SIZE).add(translation), + null); + } + } + + private void buildLocation(ModelBuilder worldBuilder, int x, int y) { + var translation = new Vector3(x * WALL_SIZE * 2, y * WALL_SIZE * 2, 0); + + buildLocation(worldBuilder, this.maze.at(x, y), translation, String.format("lx%dy%d", x, y)); + } + + @Override + public void render() { + this.camController.update(); + + Gdx.gl.glClear(GL32.GL_COLOR_BUFFER_BIT | GL32.GL_DEPTH_BUFFER_BIT); + ScreenUtils.clear(0.15f, 0.15f, 0.2f, 1f); + + Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); + this.modelBatch.begin(this.camController.getCamera()); + this.modelBatch.render(this.instance); + this.modelBatch.end(); + + this.shapeRenderer.begin(ShapeType.Line); + this.shapeRenderer.setColor(Color.BLUE); + this.maze.draw(this.shapeRenderer); + this.shapeRenderer.end(); + } + + @Override + public void dispose() { + this.modelBatch.dispose(); + this.model.dispose(); + this.shapeRenderer.dispose(); + } + + @Override + public void resume() { + } + + @Override + public void resize(int width, int height) { + } + + @Override + public void pause() { + } +} diff --git a/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Maze.java b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Maze.java new file mode 100644 index 0000000..828c1d8 --- /dev/null +++ b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Maze.java @@ -0,0 +1,99 @@ +package net.caraus.labyrinth; + +import com.badlogic.gdx.graphics.glutils.ShapeRenderer; +import com.badlogic.gdx.math.Vector2; + +import java.io.BufferedReader; +import java.io.Reader; +import java.io.IOException; + +public final class Maze { + private Location[][] maze; + + public static final int[] DX = {1, 0, -1, 0}; + public static final int[] DY = {0, -1, 0, 1}; + public static final float CELL_SIZE = 30.0f; + + public Maze(Reader inputReader) throws IOException { + BufferedReader reader = new BufferedReader(inputReader); + + String[] inputPair = reader.readLine().split(" "); + var width = Integer.parseInt(inputPair[0]); + var height = Integer.parseInt(inputPair[1]); + + this.maze = new Location[width + 1][height + 1]; + + for (var y = 0; y <= height; ++y) { + for (var x = 0; x <= width; ++x) { + if (y == height || x == width) { + this.maze[x][y] = new Location(true, true); + } else { + inputPair = reader.readLine().split(" "); + this.maze[x][y] = new Location(inputPair[1].equals("1"), inputPair[0].equals("1")); + } + } + } + } + + public Maze(int width, int height) { + this.maze = new Location[width + 1][height + 1]; + + // Все стены изначально существуют. + for (int x = 0; x <= width; ++x) { + for (int y = 0; y <= height; ++y) { + this.maze[x][y] = new Location(true, true); + } + } + } + + public int width() { + return this.maze == null ? 0 : this.maze.length - 1; + } + + public int height() { + return this.maze == null ? 0 : this.maze[0].length - 1; + } + + public void draw(ShapeRenderer shape) { + for (var x = 0; x < width(); ++x) { + for (var y = 0; y < height(); ++y) { + var start = new Vector2((x + 1) * CELL_SIZE, (height() - y + 1) * CELL_SIZE); + + if (this.maze[x][y].upWall()) { + var end = new Vector2(start).add(CELL_SIZE, 0); + + shape.line(start, end); + } + if (this.maze[x][y].leftWall()) { + var end = new Vector2(start).sub(0, CELL_SIZE); + + shape.line(start, end); + } + } + } + // Рисуем нижнюю и правую стены. + var edge = new Vector2(CELL_SIZE * (width() + 1), CELL_SIZE); + shape.line(new Vector2(CELL_SIZE, CELL_SIZE), edge); + shape.line(new Vector2(edge).add(0, height() * CELL_SIZE), edge); + } + + public boolean canGo(Point xy, int deltaIndex) { + if (DX[deltaIndex] == -1) { + return !this.maze[xy.x()][xy.y()].leftWall(); + } else if (DX[deltaIndex] == 1) { + return !this.maze[xy.x() + 1][xy.y()].leftWall(); + } else if (DY[deltaIndex] == -1) { + return !this.maze[xy.x()][xy.y()].upWall(); + } else { + return !this.maze[xy.x()][xy.y() + 1].upWall(); + } + } + + public Location at(int x, int y) { + return this.maze[x][y]; + } + + public Location at(Point xy) { + return at(xy.x(), xy.y()); + } +} diff --git a/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/MazeInputProcessor.java b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/MazeInputProcessor.java new file mode 100644 index 0000000..7303829 --- /dev/null +++ b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/MazeInputProcessor.java @@ -0,0 +1,111 @@ +package net.caraus.labyrinth; + +import com.badlogic.gdx.InputProcessor; +import static com.badlogic.gdx.Input.Keys; +import com.badlogic.gdx.graphics.PerspectiveCamera; +import com.badlogic.gdx.math.Vector3; + +public final class MazeInputProcessor implements InputProcessor { + + public PerspectiveCamera cam; + private short direction = 3; + private Point position = new Point(0, 0); + private final float step; + private Maze maze; + + public MazeInputProcessor(Maze maze, PerspectiveCamera cam, float wallSize) { + this.cam = cam; + this.step = wallSize * 2; + this.maze = maze; + } + + public void update() { + this.cam.update(); + } + + public PerspectiveCamera getCamera() { + return this.cam; + } + + @Override + public boolean keyDown(int keycode) { + if (keycode == Keys.RIGHT) { + turnRight(); + return true; + } else if (keycode == Keys.LEFT) { + turnLeft(); + return true; + } else if (keycode == Keys.UP) { + stepForward(); + } + return false; + } + + private void stepForward() { + if (!this.maze.canGo(this.position, this.direction)) { + return; + } + this.position = new Point(this.position.x() + Maze.DX[this.direction], + this.position.y() + Maze.DY[this.direction]); + this.cam.position.set(this.position.x() * this.step, + this.position.y() * this.step, 0.0f); + } + + private void turnRight() { + if (this.direction >= 3) { + this.direction = 0; + } else { + ++this.direction; + } + this.cam.rotate(90, 0, 0, -1); + } + + private void turnLeft() { + if (this.direction <= 0) { + this.direction = 3; + } else { + --this.direction; + } + this.cam.rotate(90, 0, 0, 1); + } + + @Override + public boolean keyUp(int keycode) { + return false; + } + + @Override + public boolean keyTyped(char character) { + return false; + } + + @Override + public boolean touchDown(int x, int y, int pointer, int button) { + return false; + } + + @Override + public boolean touchUp(int x, int y, int pointer, int button) { + return false; + } + + @Override + public boolean touchDragged(int x, int y, int pointer) { + return false; + } + + @Override + public boolean touchCancelled(int x, int y, int pointer, int button) { + return false; + } + + @Override + public boolean mouseMoved(int x, int y) { + return false; + } + + @Override + public boolean scrolled(float amountX, float amountY) { + return false; + } +} diff --git a/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Point.java b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Point.java new file mode 100644 index 0000000..6f70d4c --- /dev/null +++ b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Point.java @@ -0,0 +1,4 @@ +package net.caraus.labyrinth; + +public record Point(int x, int y) { +} diff --git a/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Wall.java b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Wall.java new file mode 100644 index 0000000..e8615bd --- /dev/null +++ b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/Wall.java @@ -0,0 +1,15 @@ +package net.caraus.labyrinth; + +public record Wall(Point xy, Point delta) { + public int x() { + return this.xy.x() + this.delta.x(); + } + + public int y() { + return this.xy.y() + this.delta.y(); + } + + public Point end() { + return new Point(x(), y()); + } +} diff --git a/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/lwjgl3/Lwjgl3Launcher.java b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/lwjgl3/Lwjgl3Launcher.java new file mode 100644 index 0000000..cbdfa6c --- /dev/null +++ b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/lwjgl3/Lwjgl3Launcher.java @@ -0,0 +1,45 @@ +package net.caraus.labyrinth.lwjgl3; + +import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application; +import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration; +import net.caraus.labyrinth.Main; + +/** Launches the desktop (LWJGL3) application. */ +public class Lwjgl3Launcher { + public static void main(String[] args) { + if (StartupHelper.startNewJvmIfRequired()) return; // This handles macOS support and helps on Windows. + createApplication(); + } + + private static Lwjgl3Application createApplication() { + return new Lwjgl3Application(new Main(), getDefaultConfiguration()); + } + + private static Lwjgl3ApplicationConfiguration getDefaultConfiguration() { + Lwjgl3ApplicationConfiguration configuration = new Lwjgl3ApplicationConfiguration(); + configuration.setTitle("Labyrinth"); + //// Vsync limits the frames per second to what your hardware can display, and helps eliminate + //// screen tearing. This setting doesn't always work on Linux, so the line after is a safeguard. + configuration.useVsync(true); + //// Limits FPS to the refresh rate of the currently active monitor, plus 1 to try to match fractional + //// refresh rates. The Vsync setting above should limit the actual FPS to match the monitor. + configuration.setForegroundFPS(Lwjgl3ApplicationConfiguration.getDisplayMode().refreshRate + 1); + //// If you remove the above line and set Vsync to false, you can get unlimited FPS, which can be + //// useful for testing performance, but can also be very stressful to some hardware. + //// You may also need to configure GPU drivers to fully disable Vsync; this can cause screen tearing. + + configuration.setWindowedMode(1366, 768); + //// You can change these files; they are in lwjgl3/src/main/resources/ . + //// They can also be loaded from the root of assets/ . + configuration.setWindowIcon("libgdx128.png", "libgdx64.png", "libgdx32.png", "libgdx16.png"); + + //// This should improve compatibility with Windows machines with buggy OpenGL drivers, Macs + //// with Apple Silicon that have to emulate compatibility with OpenGL anyway, and more. + //// This uses the dependency `com.badlogicgames.gdx:gdx-lwjgl3-angle` to function. + //// You can choose to remove the following line and the mentioned dependency if you want; they + //// are not intended for games that use GL30 (which is compatibility with OpenGL ES 3.0). + configuration.setOpenGLEmulation(Lwjgl3ApplicationConfiguration.GLEmulation.ANGLE_GLES20, 0, 0); + + return configuration; + } +} diff --git a/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/lwjgl3/StartupHelper.java b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/lwjgl3/StartupHelper.java new file mode 100644 index 0000000..b62cf6f --- /dev/null +++ b/Занимательное программирование/4/5_3d/src/main/java/net/caraus/labyrinth/lwjgl3/StartupHelper.java @@ -0,0 +1,204 @@ +/* + * Copyright 2020 damios + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +//Note, the above license and copyright applies to this file only. + +package net.caraus.labyrinth.lwjgl3; + +import com.badlogic.gdx.Version; +import com.badlogic.gdx.backends.lwjgl3.Lwjgl3NativesLoader; +import org.lwjgl.system.macosx.LibC; +import org.lwjgl.system.macosx.ObjCRuntime; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.lang.management.ManagementFactory; +import java.util.ArrayList; + +import static org.lwjgl.system.JNI.invokePPP; +import static org.lwjgl.system.JNI.invokePPZ; +import static org.lwjgl.system.macosx.ObjCRuntime.objc_getClass; +import static org.lwjgl.system.macosx.ObjCRuntime.sel_getUid; + +/** + * Adds some utilities to ensure that the JVM was started with the + * {@code -XstartOnFirstThread} argument, which is required on macOS for LWJGL 3 + * to function. Also helps on Windows when users have names with characters from + * outside the Latin alphabet, a common cause of startup crashes. + * <br> + * <a href="https://jvm-gaming.org/t/starting-jvm-on-mac-with-xstartonfirstthread-programmatically/57547">Based on this java-gaming.org post by kappa</a> + * @author damios + */ +public class StartupHelper { + + private static final String JVM_RESTARTED_ARG = "jvmIsRestarted"; + + private StartupHelper() { + throw new UnsupportedOperationException(); + } + + /** + * Starts a new JVM if the application was started on macOS without the + * {@code -XstartOnFirstThread} argument. This also includes some code for + * Windows, for the case where the user's home directory includes certain + * non-Latin-alphabet characters (without this code, most LWJGL3 apps fail + * immediately for those users). Returns whether a new JVM was started and + * thus no code should be executed. + * <p> + * <u>Usage:</u> + * + * <pre><code> + * public static void main(String... args) { + * if (StartupHelper.startNewJvmIfRequired(true)) return; // This handles macOS support and helps on Windows. + * // after this is the actual main method code + * } + * </code></pre> + * + * @param redirectOutput + * whether the output of the new JVM should be rerouted to the + * old JVM, so it can be accessed in the same place; keeps the + * old JVM running if enabled + * @return whether a new JVM was started and thus no code should be executed + * in this one + */ + public static boolean startNewJvmIfRequired(boolean redirectOutput) { + String osName = System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT); + if (!osName.contains("mac")) { + if (osName.contains("windows")) { +// Here, we are trying to work around an issue with how LWJGL3 loads its extracted .dll files. +// By default, LWJGL3 extracts to the directory specified by "java.io.tmpdir", which is usually the user's home. +// If the user's name has non-ASCII (or some non-alphanumeric) characters in it, that would fail. +// By extracting to the relevant "ProgramData" folder, which is usually "C:\ProgramData", we avoid this. +// We also temporarily change the "user.name" property to one without any chars that would be invalid. +// We revert our changes immediately after loading LWJGL3 natives. + String programData = System.getenv("ProgramData"); + if(programData == null) programData = "C:\\Temp\\"; // if ProgramData isn't set, try some fallback. + String prevTmpDir = System.getProperty("java.io.tmpdir", programData); + String prevUser = System.getProperty("user.name", "libGDX_User"); + System.setProperty("java.io.tmpdir", programData + "/libGDX-temp"); + System.setProperty("user.name", ("User_" + prevUser.hashCode() + "_GDX" + Version.VERSION).replace('.', '_')); + Lwjgl3NativesLoader.load(); + System.setProperty("java.io.tmpdir", prevTmpDir); + System.setProperty("user.name", prevUser); + } + return false; + } + + // There is no need for -XstartOnFirstThread on Graal native image + if (!System.getProperty("org.graalvm.nativeimage.imagecode", "").isEmpty()) { + return false; + } + + // Checks if we are already on the main thread, such as from running via Construo. + long objc_msgSend = ObjCRuntime.getLibrary().getFunctionAddress("objc_msgSend"); + long NSThread = objc_getClass("NSThread"); + long currentThread = invokePPP(NSThread, sel_getUid("currentThread"), objc_msgSend); + boolean isMainThread = invokePPZ(currentThread, sel_getUid("isMainThread"), objc_msgSend); + if(isMainThread) return false; + + long pid = LibC.getpid(); + + // check whether -XstartOnFirstThread is enabled + if ("1".equals(System.getenv("JAVA_STARTED_ON_FIRST_THREAD_" + pid))) { + return false; + } + + // check whether the JVM was previously restarted + // avoids looping, but most certainly leads to a crash + if ("true".equals(System.getProperty(JVM_RESTARTED_ARG))) { + System.err.println( + "There was a problem evaluating whether the JVM was started with the -XstartOnFirstThread argument."); + return false; + } + + // Restart the JVM with -XstartOnFirstThread + ArrayList<String> jvmArgs = new ArrayList<>(); + String separator = System.getProperty("file.separator", "/"); + // The following line is used assuming you target Java 8, the minimum for LWJGL3. + String javaExecPath = System.getProperty("java.home") + separator + "bin" + separator + "java"; + // If targeting Java 9 or higher, you could use the following instead of the above line: + //String javaExecPath = ProcessHandle.current().info().command().orElseThrow(); + + if (!(new File(javaExecPath)).exists()) { + System.err.println( + "A Java installation could not be found. If you are distributing this app with a bundled JRE, be sure to set the -XstartOnFirstThread argument manually!"); + return false; + } + + jvmArgs.add(javaExecPath); + jvmArgs.add("-XstartOnFirstThread"); + jvmArgs.add("-D" + JVM_RESTARTED_ARG + "=true"); + jvmArgs.addAll(ManagementFactory.getRuntimeMXBean().getInputArguments()); + jvmArgs.add("-cp"); + jvmArgs.add(System.getProperty("java.class.path")); + String mainClass = System.getenv("JAVA_MAIN_CLASS_" + pid); + if (mainClass == null) { + StackTraceElement[] trace = Thread.currentThread().getStackTrace(); + if (trace.length > 0) { + mainClass = trace[trace.length - 1].getClassName(); + } else { + System.err.println("The main class could not be determined."); + return false; + } + } + jvmArgs.add(mainClass); + + try { + if (!redirectOutput) { + ProcessBuilder processBuilder = new ProcessBuilder(jvmArgs); + processBuilder.start(); + } else { + Process process = (new ProcessBuilder(jvmArgs)) + .redirectErrorStream(true).start(); + BufferedReader processOutput = new BufferedReader( + new InputStreamReader(process.getInputStream())); + String line; + + while ((line = processOutput.readLine()) != null) { + System.out.println(line); + } + + process.waitFor(); + } + } catch (Exception e) { + System.err.println("There was a problem restarting the JVM"); + e.printStackTrace(); + } + + return true; + } + + /** + * Starts a new JVM if the application was started on macOS without the + * {@code -XstartOnFirstThread} argument. Returns whether a new JVM was + * started and thus no code should be executed. Redirects the output of the + * new JVM to the old one. + * <p> + * <u>Usage:</u> + * + * <pre> + * public static void main(String... args) { + * if (StartupHelper.startNewJvmIfRequired()) return; // This handles macOS support and helps on Windows. + * // the actual main method code + * } + * </pre> + * + * @return whether a new JVM was started and thus no code should be executed + * in this one + */ + public static boolean startNewJvmIfRequired() { + return startNewJvmIfRequired(true); + } +} |
