Compare commits

..

31 Commits

Author SHA1 Message Date
be82d76bba Fix offset when camera moving (offset with camera rotating remains) 2023-10-06 16:04:26 +02:00
8b8497b53b Mousepicker with offset in selection 2023-10-06 15:33:52 +02:00
fb3d4e3685 Partial Intersection Calculation 2023-10-06 11:44:25 +02:00
3d4d0485f3 Updated Mousepicker 2023-10-05 16:39:59 +02:00
ed6a4e8472 Implement MousePicker 2023-10-05 15:55:23 +02:00
44514f87e5 Merge pull request 'finished game-engine-terrain-generation' (#2) from game-engine-terrain-generation into game-engine
Reviewed-on: Sebastian/Dicewars#2
2023-10-05 14:00:28 +02:00
354c5ce8be Apply Noise generation 2023-10-05 13:32:13 +02:00
db7c533206 Assign to each TerrainTile a random color 2023-10-05 12:33:47 +02:00
9e09df3cf8 Fix wierd looking terrain 2023-10-05 12:14:06 +02:00
c5ca9f435e Wierd looking terrain 2023-10-04 09:55:09 +02:00
88099c41c0 Load Hexagonmodel directly in loader 2023-10-04 08:57:52 +02:00
d11e58c998 Remove usement of unused entity dragon (remaining from tut) 2023-10-04 08:55:13 +02:00
Sebastian
466a15f160 Generate single Hexagon 2023-08-25 07:20:04 +02:00
Sebastian
e0afd6e93a Fix gaps in TerrainTiles 2023-08-24 20:08:41 +02:00
Sebastian
4932b3f6a0 Generating Terrain with TerrainTiles 2023-08-24 17:30:57 +02:00
Sebastian
ba47896d88 Set size of terrain and initialize camera ad midpoint of terrain 2023-08-24 15:57:12 +02:00
Sebastian
98b6208c74 Implementing Rotation of the camera by mouse input 2023-08-24 15:19:32 +02:00
Sebastian
7acf9fd703 Implementing Zooming 2023-08-24 15:04:35 +02:00
Sebastian
7edcda998c Render terrains 2023-08-24 14:31:46 +02:00
Sebastian
5912ac5a7c Renderer optimizations 2023-08-11 20:28:43 +02:00
Sebastian
bf2b169563 Implement Backface Culling 2023-08-11 20:09:20 +02:00
Sebastian
ce75297105 Ambient Lightning 2023-08-11 20:06:38 +02:00
Sebastian
666d3e1ea2 Per Pixel Lightning 2023-08-11 20:04:01 +02:00
Sebastian
9b5adeab00 Load OBJ models 2023-08-11 19:44:31 +02:00
Sebastian
c7c1bbe0af Include Cameramovement 2023-08-11 17:32:26 +02:00
Sebastian
0383c43675 Transform rectangle 2023-08-11 16:49:59 +02:00
Sebastian
43f6d9535e Render a texture on a quad 2023-08-06 15:43:51 +02:00
Sebastian
8d76c8bcf0 Render rectangle with color interpolation 2023-08-04 08:39:05 +02:00
Sebastian
76e268e9ed Improve Rendering Performance 2023-08-04 08:10:38 +02:00
Sebastian
1303d0d05e Render white rectangle 2023-08-04 07:57:24 +02:00
Sebastian
d989edee91 Initialize GameEngine (create empty window) 2023-08-03 21:20:50 +02:00
47 changed files with 4890 additions and 0 deletions

39
.gitignore vendored
View File

@ -100,6 +100,45 @@ fabric.properties
# Editor-based Rest Client # Editor-based Rest Client
.idea/httpRequests .idea/httpRequests
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
client/.idea/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
# Android studio 3.1+ serialized cache file # Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser .idea/caches/build_file_checksums.ser

144
client/pom.xml Normal file
View File

@ -0,0 +1,144 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>client</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<lwjgl.version>3.3.2</lwjgl.version>
</properties>
<profiles>
<profile>
<id>lwjgl-natives-linux-amd64</id>
<activation>
<os>
<family>unix</family>
<arch>amd64</arch>
</os>
</activation>
<properties>
<lwjgl.natives>natives-linux</lwjgl.natives>
</properties>
</profile>
<profile>
<id>lwjgl-natives-windows-amd64</id>
<activation>
<os>
<family>windows</family>
<arch>amd64</arch>
</os>
</activation>
<properties>
<lwjgl.natives>natives-windows</lwjgl.natives>
</properties>
</profile>
</profiles>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-bom</artifactId>
<version>${lwjgl.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-assimp</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-bgfx</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-nanovg</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-nuklear</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-openal</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-par</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-stb</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-bgfx</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-nanovg</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-nuklear</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-openal</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-par</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-stb</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
</dependencies>
</project>

BIN
client/res/grass.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 MiB

BIN
client/res/hexagon.blend Normal file

Binary file not shown.

BIN
client/res/white.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

View File

@ -0,0 +1,15 @@
package core;
import core.engine.Engine;
public class Main {
private static final Engine gameEngine = new Engine();
public static void main(String[] args) {
}
}

View File

@ -0,0 +1,258 @@
package core.engine;
import core.engine.entity.Camera;
import core.engine.entity.Entity;
import core.engine.entity.Light;
import core.engine.model.HexagonModel;
import core.engine.model.RawModel;
import core.engine.model.TexturedModel;
import core.engine.renderer.MasterRenderer;
import core.engine.terrain.Terrain;
import core.engine.textures.ModelTexture;
import core.engine.toolbox.MousePicker;
import org.lwjgl.BufferUtils;
import org.lwjgl.Version;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.GL;
import org.lwjgl.system.MemoryStack;
import utils.vectors.Vector3f;
import java.nio.DoubleBuffer;
import java.nio.IntBuffer;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.glfw.GLFW.glfwSwapBuffers;
import static org.lwjgl.opengl.GL11.glClearColor;
import static org.lwjgl.system.MemoryStack.stackPush;
import static org.lwjgl.system.MemoryUtil.NULL;
public class Engine {
private long window;
private GLFWKeyCallback glfwKeyCallback;
private final Loader loader = new Loader();
public static int WINDOW_WIDTH = 1280;
public static int WINDOW_HEIGHT = 720;
private static boolean isMouseWheelPressed = false;
private static DoubleBuffer lastCursorX = BufferUtils.createDoubleBuffer(1);
private static DoubleBuffer lastCursorY = BufferUtils.createDoubleBuffer(1);
public Engine() {
System.out.println("Hello LWJGL " + Version.getVersion() + "!");
init();
loop();
// Free the window callbacks and destroy the window
glfwFreeCallbacks(window);
glfwDestroyWindow(window);
// Terminate GLFW and free the error callback
glfwTerminate();
glfwSetErrorCallback(null).free();
}
private void init() {
// Setup an error callback. The default implementation
// will print the error message in System.err.
GLFWErrorCallback.createPrint(System.err).set();
// Initialize GLFW. Most GLFW functions will not work before doing this.
if ( !glfwInit() )
throw new IllegalStateException("Unable to initialize GLFW");
// Configure GLFW
glfwDefaultWindowHints(); // optional, the current window hints are already the default
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); // the window will be resizable
// Create the window
window = glfwCreateWindow(1280, 720, "Hello World!", NULL, NULL);
if ( window == NULL )
throw new RuntimeException("Failed to create the GLFW window");
// Setup a key callback. It will be called every time a key is pressed, repeated or released.
glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
if ( key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE )
glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop
});
// Get the thread stack and push a new frame
try ( MemoryStack stack = stackPush() ) {
IntBuffer pWidth = stack.mallocInt(1); // int*
IntBuffer pHeight = stack.mallocInt(1); // int*
// Get the window size passed to glfwCreateWindow
glfwGetWindowSize(window, pWidth, pHeight);
// Get the resolution of the primary monitor
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
// Center the window
glfwSetWindowPos(
window,
(vidmode.width() - pWidth.get(0)) / 2,
(vidmode.height() - pHeight.get(0)) / 2
);
} // the stack frame is popped automatically
// Make the OpenGL context current
glfwMakeContextCurrent(window);
// Enable v-sync
glfwSwapInterval(1);
// Make the window visible
glfwShowWindow(window);
}
private void loop() {
// This line is critical for LWJGL's interoperation with GLFW's
// OpenGL context, or any context that is managed externally.
// LWJGL detects the context that is current in the current thread,
// creates the GLCapabilities instance and makes the OpenGL
// bindings available for use.
GL.createCapabilities();
// Set the clear color
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
Camera camera = new Camera();
Light light = new Light(new Vector3f(0,0,-20), new Vector3f(1,1,1));
//Generate Simple, Flat Terrain
Terrain terrain = new Terrain( loader, new ModelTexture(loader.loadTexture("white")), 16, 16, 7);
//Create Hexagon
HexagonModel hexagonModel = new HexagonModel();
RawModel hexagonRawModel = loader.loadHexagon(hexagonModel);
ModelTexture hexagonTexture = new ModelTexture(loader.loadTexture("white"));
TexturedModel hexagontexturedModel = new TexturedModel(hexagonRawModel, hexagonTexture);
Entity hexagonEntity = new Entity(hexagontexturedModel, new Vector3f(0,1,0), 0,0,0,1);
// Run the rendering loop until the user has attempted to close
// the window or has pressed the ESCAPE key.
MasterRenderer renderer = new MasterRenderer();
MousePicker mousePicker = new MousePicker(camera, renderer.getProjectionMatrix(), terrain);
input(camera, renderer, mousePicker);
while ( !glfwWindowShouldClose(window) ) {
renderer.processTerrain(terrain);
//renderer.processEntity(hexagonEntity);
renderer.render(light, camera);
DoubleBuffer posX = BufferUtils.createDoubleBuffer(1);
DoubleBuffer posY = BufferUtils.createDoubleBuffer(1);
glfwGetCursorPos(window, posX, posY);
mousePicker.update((float) posX.get(0), (float) posY.get(0));
glfwSwapBuffers(window); // swap the color buffers
// Poll for window events. The key callback above will only be
// invoked during this call.
glfwPollEvents();
}
renderer.cleanUp();
loader.cleanUp();
}
private void input(Camera camera, MasterRenderer masterRenderer, MousePicker mousePicker) {
GLFWScrollCallback glfwScrollCallback = new GLFWScrollCallback() {
@Override
public void invoke(long window, double xOffset, double yOffset) {
if(yOffset > 0) {
camera.zoomIn();
} else if(yOffset < 0) {
camera.zoomOut();
}
}
};
GLFWMouseButtonCallback glfwMouseButtonCallback = new GLFWMouseButtonCallback() {
@Override
public void invoke(long window, int button, int action, int mods) {
if (button == GLFW.GLFW_MOUSE_BUTTON_MIDDLE && action == GLFW.GLFW_PRESS) {
// Middle mouse button pressed
isMouseWheelPressed = true;
glfwGetCursorPos(window, lastCursorX, lastCursorY);
} else if (button == GLFW.GLFW_MOUSE_BUTTON_MIDDLE && action == GLFW.GLFW_RELEASE) {
// Middle mouse button released
isMouseWheelPressed = false;
}
if(button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS) {
//Track mouse position
DoubleBuffer posX = BufferUtils.createDoubleBuffer(1);
DoubleBuffer posY = BufferUtils.createDoubleBuffer(1);
glfwGetCursorPos(window, posX, posY);
mousePicker.update((float) posX.get(0), (float) posY.get(0));
}
}
};
// Define the cursor position callback function
GLFWCursorPosCallback cursorPosCallback = new GLFWCursorPosCallback() {
@Override
public void invoke(long window, double xpos, double ypos) {
if (isMouseWheelPressed) {
// Calculate the offset
double xOffset = xpos - lastCursorX.get(0);
double yOffset = ypos - lastCursorY.get(0);
// Use xOffset and yOffset for your desired functionality
if(yOffset > 0) {
camera.decreasePitch();
} else if(yOffset < 0) {
camera.increasePitch();
}
if(xOffset > 0) {
camera.decreaseYaw();
} else if(xOffset < 0) {
camera.increaseYaw();
}
// Update the last cursor position
lastCursorX.put(0, xpos);
lastCursorY.put(0, ypos);
}
}
};
glfwSetMouseButtonCallback(window, glfwMouseButtonCallback);
glfwSetCursorPosCallback(window, cursorPosCallback);
glfwSetScrollCallback(window, glfwScrollCallback);
glfwSetKeyCallback(window, glfwKeyCallback = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
if(key == GLFW_KEY_A) {
//move camera to left
camera.moveLeft();
}
if(key == GLFW_KEY_D) {
//move camera to right
camera.moveRight();
}
if(key == GLFW_KEY_W) {
camera.moveForward();
}
if(key == GLFW_KEY_S) {
camera.moveBackward();
}
if(key == GLFW_KEY_Y && action == GLFW_PRESS) {
masterRenderer.switchWireframe();
}
}
});
}
}

View File

@ -0,0 +1,103 @@
package core.engine;
import core.engine.model.HexagonModel;
import core.engine.model.RawModel;
import core.engine.textures.Texture;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;
public class Loader {
private List<Integer> vaos = new ArrayList<>();
private List<Integer> vbos = new ArrayList<>();
private List<Integer> textureIDs = new ArrayList<>();
public RawModel loadToVAO(float[] positions, float[] textureCoords, float[] normals, int[] indices) {
int vaoID = createVAO();
bindIndicesBuffer(indices);
storeDataInAttributeList(0, 3,positions);
storeDataInAttributeList(1, 2, textureCoords);
storeDataInAttributeList(2, 3, normals);
unbindVAO();
return new RawModel(vaoID, indices.length);
}
public RawModel loadHexagon(HexagonModel hexagonModel) {
return loadToVAO(hexagonModel.getVertices(), hexagonModel.getTextureCoords(), hexagonModel.getNormals(), hexagonModel.getIndices());
}
public int loadTexture(String fileName) {
Texture texture = new Texture("res/" + fileName + ".png");
int textureID = texture.getTextureID();
this.textureIDs.add(textureID);
return textureID;
}
private int createVAO() {
int vao = GL30.glGenVertexArrays();
vaos.add(vao);
GL30.glBindVertexArray(vao);
return vao;
}
private void storeDataInAttributeList(int attributeNumber, int coordinateSize, float[] data) {
int vboID = GL15.glGenBuffers();
vbos.add(vboID);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID);
FloatBuffer floatBuffer = storeInFloatBuffer(data);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, floatBuffer, GL15.GL_STATIC_DRAW);
GL20.glVertexAttribPointer(attributeNumber, coordinateSize, GL11.GL_FLOAT, false, 0,0);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
private void unbindVAO() {
GL30.glBindVertexArray(0);
}
private void bindIndicesBuffer(int[] indices) {
int vboID = GL15.glGenBuffers();
vbos.add(vboID);
GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboID);
IntBuffer buffer = storeInIntBuffer(indices);
GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, indices, GL15.GL_STATIC_DRAW);
}
private IntBuffer storeInIntBuffer(int[] data) {
IntBuffer intBuffer = BufferUtils.createIntBuffer(data.length);
intBuffer.put(data);
//Buffer is until know expected to be written to. Flip it, so it can be read
intBuffer.flip();
return intBuffer;
}
private FloatBuffer storeInFloatBuffer(float[] data) {
FloatBuffer floatBuffer = BufferUtils.createFloatBuffer(data.length);
floatBuffer.put(data);
//Buffer is until know expected to be written to. Flip it, so it can be read
floatBuffer.flip();
return floatBuffer;
}
public void cleanUp() {
for(int vao: vaos) {
GL30.glDeleteVertexArrays(vao);
}
for(int vbo: vbos) {
GL15.glDeleteBuffers(vbo);
}
for(int textureID: textureIDs) {
GL11.glDeleteTextures(textureID);
}
}
}

View File

@ -0,0 +1,119 @@
package core.engine;
import core.engine.model.RawModel;
import utils.vectors.Vector2f;
import utils.vectors.Vector3f;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class OBJLoader {
public static RawModel loadOBJModel(String fileName, Loader loader) {
FileReader fileReader = null;
try {
fileReader = new FileReader("res/" + fileName + ".obj");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if(fileReader != null) {
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line = null;
List<Vector3f> vertices = new ArrayList<>();
List<Vector2f> textures = new ArrayList<>();
List<Vector3f> normals = new ArrayList<>();
List<Integer> indices = new ArrayList<>();
float[] verticesArray = null;
float[] normalsArray = null;
float[] texturesArray = null;
int[] indicesArray = null;
try {
while(bufferedReader.ready()) {
line = bufferedReader.readLine();
String[] splittedLine = line.split(" ");
if(splittedLine[0].equals("v")) {
Vector3f vertex = new Vector3f(Float.parseFloat(splittedLine[1]),
Float.parseFloat(splittedLine[2]), Float.parseFloat(splittedLine[3]));
vertices.add(vertex);
} else if(splittedLine[0].equals("vt")) {
Vector2f texture = new Vector2f(Float.parseFloat(splittedLine[1]), Float.parseFloat(splittedLine[2]));
textures.add(texture);
} else if(splittedLine[0].equals("vn")) {
Vector3f normal = new Vector3f(Float.parseFloat(splittedLine[1]),
Float.parseFloat(splittedLine[2]), Float.parseFloat(splittedLine[3]));
normals.add(normal);
} else if(splittedLine[0].equals("f")) {
//No more vertices/textures/normals should be added at this point in the file
texturesArray = new float[vertices.size()*2];
normalsArray = new float[vertices.size()*3];
break;
}
}
while(line != null) {
if(!line.startsWith("f ")) {
line = bufferedReader.readLine();
continue;
}
String[] splittedLine = line.split(" ");
String[] vertex1 = splittedLine[1].split("/");
String[] vertex2 = splittedLine[2].split("/");
String[] vertex3 = splittedLine[3].split("/");
processVertex(vertex1, indices, textures, normals, texturesArray, normalsArray);
processVertex(vertex2, indices, textures, normals, texturesArray, normalsArray);
processVertex(vertex3, indices, textures, normals, texturesArray, normalsArray);
line = bufferedReader.readLine();
}
bufferedReader.close();
fileReader.close();
} catch(Exception e) {
e.printStackTrace();
}
verticesArray = new float[vertices.size()*3];
indicesArray = new int[indices.size()];
int vertexPointer = 0;
for(Vector3f vertex: vertices) {
verticesArray[vertexPointer++] = vertex.x;
verticesArray[vertexPointer++] = vertex.y;
verticesArray[vertexPointer++] = vertex.z;
}
for(int i=0; i<indices.size(); i++) {
indicesArray[i] = indices.get(i);
}
return loader.loadToVAO(verticesArray, texturesArray, normalsArray, indicesArray);
} else {
return null;
}
}
private static void processVertex(String[] vertexData, List<Integer> indices, List<Vector2f> textures,
List<Vector3f> normals, float[] textureArray, float[] normalsArray) {
int currentVertexPointer = Integer.parseInt(vertexData[0]) -1;
indices.add(currentVertexPointer);
Vector2f currentTex = textures.get(Integer.parseInt(vertexData[1])-1);
textureArray[currentVertexPointer*2] = currentTex.x;
textureArray[currentVertexPointer*2+1] = 1 - currentTex.y;
Vector3f currentNorm = normals.get(Integer.parseInt(vertexData[2])-1);
normalsArray[currentVertexPointer*3] = currentNorm.x;
normalsArray[currentVertexPointer*3+1] = currentNorm.y;
normalsArray[currentVertexPointer*3+2] = currentNorm.z;
}
}

View File

@ -0,0 +1,79 @@
package core.engine.entity;
import utils.vectors.Vector3f;
public class Camera {
private Vector3f position = new Vector3f(0, 37,0);
private float pitch = 90;
private float yaw = 180;
private float roll;
public void moveLeft() {
position.x += 0.5f;
}
public void moveForward() {
position.z -= .5f;
}
public void moveBackward() {
position.z += .5f;
}
public void moveRight() {
position.x -= .5f;
}
public void zoomOut() {
position.y += 0.5f;
}
public void zoomIn() {
position.y -= 0.5f;
}
public void increasePitch() {
this.pitch += .5f;
}
public void decreasePitch() {
this.pitch -= .5f;
}
public void increaseYaw() {
this.yaw += 0.5f;
}
public void decreaseYaw() {
this.yaw -= 0.5f;
}
public Vector3f getPosition() {
return position;
}
public float getPitch() {
return pitch;
}
public float getYaw() {
return yaw;
}
public float getRoll() {
return roll;
}
public void setPitch(float pitch) {
this.pitch += pitch;
}
public void setYaw(float yaw) {
this.yaw += yaw;
}
public void setRoll(float roll) {
this.roll += roll;
}
}

View File

@ -0,0 +1,81 @@
package core.engine.entity;
import core.engine.model.TexturedModel;
import utils.vectors.Vector3f;
public class Entity {
private TexturedModel model;
private Vector3f position;
private float rotX, rotY, rotZ;
private float scale;
public Entity(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ, float scale) {
this.model = model;
this.position = position;
this.rotX = rotX;
this.rotY = rotY;
this.rotZ = rotZ;
this.scale = scale;
}
public void increasePosition(float dx, float dy, float dz) {
position.x += dx;
position.y += dy;
position.z += dz;
}
public void increaseRotation(float dx, float dy, float dz) {
rotX += dx;
rotY += dy;
rotZ += dz;
}
public TexturedModel getModel() {
return model;
}
public void setModel(TexturedModel model) {
this.model = model;
}
public Vector3f getPosition() {
return position;
}
public void setPosition(Vector3f position) {
this.position = position;
}
public float getRotX() {
return rotX;
}
public void setRotX(float rotX) {
this.rotX = rotX;
}
public float getRotY() {
return rotY;
}
public void setRotY(float rotY) {
this.rotY = rotY;
}
public float getRotZ() {
return rotZ;
}
public void setRotZ(float rotZ) {
this.rotZ = rotZ;
}
public float getScale() {
return scale;
}
public void setScale(float scale) {
this.scale = scale;
}
}

View File

@ -0,0 +1,30 @@
package core.engine.entity;
import utils.vectors.Vector3f;
public class Light {
private Vector3f position;
private Vector3f color;
public Light(Vector3f position, Vector3f color) {
this.position = position;
this.color = color;
}
public Vector3f getPosition() {
return position;
}
public void setPosition(Vector3f position) {
this.position = position;
}
public Vector3f getColor() {
return color;
}
public void setColor(Vector3f color) {
this.color = color;
}
}

View File

@ -0,0 +1,88 @@
package core.engine.model;
import utils.vectors.Vector3f;
public class HexagonModel {
private float[] vertices;
private float[] normals;
private float[] textureCoords;
private int[] indices;
public HexagonModel() {
// Vertices (including the center)
vertices = new float[]{
0.0f, 0.0f, 0.0f, // Center
0.0f, 0.0f, 1.0f, // Top Vertex
0.866f, 0.0f, 0.5f, // Upper Right Vertex
0.866f, 0.0f, -0.5f, // Lower Right Vertex
0.0f, 0.0f, -1.0f, // Bottom Vertex
-0.866f, 0.0f, -0.5f, // Lower Left Vertex
-0.866f, 0.0f, 0.5f // Upper Left Vertex
};
// Normals
normals = new float[]{
0, 1, 0, // Center
0, 1, 0, // Top Vertex
0, 1, 0, // Upper Right Vertex
0, 1, 0, // Lower Right Vertex
0, 1, 0, // Bottom Vertex
0, 1, 0, // Lower Left Vertex
0, 1, 0 // Upper Left Vertex
};
// Texture Coordinates
textureCoords = new float[]{
0.5f, 0.5f, // Center
0.5f, 0.0f, // Top Vertex
1.0f, 0.25f, // Upper Right Vertex
1.0f, 0.75f, // Lower Right Vertex
0.5f, 1.0f, // Bottom Vertex
0.0f, 0.75f, // Lower Left Vertex
0.0f, 0.25f // Upper Left Vertex
};
// Indices
indices = new int[]{
0, 1, 2, // Center to Top Vertex to Upper Right Vertex
0, 2, 3, // Center to Upper Right Vertex to Lower Right Vertex
0, 3, 4, // Center to Lower Right Vertex to Bottom Vertex
0, 4, 5, // Center to Bottom Vertex to Lower Left Vertex
0, 5, 6, // Center to Lower Left Vertex to Upper Left Vertex
0, 6, 1 // Center to Upper Left Vertex to Top Vertex
};
}
public float[] getVertices() {
return vertices;
}
public void setVertices(float[] vertices) {
this.vertices = vertices;
}
public float[] getNormals() {
return normals;
}
public void setNormals(float[] normals) {
this.normals = normals;
}
public float[] getTextureCoords() {
return textureCoords;
}
public void setTextureCoords(float[] textureCoords) {
this.textureCoords = textureCoords;
}
public int[] getIndices() {
return indices;
}
public void setIndices(int[] indices) {
this.indices = indices;
}
}

View File

@ -0,0 +1,20 @@
package core.engine.model;
public class RawModel {
private final int vaoID;
private final int vertexCount;
public RawModel(int vaoID, int vertexCount) {
this.vaoID = vaoID;
this.vertexCount = vertexCount;
}
public int getVaoID() {
return vaoID;
}
public int getVertexCount() {
return vertexCount;
}
}

View File

@ -0,0 +1,22 @@
package core.engine.model;
import core.engine.textures.ModelTexture;
public class TexturedModel {
private RawModel rawModel;
private ModelTexture modelTexture;
public TexturedModel(RawModel rawModel, ModelTexture modelTexture) {
this.rawModel = rawModel;
this.modelTexture = modelTexture;
}
public RawModel getRawModel() {
return rawModel;
}
public ModelTexture getModelTexture() {
return modelTexture;
}
}

View File

@ -0,0 +1,73 @@
package core.engine.renderer;
import core.engine.entity.Entity;
import core.engine.model.RawModel;
import core.engine.model.TexturedModel;
import core.engine.shader.StaticShader;
import core.engine.textures.ModelTexture;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import utils.MatrixGraphicUtils;
import utils.vectors.Matrix4f;
import java.util.List;
import java.util.Map;
import static org.lwjgl.opengl.GL11C.*;
public class EntityRenderer {
private static final float FOV = 70;
private static final float NEAR_PLEANE = 0.1f;
private static final float FAR_PLANE = 1000;
private StaticShader shader;
public EntityRenderer(StaticShader shader, Matrix4f projectionMatrix) {
this.shader = shader;
shader.start();
shader.loadProjectionMatrix(projectionMatrix);
shader.stop();
}
public void render(Map<TexturedModel, List<Entity>> entities) {
for(TexturedModel model: entities.keySet()) {
prepareTexturedModel(model);
List<Entity> batch = entities.get(model);
for(Entity entity : batch) {
prepareInstance(entity);
GL11.glDrawElements(GL11.GL_TRIANGLES, model.getRawModel().getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
}
unbindTexturedModel();
}
}
private void prepareTexturedModel(TexturedModel model) {
RawModel rawModel = model.getRawModel();
GL30.glBindVertexArray(rawModel.getVaoID());
GL20.glEnableVertexAttribArray(0);
GL20.glEnableVertexAttribArray(1);
GL20.glEnableVertexAttribArray(2);
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, model.getModelTexture().getTextureID());
}
private void unbindTexturedModel() {
GL20.glDisableVertexAttribArray(0);
GL20.glDisableVertexAttribArray(1);
GL20.glDisableVertexAttribArray(2);
GL30.glBindVertexArray(0);
}
private void prepareInstance(Entity entity) {
Matrix4f transformationMatrix = MatrixGraphicUtils.createTransformationMatrix(entity.getPosition(), entity.getRotX(),
entity.getRotY(), entity.getRotZ(), entity.getScale());
shader.loadTransformationMatrix(transformationMatrix);
}
}

View File

@ -0,0 +1,117 @@
package core.engine.renderer;
import core.engine.Engine;
import core.engine.entity.Camera;
import core.engine.entity.Entity;
import core.engine.entity.Light;
import core.engine.model.TexturedModel;
import core.engine.shader.StaticShader;
import core.engine.shader.TerrainShader;
import core.engine.terrain.Terrain;
import core.engine.terrain.TerrainTile;
import org.lwjgl.opengl.GL11;
import utils.vectors.Matrix4f;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.lwjgl.opengl.GL11C.*;
public class MasterRenderer {
private static final float FOV = 70;
private static final float NEAR_PLEANE = 0.1f;
private static final float FAR_PLANE = 1000;
private StaticShader shader = new StaticShader();
private TerrainShader terrainShader = new TerrainShader();
private EntityRenderer renderer;
private TerrainRenderer terrainRenderer;
private Map<TexturedModel, List<Entity>> entities = new HashMap<>();
private List<TerrainTile> terrains = new ArrayList<>();
private Matrix4f projectionMatrix;
private boolean wireframe = false;
public MasterRenderer() {
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glCullFace(GL11.GL_BACK);
createProjectionMatrix();
renderer = new EntityRenderer(shader, projectionMatrix);
terrainRenderer = new TerrainRenderer(terrainShader, projectionMatrix);
}
public void prepare() {
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
GL11.glClearColor(0.49f, 89f, 0.98f, 1);
}
public void render(Light light, Camera camera) {
prepare();
shader.start();
shader.loadLight(light);
shader.loadViewMatrix(camera);
renderer.render(entities);
shader.stop();
terrainShader.start();
terrainShader.loadLight(light);
terrainShader.loadViewMatrix(camera);
terrainRenderer.render(terrains);
terrainShader.stop();
terrains.clear();
entities.clear();
}
public void processTerrain(Terrain terrain) {
terrains.addAll(terrain.getTerrainTiles());
}
public void processEntity(Entity entity) {
TexturedModel entityModel = entity.getModel();
List<Entity> batch = entities.get(entityModel);
if(batch != null) {
batch.add(entity);
} else {
List<Entity> newBatch = new ArrayList<>();
newBatch.add(entity);
entities.put(entityModel, newBatch);
}
}
public void cleanUp() {
shader.cleanUp();
terrainShader.cleanUp();
}
private void createProjectionMatrix() {
float aspectRatio = (float) Engine.WINDOW_WIDTH / (float) Engine.WINDOW_HEIGHT;
float y_scale = (float) ((1f / Math.tan(Math.toRadians(FOV / 2f))) * aspectRatio);
float x_scale = y_scale / aspectRatio;
float frustum_length = FAR_PLANE - NEAR_PLEANE;
projectionMatrix = new Matrix4f();
projectionMatrix.m00 = x_scale;
projectionMatrix.m11 = y_scale;
projectionMatrix.m22 = -((FAR_PLANE + NEAR_PLEANE) / frustum_length);
projectionMatrix.m23 = -1;
projectionMatrix.m32 = -((2 * NEAR_PLEANE * FAR_PLANE) / frustum_length);
projectionMatrix.m33 = 0;
}
public void switchWireframe() {
this.wireframe = !this.wireframe;
if(this.wireframe) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
} else {
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
}
}
public Matrix4f getProjectionMatrix() {
return projectionMatrix;
}
}

View File

@ -0,0 +1,62 @@
package core.engine.renderer;
import core.engine.entity.Entity;
import core.engine.model.RawModel;
import core.engine.model.TexturedModel;
import core.engine.shader.TerrainShader;
import core.engine.terrain.Terrain;
import core.engine.terrain.TerrainTile;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import utils.MatrixGraphicUtils;
import utils.vectors.Matrix4f;
import utils.vectors.Vector3f;
import java.util.List;
public class TerrainRenderer {
private TerrainShader shader;
public TerrainRenderer(TerrainShader shader, Matrix4f projectionMatrix) {
this.shader = shader;
shader.start();
shader.loadProjectionMatrix(projectionMatrix);
shader.stop();
}
public void render(List<TerrainTile> terrains) {
for(TerrainTile terrain : terrains) {
prepareTerrain(terrain);
loadModelMatrix(terrain);
GL11.glDrawElements(GL11.GL_TRIANGLES, terrain.getModel().getRawModel().getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
unbindTexturedModel();
}
}
private void prepareTerrain(TerrainTile terrainTile) {
RawModel rawModel = terrainTile.getModel().getRawModel();
GL30.glBindVertexArray(rawModel.getVaoID());
GL20.glEnableVertexAttribArray(0);
GL20.glEnableVertexAttribArray(1);
GL20.glEnableVertexAttribArray(2);
GL13.glActiveTexture(GL13.GL_TEXTURE0);
GL11.glBindTexture(GL11.GL_TEXTURE_2D, terrainTile.getModel().getModelTexture().getTextureID());
shader.loadTerrainColor(terrainTile.getColor());
}
private void unbindTexturedModel() {
GL20.glDisableVertexAttribArray(0);
GL20.glDisableVertexAttribArray(1);
GL20.glDisableVertexAttribArray(2);
GL30.glBindVertexArray(0);
}
private void loadModelMatrix(TerrainTile terrain) {
Matrix4f transformationMatrix = MatrixGraphicUtils.createTransformationMatrix(terrain.getPosition(), terrain.getRotX(),
terrain.getRotY(), terrain.getRotZ(), terrain.getScale());
shader.loadTransformationMatrix(transformationMatrix);
}
}

View File

@ -0,0 +1,108 @@
package core.engine.shader;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import utils.vectors.Matrix4f;
import utils.vectors.Vector3f;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.FloatBuffer;
public abstract class ShaderProgram {
private int programID;
private int vertexShaderID;
private int fragmentShaderID;
private static FloatBuffer matrixBuffer = BufferUtils.createFloatBuffer(16);
public ShaderProgram(String vertexFile, String fragmentFile) {
vertexShaderID = loadShader(vertexFile, GL20.GL_VERTEX_SHADER);
fragmentShaderID = loadShader(fragmentFile, GL20.GL_FRAGMENT_SHADER);
programID = GL20.glCreateProgram();
GL20.glAttachShader(programID, vertexShaderID);
GL20.glAttachShader(programID, fragmentShaderID);
bindAttributes();
GL20.glLinkProgram(programID);
GL20.glValidateProgram(programID);
getAllUniformLocations();
}
protected abstract void getAllUniformLocations();
protected int getUniformLocation(String uniformName) {
return GL20.glGetUniformLocation(programID, uniformName);
}
public void start() {
GL20.glUseProgram(programID);
}
public void stop() {
GL20.glUseProgram(0);
}
public void cleanUp() {
stop();
GL20.glDetachShader(programID, vertexShaderID);
GL20.glDetachShader(programID, fragmentShaderID);
GL20.glDeleteShader(vertexShaderID);
GL20.glDeleteShader(fragmentShaderID);
GL20.glDeleteProgram(programID);
}
protected abstract void bindAttributes();
protected void bindAttribute(int attribute, String variableName) {
GL20.glBindAttribLocation(programID, attribute, variableName);
}
protected void loadFloat(int location, float value) {
GL20.glUniform1f(location, value);
}
protected void loadVector(int location, Vector3f vector) {
GL20.glUniform3f(location, vector.x, vector.y, vector.z);
}
protected void loadBoolean(int location, boolean value) {
GL20.glUniform1f(location, value? 1: 0);
}
protected void loadMatrix(int location, Matrix4f matrix) {
matrix.store(matrixBuffer);
matrixBuffer.flip();
GL20.glUniformMatrix4fv(location,false, matrixBuffer);
}
private static int loadShader(String file, int type) {
StringBuilder shadersource = new StringBuilder();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
while((line = bufferedReader.readLine()) != null) {
shadersource.append(line).append(System.lineSeparator());
}
bufferedReader.close();
} catch (IOException e) {
System.err.println("Could not read file!");
e.printStackTrace();
System.exit(-1);
}
int shaderID = GL20.glCreateShader(type);
GL20.glShaderSource(shaderID, shadersource);
GL20.glCompileShader(shaderID);
if(GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
System.out.println(GL20.glGetShaderInfoLog(shaderID));
System.err.println("Could not compile Shader");
System.exit(-1);
}
return shaderID;
}
}

View File

@ -0,0 +1,55 @@
package core.engine.shader;
import core.engine.entity.Camera;
import core.engine.entity.Light;
import utils.MatrixGraphicUtils;
import utils.vectors.Matrix4f;
public class StaticShader extends ShaderProgram{
private static final String VERTEX_FILE = "src/main/java/core/engine/shader/vertexShader.glsl";
private static final String FRAGMENT_FILE = "src/main/java/core/engine/shader/fragmentShader.glsl";
private int location_transformationMatrix;
private int location_projectionMatrix;
private int location_viewMatrix;
private int location_lightPosition;
private int location_lightColor;
public StaticShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
@Override
protected void getAllUniformLocations() {
this.location_transformationMatrix = super.getUniformLocation("transformationMatrix");
this.location_projectionMatrix = super.getUniformLocation("projectionMatrix");
this.location_viewMatrix = super.getUniformLocation("viewMatrix");
this.location_lightColor = super.getUniformLocation("lightColor");
this.location_lightPosition = super.getUniformLocation("lightPosition");
}
@Override
protected void bindAttributes() {
super.bindAttribute(0, "position");
super.bindAttribute(1, "textureCoords");
super.bindAttribute(2, "normal");
}
public void loadTransformationMatrix(Matrix4f matrix) {
super.loadMatrix(location_transformationMatrix, matrix);
}
public void loadProjectionMatrix(Matrix4f matrix) {
super.loadMatrix(location_projectionMatrix, matrix);
}
public void loadViewMatrix(Camera camera) {
Matrix4f viewMatrix = MatrixGraphicUtils.createViewMatrix(camera);
super.loadMatrix(location_viewMatrix, viewMatrix);
}
public void loadLight(Light light) {
super.loadVector(location_lightPosition, light.getPosition());
super.loadVector(location_lightColor, light.getColor());
}
}

View File

@ -0,0 +1,61 @@
package core.engine.shader;
import core.engine.entity.Camera;
import core.engine.entity.Light;
import utils.MatrixGraphicUtils;
import utils.vectors.Matrix4f;
import utils.vectors.Vector3f;
public class TerrainShader extends ShaderProgram{
private static final String VERTEX_FILE = "src/main/java/core/engine/shader/terrainVertexShader.glsl";
private static final String FRAGMENT_FILE = "src/main/java/core/engine/shader/terrainFragmentShader.glsl";
private int location_transformationMatrix;
private int location_projectionMatrix;
private int location_viewMatrix;
private int location_lightPosition;
private int location_lightColor;
private int location_terrainColor;
public TerrainShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
@Override
protected void getAllUniformLocations() {
this.location_transformationMatrix = super.getUniformLocation("transformationMatrix");
this.location_projectionMatrix = super.getUniformLocation("projectionMatrix");
this.location_viewMatrix = super.getUniformLocation("viewMatrix");
this.location_lightColor = super.getUniformLocation("lightColor");
this.location_lightPosition = super.getUniformLocation("lightPosition");
this.location_terrainColor = super.getUniformLocation("terrainColor");
}
@Override
protected void bindAttributes() {
super.bindAttribute(0, "position");
super.bindAttribute(1, "textureCoords");
super.bindAttribute(2, "normal");
}
public void loadTransformationMatrix(Matrix4f matrix) {
super.loadMatrix(location_transformationMatrix, matrix);
}
public void loadProjectionMatrix(Matrix4f matrix) {
super.loadMatrix(location_projectionMatrix, matrix);
}
public void loadViewMatrix(Camera camera) {
Matrix4f viewMatrix = MatrixGraphicUtils.createViewMatrix(camera);
super.loadMatrix(location_viewMatrix, viewMatrix);
}
public void loadLight(Light light) {
super.loadVector(location_lightPosition, light.getPosition());
super.loadVector(location_lightColor, light.getColor());
}
public void loadTerrainColor(Vector3f color) {
super.loadVector(location_terrainColor, color);
}
}

View File

@ -0,0 +1,21 @@
#version 400 core
in vec2 pass_textureCoords;
in vec3 surfaceNormal;
in vec3 toLightVector;
out vec4 out_Color;
uniform sampler2D textureSampler;
uniform vec3 lightColor;
void main(void) {
vec3 unitNormal = normalize(surfaceNormal);
vec3 unitToLightVector = normalize(toLightVector);
float nDotl = dot(unitNormal, unitToLightVector);
float brightness = max(nDotl, 0.2);
vec3 diffusde = brightness * lightColor;
out_Color = vec4(diffusde, 1.0) * texture(textureSampler, pass_textureCoords);
}

View File

@ -0,0 +1,22 @@
#version 400 core
in vec2 pass_textureCoords;
in vec3 surfaceNormal;
in vec3 toLightVector;
out vec4 out_Color;
uniform sampler2D textureSampler;
uniform vec3 lightColor;
uniform vec3 terrainColor;
void main(void) {
vec3 unitNormal = normalize(surfaceNormal);
vec3 unitToLightVector = normalize(toLightVector);
float nDotl = dot(unitNormal, unitToLightVector);
float brightness = max(nDotl, 0.2);
vec3 diffusde = brightness * lightColor;
out_Color = /*vec4(diffusde, 1.0) **/ vec4(terrainColor, 1);
}

View File

@ -0,0 +1,24 @@
#version 400 core
in vec3 position;
in vec2 textureCoords;
in vec3 normal;
uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform vec3 lightPosition;
out vec2 pass_textureCoords;
out vec3 surfaceNormal;
out vec3 toLightVector;
void main(void) {
vec4 worldPosition = transformationMatrix * vec4(position, 1.0);
gl_Position = projectionMatrix * viewMatrix * worldPosition;
pass_textureCoords = textureCoords;
surfaceNormal = (transformationMatrix * vec4(normal, 0.0)).xyz;
toLightVector = lightPosition - worldPosition.xyz;
}

View File

@ -0,0 +1,24 @@
#version 400 core
in vec3 position;
in vec2 textureCoords;
in vec3 normal;
uniform mat4 transformationMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;
uniform vec3 lightPosition;
out vec2 pass_textureCoords;
out vec3 surfaceNormal;
out vec3 toLightVector;
void main(void) {
vec4 worldPosition = transformationMatrix * vec4(position, 1.0);
gl_Position = projectionMatrix * viewMatrix * worldPosition;
pass_textureCoords = textureCoords;
surfaceNormal = (transformationMatrix * vec4(normal, 0.0)).xyz;
toLightVector = lightPosition - worldPosition.xyz;
}

View File

@ -0,0 +1,40 @@
package core.engine.terrain;
import core.engine.Loader;
import core.engine.entity.Camera;
import core.engine.model.HexagonModel;
import core.engine.model.RawModel;
import core.engine.model.TexturedModel;
import core.engine.textures.ModelTexture;
import utils.vectors.Vector3f;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Terrain {
private List<TerrainTile> terrainTiles = new ArrayList<>();
public Terrain(Loader loader, ModelTexture modelTexture, int rows, int columns, int numberPlayers) {
TerrainGenerator terrainGenerator = new TerrainGenerator();
HexagonModel hexagonModel = new HexagonModel();
RawModel rawModel = loader.loadHexagon(hexagonModel);
TexturedModel texturedModel = new TexturedModel(rawModel, modelTexture);
for(int row = 0; row < rows; row++) {
for(int column = 0; column < columns; column++) {
if(row % 2 == 1) {
terrainTiles.add(new TerrainTile(texturedModel, new Vector3f(column * 2* 0.866f, 0, row * 1.5f),0,0,0,1, row, column, terrainGenerator.generateColor(column, row)));
} else {
terrainTiles.add(new TerrainTile(texturedModel, new Vector3f(column *2 * 0.866f - 0.866f, 0, row * 1.5f),0,0,0,1, row, column, terrainGenerator.generateColor(column, row)));
}
}
}
}
public List<TerrainTile> getTerrainTiles() {
return terrainTiles;
}
}

View File

@ -0,0 +1,37 @@
package core.engine.terrain;
import utils.vectors.Vector3f;
import java.util.Random;
public class TerrainGenerator {
private final Random random = new Random();
private final int seed_red;
private final int seed_blue;
private final int seed_green;
public TerrainGenerator() {
this.seed_red = random.nextInt(1000000000);
this.seed_blue = random.nextInt(1000000000);
this.seed_green = random.nextInt(1000000000);
}
public Vector3f generateColor(int x, int z) {
return new Vector3f(getSmoothNoise(x, z, seed_red), getSmoothNoise(x, z, seed_green), getSmoothNoise(x, z, seed_blue));
}
private float getSmoothNoise(int x, int z, int seed) {
float corners = (getNoise(x -1, z-1, seed) + getNoise(x+1, z-1, seed) +
getNoise(x-1, z+1, seed) + getNoise(x+1, z+1, seed)) / 16f;
float sides = (getNoise(x-1, z, seed) + getNoise(x+1, z, seed) +
getNoise(x, z-1, seed) + getNoise(x, z+1, seed)) / 8f;
float center = getNoise(x, z, seed) / 4f;
return corners + sides + center;
}
private float getNoise(int x, int z, int seed) {
random.setSeed(x * 49632L + z * 325176L + seed);
return random.nextFloat();
}
}

View File

@ -0,0 +1,96 @@
package core.engine.terrain;
import core.engine.Loader;
import core.engine.entity.Camera;
import core.engine.model.RawModel;
import core.engine.model.TexturedModel;
import core.engine.textures.ModelTexture;
import utils.vectors.Vector3f;
public class TerrainTile {
private TexturedModel model;
private Vector3f position;
private float rotX, rotY, rotZ;
private float scale;
private int row;
private int column;
private Vector3f color;
public TerrainTile(TexturedModel model, Vector3f position, float rotX, float rotY, float rotZ, float scale, int row, int column, Vector3f color) {
this.model = model;
this.position = position;
this.rotX = rotX;
this.rotY = rotY;
this.rotZ = rotZ;
this.scale = scale;
this.row = row;
this.column = column;
this.color = color;
}
public TexturedModel getModel() {
return model;
}
public void setModel(TexturedModel model) {
this.model = model;
}
public Vector3f getPosition() {
return position;
}
public void setPosition(Vector3f position) {
this.position = position;
}
public float getRotX() {
return rotX;
}
public void setRotX(float rotX) {
this.rotX = rotX;
}
public float getRotY() {
return rotY;
}
public void setRotY(float rotY) {
this.rotY = rotY;
}
public float getRotZ() {
return rotZ;
}
public void setRotZ(float rotZ) {
this.rotZ = rotZ;
}
public float getScale() {
return scale;
}
public void setScale(float scale) {
this.scale = scale;
}
public Vector3f getColor() {
return color;
}
public void setColor(Vector3f color) {
this.color = color;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
}

View File

@ -0,0 +1,14 @@
package core.engine.textures;
public class ModelTexture {
private int textureID;
public ModelTexture(int textureID) {
this.textureID = textureID;
}
public int getTextureID() {
return textureID;
}
}

View File

@ -0,0 +1,70 @@
package core.engine.textures;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import static org.lwjgl.opengl.GL11.*;
public class Texture {
private int width, height;
private int texture;
public Texture(String path) {
texture = load(path);
}
private int load(String path) {
int[] pixels = null;
try {
BufferedImage image = ImageIO.read(new FileInputStream(path));
width = image.getWidth();
height = image.getHeight();
pixels = new int[width * height];
image.getRGB(0, 0, width, height, pixels, 0, width);
} catch (IOException e) {
e.printStackTrace();
}
int[] data = new int[width * height];
for (int i = 0; i < width * height; i++) {
int a = (pixels[i] & 0xff000000) >> 24;
int r = (pixels[i] & 0xff0000) >> 16;
int g = (pixels[i] & 0xff00) >> 8;
int b = (pixels[i] & 0xff);
data[i] = a << 24 | b << 16 | g << 8 | r;
}
int result = glGenTextures();
glBindTexture(GL_TEXTURE_2D, result);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
IntBuffer buffer = ByteBuffer.allocateDirect(data.length << 2)
.order(ByteOrder.nativeOrder()).asIntBuffer();
buffer.put(data).flip();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, buffer);
glBindTexture(GL_TEXTURE_2D, 0);
return result;
}
public void bind() {
glBindTexture(GL_TEXTURE_2D, texture);
}
public void unbind() {
glBindTexture(GL_TEXTURE_2D, 0);
}
public int getTextureID() {
return texture;
}
}

View File

@ -0,0 +1,155 @@
package core.engine.toolbox;
import core.engine.Engine;
import core.engine.entity.Camera;
import core.engine.terrain.Terrain;
import core.engine.terrain.TerrainTile;
import org.lwjgl.system.windows.MOUSEINPUT;
import utils.MatrixGraphicUtils;
import utils.vectors.*;
public class MousePicker {
private static final int RECURSION_COUNT = 200;
private static final float RAY_RANGE = 600;
private Vector3f currentRay = new Vector3f();
private Matrix4f projectionMatrix;
private Matrix4f viewMatrix;
private Camera camera;
private Terrain terrain;
private Vector3f currentTerrainPoint;
public MousePicker(Camera cam, Matrix4f projection, Terrain terrain) {
camera = cam;
projectionMatrix = projection;
viewMatrix = MatrixGraphicUtils.createViewMatrix(camera);
this.terrain = terrain;
}
public Vector3f getCurrentTerrainPoint() {
return currentTerrainPoint;
}
public Vector3f getCurrentRay() {
return currentRay;
}
public void update(float mouseX, float mouseY) {
viewMatrix = MatrixGraphicUtils.createViewMatrix(camera);
currentRay = calculateMouseRay(mouseX, mouseY);
if (intersectionInRange(0, RAY_RANGE, currentRay)) {
currentTerrainPoint = binarySearch(0, 0, RAY_RANGE, currentRay);
} else {
currentTerrainPoint = null;
}
System.out.println(currentTerrainPoint);
TerrainTile terrainTile = calcIntersectingTerrainTile();
if(terrainTile != null) {
terrainTile.setColor(new Vector3f(1f, 1f, 1f));
}
}
private Vector3f calculateMouseRay(float mouseX, float mouseY) {
Vector2f normalizedCoords = getNormalisedDeviceCoordinates(mouseX, mouseY);
Vector4f clipCoords = new Vector4f(normalizedCoords.x, normalizedCoords.y, -1.0f, 1.0f);
Vector4f eyeCoords = toEyeCoords(clipCoords);
Vector3f worldRay = toWorldCoords(eyeCoords);
return worldRay;
}
private Vector3f toWorldCoords(Vector4f eyeCoords) {
Matrix4f invertedView = Matrix4f.invert(viewMatrix, null);
Vector4f rayWorld = Matrix4f.transform(invertedView, eyeCoords, null);
Vector3f mouseRay = new Vector3f(rayWorld.x, rayWorld.y, rayWorld.z);
mouseRay.normalise();
return mouseRay;
}
private Vector4f toEyeCoords(Vector4f clipCoords) {
Matrix4f invertedProjection = Matrix4f.invert(projectionMatrix, null);
Vector4f eyeCoords = Matrix4f.transform(invertedProjection, clipCoords, null);
return new Vector4f(eyeCoords.x, eyeCoords.y, -1f, 0f);
}
private Vector2f getNormalisedDeviceCoordinates(float mouseX, float mouseY) {
float x = (2.0f * mouseX) / Engine.WINDOW_WIDTH - 1f;
float y = (2.0f * mouseY) / Engine.WINDOW_HEIGHT - 1f;
return new Vector2f(x, y);
}
//**********************************************************
private Vector3f getPointOnRay(Vector3f ray, float distance) {
Vector3f camPos = camera.getPosition();
Vector3f start = new Vector3f(camPos.x, camPos.y, -camPos.z);
Vector3f scaledRay = new Vector3f(ray.x * distance, ray.y * distance, ray.z * distance);
return Vector3f.add(start, scaledRay, null);
}
private Vector3f binarySearch(int count, float start, float finish, Vector3f ray) {
float half = start + ((finish - start) / 2f);
if (count >= RECURSION_COUNT) {
Vector3f endPoint = getPointOnRay(ray, half);
Terrain terrain = getTerrain(endPoint.getX(), endPoint.getZ());
if (terrain != null) {
return endPoint;
} else {
return null;
}
}
if (intersectionInRange(start, half, ray)) {
return binarySearch(count + 1, start, half, ray);
} else {
return binarySearch(count + 1, half, finish, ray);
}
}
private boolean intersectionInRange(float start, float finish, Vector3f ray) {
Vector3f startPoint = getPointOnRay(ray, start);
Vector3f endPoint = getPointOnRay(ray, finish);
if (!isUnderGround(startPoint) && isUnderGround(endPoint)) {
return true;
} else {
return false;
}
}
private boolean isUnderGround(Vector3f testPoint) {
Terrain terrain = getTerrain(testPoint.getX(), testPoint.getZ());
float height = 0;
if (testPoint.y < height) {
return true;
} else {
return false;
}
}
private Terrain getTerrain(float worldX, float worldZ) {
return terrain;
}
public TerrainTile calcIntersectingTerrainTile() {
for(TerrainTile terrainTile : terrain.getTerrainTiles()) {
float distanceX = (float) Math.pow(currentTerrainPoint.x - terrainTile.getPosition().x, 2);
float distanceZ = (float) Math.pow(-currentTerrainPoint.z - terrainTile.getPosition().z, 2);
float radius = (float) Math.pow(1, 2);
if(distanceX + distanceZ < radius) {
if(!terrainTile.getColor().equals(new Vector3f(1f, 1f, 1f))) {
System.out.println("Center: " + terrainTile.getPosition());
System.out.println("TerrainPoint: " + currentTerrainPoint);
}
return terrainTile;
}
}
return null;
}
}

View File

@ -0,0 +1,32 @@
package utils;
import core.engine.entity.Camera;
import utils.vectors.Matrix4f;
import utils.vectors.Vector3f;
public class MatrixGraphicUtils {
public static Matrix4f createTransformationMatrix(Vector3f translation, float rx, float ry,
float rz, float scale) {
Matrix4f matrix = new Matrix4f();
matrix.setIdentity();
Matrix4f.translate(translation, matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(rx), new Vector3f(1,0,0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(ry), new Vector3f(0,1,0), matrix, matrix);
Matrix4f.rotate((float) Math.toRadians(rz), new Vector3f(0,0,1), matrix, matrix);
Matrix4f.scale(new Vector3f(scale,scale,scale), matrix, matrix);
return matrix;
}
public static Matrix4f createViewMatrix(Camera camera) {
Matrix4f viewMatrix = new Matrix4f();
viewMatrix.setIdentity();
Matrix4f.rotate((float) Math.toRadians(camera.getPitch()), new Vector3f(1, 0, 0), viewMatrix,
viewMatrix);
Matrix4f.rotate((float) Math.toRadians(camera.getYaw()), new Vector3f(0, 1, 0), viewMatrix, viewMatrix);
Vector3f cameraPos = camera.getPosition();
Vector3f negativeCameraPos = new Vector3f(-cameraPos.x,-cameraPos.y,-cameraPos.z);
Matrix4f.translate(negativeCameraPos, viewMatrix, viewMatrix);
return viewMatrix;
}
}

View File

@ -0,0 +1,103 @@
package utils.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
*
* Base class for matrices. When a matrix is constructed it will be the identity
* matrix unless otherwise stated.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public abstract class Matrix implements Serializable {
/**
* Constructor for Matrix.
*/
protected Matrix() {
super();
}
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public abstract Matrix setIdentity();
/**
* Invert this matrix
* @return this
*/
public abstract Matrix invert();
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public abstract Matrix load(FloatBuffer buf);
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (mathematical) order.
*
* @param buf A float buffer to read from
* @return this
*/
public abstract Matrix loadTranspose(FloatBuffer buf);
/**
* Negate this matrix
* @return this
*/
public abstract Matrix negate();
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
* @return this
*/
public abstract Matrix store(FloatBuffer buf);
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
* @return this
*/
public abstract Matrix storeTranspose(FloatBuffer buf);
/**
* Transpose this matrix
* @return this
*/
public abstract Matrix transpose();
/**
* Set this matrix to 0.
* @return this
*/
public abstract Matrix setZero();
/**
* @return the determinant of the matrix
*/
public abstract float determinant();
}

View File

@ -0,0 +1,370 @@
package utils.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
*
* Holds a 2x2 matrix
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public class Matrix2f extends Matrix implements Serializable {
private static final long serialVersionUID = 1L;
public float m00, m01, m10, m11;
/**
* Constructor for Matrix2f. The matrix is initialised to the identity.
*/
public Matrix2f() {
setIdentity();
}
/**
* Constructor
*/
public Matrix2f(Matrix2f src) {
load(src);
}
/**
* Load from another matrix
* @param src The source matrix
* @return this
*/
public Matrix2f load(Matrix2f src) {
return load(src, this);
}
/**
* Copy the source matrix to the destination matrix.
* @param src The source matrix
* @param dest The destination matrix, or null if a new one should be created.
* @return The copied matrix
*/
public static Matrix2f load(Matrix2f src, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
dest.m00 = src.m00;
dest.m01 = src.m01;
dest.m10 = src.m10;
dest.m11 = src.m11;
return dest;
}
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix load(FloatBuffer buf) {
m00 = buf.get();
m01 = buf.get();
m10 = buf.get();
m11 = buf.get();
return this;
}
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (mathematical) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix loadTranspose(FloatBuffer buf) {
m00 = buf.get();
m10 = buf.get();
m01 = buf.get();
m11 = buf.get();
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
*/
public Matrix store(FloatBuffer buf) {
buf.put(m00);
buf.put(m01);
buf.put(m10);
buf.put(m11);
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
*/
public Matrix storeTranspose(FloatBuffer buf) {
buf.put(m00);
buf.put(m10);
buf.put(m01);
buf.put(m11);
return this;
}
/**
* Add two matrices together and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f add(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
return dest;
}
/**
* Subtract the right matrix from the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f sub(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
return dest;
}
/**
* Multiply the right matrix by the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix2f mul(Matrix2f left, Matrix2f right, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
float m00 = left.m00 * right.m00 + left.m10 * right.m01;
float m01 = left.m01 * right.m00 + left.m11 * right.m01;
float m10 = left.m00 * right.m10 + left.m10 * right.m11;
float m11 = left.m01 * right.m10 + left.m11 * right.m11;
dest.m00 = m00;
dest.m01 = m01;
dest.m10 = m10;
dest.m11 = m11;
return dest;
}
/**
* Transform a Vector by a matrix and return the result in a destination
* vector.
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector
*/
public static Vector2f transform(Matrix2f left, Vector2f right, Vector2f dest) {
if (dest == null)
dest = new Vector2f();
float x = left.m00 * right.x + left.m10 * right.y;
float y = left.m01 * right.x + left.m11 * right.y;
dest.x = x;
dest.y = y;
return dest;
}
/**
* Transpose this matrix
* @return this
*/
public Matrix transpose() {
return transpose(this);
}
/**
* Transpose this matrix and place the result in another matrix.
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public Matrix2f transpose(Matrix2f dest) {
return transpose(this, dest);
}
/**
* Transpose the source matrix and place the result in the destination matrix.
* @param src The source matrix or null if a new matrix is to be created
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public static Matrix2f transpose(Matrix2f src, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
float m01 = src.m10;
float m10 = src.m01;
dest.m01 = m01;
dest.m10 = m10;
return dest;
}
/**
* Invert this matrix
* @return this if successful, null otherwise
*/
public Matrix invert() {
return invert(this, this);
}
/**
* Invert the source matrix and place the result in the destination matrix.
* @param src The source matrix to be inverted
* @param dest The destination matrix or null if a new matrix is to be created
* @return The inverted matrix, or null if source can't be reverted.
*/
public static Matrix2f invert(Matrix2f src, Matrix2f dest) {
/*
*inv(A) = 1/det(A) * adj(A);
*/
float determinant = src.determinant();
if (determinant != 0) {
if (dest == null)
dest = new Matrix2f();
float determinant_inv = 1f/determinant;
float t00 = src.m11*determinant_inv;
float t01 = -src.m01*determinant_inv;
float t11 = src.m00*determinant_inv;
float t10 = -src.m10*determinant_inv;
dest.m00 = t00;
dest.m01 = t01;
dest.m10 = t10;
dest.m11 = t11;
return dest;
} else
return null;
}
/**
* Returns a string representation of this matrix
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(m00).append(' ').append(m10).append(' ').append('\n');
buf.append(m01).append(' ').append(m11).append(' ').append('\n');
return buf.toString();
}
/**
* Negate this matrix
* @return this
*/
public Matrix negate() {
return negate(this);
}
/**
* Negate this matrix and stash the result in another matrix.
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public Matrix2f negate(Matrix2f dest) {
return negate(this, dest);
}
/**
* Negate the source matrix and stash the result in the destination matrix.
* @param src The source matrix to be negated
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public static Matrix2f negate(Matrix2f src, Matrix2f dest) {
if (dest == null)
dest = new Matrix2f();
dest.m00 = -src.m00;
dest.m01 = -src.m01;
dest.m10 = -src.m10;
dest.m11 = -src.m11;
return dest;
}
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public Matrix setIdentity() {
return setIdentity(this);
}
/**
* Set the source matrix to be the identity matrix.
* @param src The matrix to set to the identity.
* @return The source matrix
*/
public static Matrix2f setIdentity(Matrix2f src) {
src.m00 = 1.0f;
src.m01 = 0.0f;
src.m10 = 0.0f;
src.m11 = 1.0f;
return src;
}
/**
* Set this matrix to 0.
* @return this
*/
public Matrix setZero() {
return setZero(this);
}
public static Matrix2f setZero(Matrix2f src) {
src.m00 = 0.0f;
src.m01 = 0.0f;
src.m10 = 0.0f;
src.m11 = 0.0f;
return src;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Matrix#determinant()
*/
public float determinant() {
return m00 * m11 - m01*m10;
}
}

View File

@ -0,0 +1,480 @@
package utils.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
*
* Holds a 3x3 matrix.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public class Matrix3f extends Matrix implements Serializable {
private static final long serialVersionUID = 1L;
public float m00,
m01,
m02,
m10,
m11,
m12,
m20,
m21,
m22;
/**
* Constructor for Matrix3f. Matrix is initialised to the identity.
*/
public Matrix3f() {
super();
setIdentity();
}
/**
* Load from another matrix
* @param src The source matrix
* @return this
*/
public Matrix3f load(Matrix3f src) {
return load(src, this);
}
/**
* Copy source matrix to destination matrix
* @param src The source matrix
* @param dest The destination matrix, or null of a new matrix is to be created
* @return The copied matrix
*/
public static Matrix3f load(Matrix3f src, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
dest.m00 = src.m00;
dest.m10 = src.m10;
dest.m20 = src.m20;
dest.m01 = src.m01;
dest.m11 = src.m11;
dest.m21 = src.m21;
dest.m02 = src.m02;
dest.m12 = src.m12;
dest.m22 = src.m22;
return dest;
}
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix load(FloatBuffer buf) {
m00 = buf.get();
m01 = buf.get();
m02 = buf.get();
m10 = buf.get();
m11 = buf.get();
m12 = buf.get();
m20 = buf.get();
m21 = buf.get();
m22 = buf.get();
return this;
}
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (maths) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix loadTranspose(FloatBuffer buf) {
m00 = buf.get();
m10 = buf.get();
m20 = buf.get();
m01 = buf.get();
m11 = buf.get();
m21 = buf.get();
m02 = buf.get();
m12 = buf.get();
m22 = buf.get();
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
*/
public Matrix store(FloatBuffer buf) {
buf.put(m00);
buf.put(m01);
buf.put(m02);
buf.put(m10);
buf.put(m11);
buf.put(m12);
buf.put(m20);
buf.put(m21);
buf.put(m22);
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
*/
public Matrix storeTranspose(FloatBuffer buf) {
buf.put(m00);
buf.put(m10);
buf.put(m20);
buf.put(m01);
buf.put(m11);
buf.put(m21);
buf.put(m02);
buf.put(m12);
buf.put(m22);
return this;
}
/**
* Add two matrices together and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f add(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m02 = left.m02 + right.m02;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
dest.m12 = left.m12 + right.m12;
dest.m20 = left.m20 + right.m20;
dest.m21 = left.m21 + right.m21;
dest.m22 = left.m22 + right.m22;
return dest;
}
/**
* Subtract the right matrix from the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f sub(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m02 = left.m02 - right.m02;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
dest.m12 = left.m12 - right.m12;
dest.m20 = left.m20 - right.m20;
dest.m21 = left.m21 - right.m21;
dest.m22 = left.m22 - right.m22;
return dest;
}
/**
* Multiply the right matrix by the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix3f mul(Matrix3f left, Matrix3f right, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
float m00 =
left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02;
float m01 =
left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02;
float m02 =
left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02;
float m10 =
left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12;
float m11 =
left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12;
float m12 =
left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12;
float m20 =
left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22;
float m21 =
left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22;
float m22 =
left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22;
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
return dest;
}
/**
* Transform a Vector by a matrix and return the result in a destination
* vector.
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector
*/
public static Vector3f transform(Matrix3f left, Vector3f right, Vector3f dest) {
if (dest == null)
dest = new Vector3f();
float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z;
float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z;
float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z;
dest.x = x;
dest.y = y;
dest.z = z;
return dest;
}
/**
* Transpose this matrix
* @return this
*/
public Matrix transpose() {
return transpose(this, this);
}
/**
* Transpose this matrix and place the result in another matrix
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public Matrix3f transpose(Matrix3f dest) {
return transpose(this, dest);
}
/**
* Transpose the source matrix and place the result into the destination matrix
* @param src The source matrix to be transposed
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public static Matrix3f transpose(Matrix3f src, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
float m00 = src.m00;
float m01 = src.m10;
float m02 = src.m20;
float m10 = src.m01;
float m11 = src.m11;
float m12 = src.m21;
float m20 = src.m02;
float m21 = src.m12;
float m22 = src.m22;
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
return dest;
}
/**
* @return the determinant of the matrix
*/
public float determinant() {
float f =
m00 * (m11 * m22 - m12 * m21)
+ m01 * (m12 * m20 - m10 * m22)
+ m02 * (m10 * m21 - m11 * m20);
return f;
}
/**
* Returns a string representation of this matrix
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(m00).append(' ').append(m10).append(' ').append(m20).append(' ').append('\n');
buf.append(m01).append(' ').append(m11).append(' ').append(m21).append(' ').append('\n');
buf.append(m02).append(' ').append(m12).append(' ').append(m22).append(' ').append('\n');
return buf.toString();
}
/**
* Invert this matrix
* @return this if successful, null otherwise
*/
public Matrix invert() {
return invert(this, this);
}
/**
* Invert the source matrix and put the result into the destination matrix
* @param src The source matrix to be inverted
* @param dest The destination matrix, or null if a new one is to be created
* @return The inverted matrix if successful, null otherwise
*/
public static Matrix3f invert(Matrix3f src, Matrix3f dest) {
float determinant = src.determinant();
if (determinant != 0) {
if (dest == null)
dest = new Matrix3f();
/* do it the ordinary way
*
* inv(A) = 1/det(A) * adj(T), where adj(T) = transpose(Conjugate Matrix)
*
* m00 m01 m02
* m10 m11 m12
* m20 m21 m22
*/
float determinant_inv = 1f/determinant;
// get the conjugate matrix
float t00 = src.m11 * src.m22 - src.m12* src.m21;
float t01 = - src.m10 * src.m22 + src.m12 * src.m20;
float t02 = src.m10 * src.m21 - src.m11 * src.m20;
float t10 = - src.m01 * src.m22 + src.m02 * src.m21;
float t11 = src.m00 * src.m22 - src.m02 * src.m20;
float t12 = - src.m00 * src.m21 + src.m01 * src.m20;
float t20 = src.m01 * src.m12 - src.m02 * src.m11;
float t21 = -src.m00 * src.m12 + src.m02 * src.m10;
float t22 = src.m00 * src.m11 - src.m01 * src.m10;
dest.m00 = t00*determinant_inv;
dest.m11 = t11*determinant_inv;
dest.m22 = t22*determinant_inv;
dest.m01 = t10*determinant_inv;
dest.m10 = t01*determinant_inv;
dest.m20 = t02*determinant_inv;
dest.m02 = t20*determinant_inv;
dest.m12 = t21*determinant_inv;
dest.m21 = t12*determinant_inv;
return dest;
} else
return null;
}
/**
* Negate this matrix
* @return this
*/
public Matrix negate() {
return negate(this);
}
/**
* Negate this matrix and place the result in a destination matrix.
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public Matrix3f negate(Matrix3f dest) {
return negate(this, dest);
}
/**
* Negate the source matrix and place the result in the destination matrix.
* @param src The source matrix
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public static Matrix3f negate(Matrix3f src, Matrix3f dest) {
if (dest == null)
dest = new Matrix3f();
dest.m00 = -src.m00;
dest.m01 = -src.m02;
dest.m02 = -src.m01;
dest.m10 = -src.m10;
dest.m11 = -src.m12;
dest.m12 = -src.m11;
dest.m20 = -src.m20;
dest.m21 = -src.m22;
dest.m22 = -src.m21;
return dest;
}
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public Matrix setIdentity() {
return setIdentity(this);
}
/**
* Set the matrix to be the identity matrix.
* @param m The matrix to be set to the identity
* @return m
*/
public static Matrix3f setIdentity(Matrix3f m) {
m.m00 = 1.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m10 = 0.0f;
m.m11 = 1.0f;
m.m12 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 1.0f;
return m;
}
/**
* Set this matrix to 0.
* @return this
*/
public Matrix setZero() {
return setZero(this);
}
/**
* Set the matrix matrix to 0.
* @param m The matrix to be set to 0
* @return m
*/
public static Matrix3f setZero(Matrix3f m) {
m.m00 = 0.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m10 = 0.0f;
m.m11 = 0.0f;
m.m12 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 0.0f;
return m;
}
}

View File

@ -0,0 +1,819 @@
package utils.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
* Holds a 4x4 float matrix.
*
* @author foo
*/
public class Matrix4f extends Matrix implements Serializable {
private static final long serialVersionUID = 1L;
public float m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33;
/**
* Construct a new matrix, initialized to the identity.
*/
public Matrix4f() {
super();
setIdentity();
}
public Matrix4f(final Matrix4f src) {
super();
load(src);
}
/**
* Returns a string representation of this matrix
*/
public String toString() {
StringBuilder buf = new StringBuilder();
buf.append(m00).append(' ').append(m10).append(' ').append(m20).append(' ').append(m30).append('\n');
buf.append(m01).append(' ').append(m11).append(' ').append(m21).append(' ').append(m31).append('\n');
buf.append(m02).append(' ').append(m12).append(' ').append(m22).append(' ').append(m32).append('\n');
buf.append(m03).append(' ').append(m13).append(' ').append(m23).append(' ').append(m33).append('\n');
return buf.toString();
}
/**
* Set this matrix to be the identity matrix.
* @return this
*/
public Matrix setIdentity() {
return setIdentity(this);
}
/**
* Set the given matrix to be the identity matrix.
* @param m The matrix to set to the identity
* @return m
*/
public static Matrix4f setIdentity(Matrix4f m) {
m.m00 = 1.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m03 = 0.0f;
m.m10 = 0.0f;
m.m11 = 1.0f;
m.m12 = 0.0f;
m.m13 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 1.0f;
m.m23 = 0.0f;
m.m30 = 0.0f;
m.m31 = 0.0f;
m.m32 = 0.0f;
m.m33 = 1.0f;
return m;
}
/**
* Set this matrix to 0.
* @return this
*/
public Matrix setZero() {
return setZero(this);
}
/**
* Set the given matrix to 0.
* @param m The matrix to set to 0
* @return m
*/
public static Matrix4f setZero(Matrix4f m) {
m.m00 = 0.0f;
m.m01 = 0.0f;
m.m02 = 0.0f;
m.m03 = 0.0f;
m.m10 = 0.0f;
m.m11 = 0.0f;
m.m12 = 0.0f;
m.m13 = 0.0f;
m.m20 = 0.0f;
m.m21 = 0.0f;
m.m22 = 0.0f;
m.m23 = 0.0f;
m.m30 = 0.0f;
m.m31 = 0.0f;
m.m32 = 0.0f;
m.m33 = 0.0f;
return m;
}
/**
* Load from another matrix4f
* @param src The source matrix
* @return this
*/
public Matrix4f load(Matrix4f src) {
return load(src, this);
}
/**
* Copy the source matrix to the destination matrix
* @param src The source matrix
* @param dest The destination matrix, or null of a new one is to be created
* @return The copied matrix
*/
public static Matrix4f load(Matrix4f src, Matrix4f dest) {
if (dest == null)
dest = new Matrix4f();
dest.m00 = src.m00;
dest.m01 = src.m01;
dest.m02 = src.m02;
dest.m03 = src.m03;
dest.m10 = src.m10;
dest.m11 = src.m11;
dest.m12 = src.m12;
dest.m13 = src.m13;
dest.m20 = src.m20;
dest.m21 = src.m21;
dest.m22 = src.m22;
dest.m23 = src.m23;
dest.m30 = src.m30;
dest.m31 = src.m31;
dest.m32 = src.m32;
dest.m33 = src.m33;
return dest;
}
/**
* Load from a float buffer. The buffer stores the matrix in column major
* (OpenGL) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix load(FloatBuffer buf) {
m00 = buf.get();
m01 = buf.get();
m02 = buf.get();
m03 = buf.get();
m10 = buf.get();
m11 = buf.get();
m12 = buf.get();
m13 = buf.get();
m20 = buf.get();
m21 = buf.get();
m22 = buf.get();
m23 = buf.get();
m30 = buf.get();
m31 = buf.get();
m32 = buf.get();
m33 = buf.get();
return this;
}
/**
* Load from a float buffer. The buffer stores the matrix in row major
* (maths) order.
*
* @param buf A float buffer to read from
* @return this
*/
public Matrix loadTranspose(FloatBuffer buf) {
m00 = buf.get();
m10 = buf.get();
m20 = buf.get();
m30 = buf.get();
m01 = buf.get();
m11 = buf.get();
m21 = buf.get();
m31 = buf.get();
m02 = buf.get();
m12 = buf.get();
m22 = buf.get();
m32 = buf.get();
m03 = buf.get();
m13 = buf.get();
m23 = buf.get();
m33 = buf.get();
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
*/
public Matrix store(FloatBuffer buf) {
buf.put(m00);
buf.put(m01);
buf.put(m02);
buf.put(m03);
buf.put(m10);
buf.put(m11);
buf.put(m12);
buf.put(m13);
buf.put(m20);
buf.put(m21);
buf.put(m22);
buf.put(m23);
buf.put(m30);
buf.put(m31);
buf.put(m32);
buf.put(m33);
return this;
}
/**
* Store this matrix in a float buffer. The matrix is stored in row
* major (maths) order.
* @param buf The buffer to store this matrix in
*/
public Matrix storeTranspose(FloatBuffer buf) {
buf.put(m00);
buf.put(m10);
buf.put(m20);
buf.put(m30);
buf.put(m01);
buf.put(m11);
buf.put(m21);
buf.put(m31);
buf.put(m02);
buf.put(m12);
buf.put(m22);
buf.put(m32);
buf.put(m03);
buf.put(m13);
buf.put(m23);
buf.put(m33);
return this;
}
/**
* Store the rotation portion of this matrix in a float buffer. The matrix is stored in column
* major (openGL) order.
* @param buf The buffer to store this matrix in
*/
public Matrix store3f(FloatBuffer buf) {
buf.put(m00);
buf.put(m01);
buf.put(m02);
buf.put(m10);
buf.put(m11);
buf.put(m12);
buf.put(m20);
buf.put(m21);
buf.put(m22);
return this;
}
/**
* Add two matrices together and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix4f add(Matrix4f left, Matrix4f right, Matrix4f dest) {
if (dest == null)
dest = new Matrix4f();
dest.m00 = left.m00 + right.m00;
dest.m01 = left.m01 + right.m01;
dest.m02 = left.m02 + right.m02;
dest.m03 = left.m03 + right.m03;
dest.m10 = left.m10 + right.m10;
dest.m11 = left.m11 + right.m11;
dest.m12 = left.m12 + right.m12;
dest.m13 = left.m13 + right.m13;
dest.m20 = left.m20 + right.m20;
dest.m21 = left.m21 + right.m21;
dest.m22 = left.m22 + right.m22;
dest.m23 = left.m23 + right.m23;
dest.m30 = left.m30 + right.m30;
dest.m31 = left.m31 + right.m31;
dest.m32 = left.m32 + right.m32;
dest.m33 = left.m33 + right.m33;
return dest;
}
/**
* Subtract the right matrix from the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix4f sub(Matrix4f left, Matrix4f right, Matrix4f dest) {
if (dest == null)
dest = new Matrix4f();
dest.m00 = left.m00 - right.m00;
dest.m01 = left.m01 - right.m01;
dest.m02 = left.m02 - right.m02;
dest.m03 = left.m03 - right.m03;
dest.m10 = left.m10 - right.m10;
dest.m11 = left.m11 - right.m11;
dest.m12 = left.m12 - right.m12;
dest.m13 = left.m13 - right.m13;
dest.m20 = left.m20 - right.m20;
dest.m21 = left.m21 - right.m21;
dest.m22 = left.m22 - right.m22;
dest.m23 = left.m23 - right.m23;
dest.m30 = left.m30 - right.m30;
dest.m31 = left.m31 - right.m31;
dest.m32 = left.m32 - right.m32;
dest.m33 = left.m33 - right.m33;
return dest;
}
/**
* Multiply the right matrix by the left and place the result in a third matrix.
* @param left The left source matrix
* @param right The right source matrix
* @param dest The destination matrix, or null if a new one is to be created
* @return the destination matrix
*/
public static Matrix4f mul(Matrix4f left, Matrix4f right, Matrix4f dest) {
if (dest == null)
dest = new Matrix4f();
float m00 = left.m00 * right.m00 + left.m10 * right.m01 + left.m20 * right.m02 + left.m30 * right.m03;
float m01 = left.m01 * right.m00 + left.m11 * right.m01 + left.m21 * right.m02 + left.m31 * right.m03;
float m02 = left.m02 * right.m00 + left.m12 * right.m01 + left.m22 * right.m02 + left.m32 * right.m03;
float m03 = left.m03 * right.m00 + left.m13 * right.m01 + left.m23 * right.m02 + left.m33 * right.m03;
float m10 = left.m00 * right.m10 + left.m10 * right.m11 + left.m20 * right.m12 + left.m30 * right.m13;
float m11 = left.m01 * right.m10 + left.m11 * right.m11 + left.m21 * right.m12 + left.m31 * right.m13;
float m12 = left.m02 * right.m10 + left.m12 * right.m11 + left.m22 * right.m12 + left.m32 * right.m13;
float m13 = left.m03 * right.m10 + left.m13 * right.m11 + left.m23 * right.m12 + left.m33 * right.m13;
float m20 = left.m00 * right.m20 + left.m10 * right.m21 + left.m20 * right.m22 + left.m30 * right.m23;
float m21 = left.m01 * right.m20 + left.m11 * right.m21 + left.m21 * right.m22 + left.m31 * right.m23;
float m22 = left.m02 * right.m20 + left.m12 * right.m21 + left.m22 * right.m22 + left.m32 * right.m23;
float m23 = left.m03 * right.m20 + left.m13 * right.m21 + left.m23 * right.m22 + left.m33 * right.m23;
float m30 = left.m00 * right.m30 + left.m10 * right.m31 + left.m20 * right.m32 + left.m30 * right.m33;
float m31 = left.m01 * right.m30 + left.m11 * right.m31 + left.m21 * right.m32 + left.m31 * right.m33;
float m32 = left.m02 * right.m30 + left.m12 * right.m31 + left.m22 * right.m32 + left.m32 * right.m33;
float m33 = left.m03 * right.m30 + left.m13 * right.m31 + left.m23 * right.m32 + left.m33 * right.m33;
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m03 = m03;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m13 = m13;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
dest.m23 = m23;
dest.m30 = m30;
dest.m31 = m31;
dest.m32 = m32;
dest.m33 = m33;
return dest;
}
/**
* Transform a Vector by a matrix and return the result in a destination
* vector.
* @param left The left matrix
* @param right The right vector
* @param dest The destination vector, or null if a new one is to be created
* @return the destination vector
*/
public static Vector4f transform(Matrix4f left, Vector4f right, Vector4f dest) {
if (dest == null)
dest = new Vector4f();
float x = left.m00 * right.x + left.m10 * right.y + left.m20 * right.z + left.m30 * right.w;
float y = left.m01 * right.x + left.m11 * right.y + left.m21 * right.z + left.m31 * right.w;
float z = left.m02 * right.x + left.m12 * right.y + left.m22 * right.z + left.m32 * right.w;
float w = left.m03 * right.x + left.m13 * right.y + left.m23 * right.z + left.m33 * right.w;
dest.x = x;
dest.y = y;
dest.z = z;
dest.w = w;
return dest;
}
/**
* Transpose this matrix
* @return this
*/
public Matrix transpose() {
return transpose(this);
}
/**
* Translate this matrix
* @param vec The vector to translate by
* @return this
*/
public Matrix4f translate(Vector2f vec) {
return translate(vec, this);
}
/**
* Translate this matrix
* @param vec The vector to translate by
* @return this
*/
public Matrix4f translate(Vector3f vec) {
return translate(vec, this);
}
/**
* Scales this matrix
* @param vec The vector to scale by
* @return this
*/
public Matrix4f scale(Vector3f vec) {
return scale(vec, this, this);
}
/**
* Scales the source matrix and put the result in the destination matrix
* @param vec The vector to scale by
* @param src The source matrix
* @param dest The destination matrix, or null if a new matrix is to be created
* @return The scaled matrix
*/
public static Matrix4f scale(Vector3f vec, Matrix4f src, Matrix4f dest) {
if (dest == null)
dest = new Matrix4f();
dest.m00 = src.m00 * vec.x;
dest.m01 = src.m01 * vec.x;
dest.m02 = src.m02 * vec.x;
dest.m03 = src.m03 * vec.x;
dest.m10 = src.m10 * vec.y;
dest.m11 = src.m11 * vec.y;
dest.m12 = src.m12 * vec.y;
dest.m13 = src.m13 * vec.y;
dest.m20 = src.m20 * vec.z;
dest.m21 = src.m21 * vec.z;
dest.m22 = src.m22 * vec.z;
dest.m23 = src.m23 * vec.z;
return dest;
}
/**
* Rotates the matrix around the given axis the specified angle
* @param angle the angle, in radians.
* @param axis The vector representing the rotation axis. Must be normalized.
* @return this
*/
public Matrix4f rotate(float angle, Vector3f axis) {
return rotate(angle, axis, this);
}
/**
* Rotates the matrix around the given axis the specified angle
* @param angle the angle, in radians.
* @param axis The vector representing the rotation axis. Must be normalized.
* @param dest The matrix to put the result, or null if a new matrix is to be created
* @return The rotated matrix
*/
public Matrix4f rotate(float angle, Vector3f axis, Matrix4f dest) {
return rotate(angle, axis, this, dest);
}
/**
* Rotates the source matrix around the given axis the specified angle and
* put the result in the destination matrix.
* @param angle the angle, in radians.
* @param axis The vector representing the rotation axis. Must be normalized.
* @param src The matrix to rotate
* @param dest The matrix to put the result, or null if a new matrix is to be created
* @return The rotated matrix
*/
public static Matrix4f rotate(float angle, Vector3f axis, Matrix4f src, Matrix4f dest) {
if (dest == null)
dest = new Matrix4f();
float c = (float) Math.cos(angle);
float s = (float) Math.sin(angle);
float oneminusc = 1.0f - c;
float xy = axis.x*axis.y;
float yz = axis.y*axis.z;
float xz = axis.x*axis.z;
float xs = axis.x*s;
float ys = axis.y*s;
float zs = axis.z*s;
float f00 = axis.x*axis.x*oneminusc+c;
float f01 = xy*oneminusc+zs;
float f02 = xz*oneminusc-ys;
// n[3] not used
float f10 = xy*oneminusc-zs;
float f11 = axis.y*axis.y*oneminusc+c;
float f12 = yz*oneminusc+xs;
// n[7] not used
float f20 = xz*oneminusc+ys;
float f21 = yz*oneminusc-xs;
float f22 = axis.z*axis.z*oneminusc+c;
float t00 = src.m00 * f00 + src.m10 * f01 + src.m20 * f02;
float t01 = src.m01 * f00 + src.m11 * f01 + src.m21 * f02;
float t02 = src.m02 * f00 + src.m12 * f01 + src.m22 * f02;
float t03 = src.m03 * f00 + src.m13 * f01 + src.m23 * f02;
float t10 = src.m00 * f10 + src.m10 * f11 + src.m20 * f12;
float t11 = src.m01 * f10 + src.m11 * f11 + src.m21 * f12;
float t12 = src.m02 * f10 + src.m12 * f11 + src.m22 * f12;
float t13 = src.m03 * f10 + src.m13 * f11 + src.m23 * f12;
dest.m20 = src.m00 * f20 + src.m10 * f21 + src.m20 * f22;
dest.m21 = src.m01 * f20 + src.m11 * f21 + src.m21 * f22;
dest.m22 = src.m02 * f20 + src.m12 * f21 + src.m22 * f22;
dest.m23 = src.m03 * f20 + src.m13 * f21 + src.m23 * f22;
dest.m00 = t00;
dest.m01 = t01;
dest.m02 = t02;
dest.m03 = t03;
dest.m10 = t10;
dest.m11 = t11;
dest.m12 = t12;
dest.m13 = t13;
return dest;
}
/**
* Translate this matrix and stash the result in another matrix
* @param vec The vector to translate by
* @param dest The destination matrix or null if a new matrix is to be created
* @return the translated matrix
*/
public Matrix4f translate(Vector3f vec, Matrix4f dest) {
return translate(vec, this, dest);
}
/**
* Translate the source matrix and stash the result in the destination matrix
* @param vec The vector to translate by
* @param src The source matrix
* @param dest The destination matrix or null if a new matrix is to be created
* @return The translated matrix
*/
public static Matrix4f translate(Vector3f vec, Matrix4f src, Matrix4f dest) {
if (dest == null)
dest = new Matrix4f();
dest.m30 += src.m00 * vec.x + src.m10 * vec.y + src.m20 * vec.z;
dest.m31 += src.m01 * vec.x + src.m11 * vec.y + src.m21 * vec.z;
dest.m32 += src.m02 * vec.x + src.m12 * vec.y + src.m22 * vec.z;
dest.m33 += src.m03 * vec.x + src.m13 * vec.y + src.m23 * vec.z;
return dest;
}
/**
* Translate this matrix and stash the result in another matrix
* @param vec The vector to translate by
* @param dest The destination matrix or null if a new matrix is to be created
* @return the translated matrix
*/
public Matrix4f translate(Vector2f vec, Matrix4f dest) {
return translate(vec, this, dest);
}
/**
* Translate the source matrix and stash the result in the destination matrix
* @param vec The vector to translate by
* @param src The source matrix
* @param dest The destination matrix or null if a new matrix is to be created
* @return The translated matrix
*/
public static Matrix4f translate(Vector2f vec, Matrix4f src, Matrix4f dest) {
if (dest == null)
dest = new Matrix4f();
dest.m30 += src.m00 * vec.x + src.m10 * vec.y;
dest.m31 += src.m01 * vec.x + src.m11 * vec.y;
dest.m32 += src.m02 * vec.x + src.m12 * vec.y;
dest.m33 += src.m03 * vec.x + src.m13 * vec.y;
return dest;
}
/**
* Transpose this matrix and place the result in another matrix
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public Matrix4f transpose(Matrix4f dest) {
return transpose(this, dest);
}
/**
* Transpose the source matrix and place the result in the destination matrix
* @param src The source matrix
* @param dest The destination matrix or null if a new matrix is to be created
* @return the transposed matrix
*/
public static Matrix4f transpose(Matrix4f src, Matrix4f dest) {
if (dest == null)
dest = new Matrix4f();
float m00 = src.m00;
float m01 = src.m10;
float m02 = src.m20;
float m03 = src.m30;
float m10 = src.m01;
float m11 = src.m11;
float m12 = src.m21;
float m13 = src.m31;
float m20 = src.m02;
float m21 = src.m12;
float m22 = src.m22;
float m23 = src.m32;
float m30 = src.m03;
float m31 = src.m13;
float m32 = src.m23;
float m33 = src.m33;
dest.m00 = m00;
dest.m01 = m01;
dest.m02 = m02;
dest.m03 = m03;
dest.m10 = m10;
dest.m11 = m11;
dest.m12 = m12;
dest.m13 = m13;
dest.m20 = m20;
dest.m21 = m21;
dest.m22 = m22;
dest.m23 = m23;
dest.m30 = m30;
dest.m31 = m31;
dest.m32 = m32;
dest.m33 = m33;
return dest;
}
/**
* @return the determinant of the matrix
*/
public float determinant() {
float f =
m00
* ((m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32)
- m13 * m22 * m31
- m11 * m23 * m32
- m12 * m21 * m33);
f -= m01
* ((m10 * m22 * m33 + m12 * m23 * m30 + m13 * m20 * m32)
- m13 * m22 * m30
- m10 * m23 * m32
- m12 * m20 * m33);
f += m02
* ((m10 * m21 * m33 + m11 * m23 * m30 + m13 * m20 * m31)
- m13 * m21 * m30
- m10 * m23 * m31
- m11 * m20 * m33);
f -= m03
* ((m10 * m21 * m32 + m11 * m22 * m30 + m12 * m20 * m31)
- m12 * m21 * m30
- m10 * m22 * m31
- m11 * m20 * m32);
return f;
}
/**
* Calculate the determinant of a 3x3 matrix
* @return result
*/
private static float determinant3x3(float t00, float t01, float t02,
float t10, float t11, float t12,
float t20, float t21, float t22)
{
return t00 * (t11 * t22 - t12 * t21)
+ t01 * (t12 * t20 - t10 * t22)
+ t02 * (t10 * t21 - t11 * t20);
}
/**
* Invert this matrix
* @return this if successful, null otherwise
*/
public Matrix invert() {
return invert(this, this);
}
/**
* Invert the source matrix and put the result in the destination
* @param src The source matrix
* @param dest The destination matrix, or null if a new matrix is to be created
* @return The inverted matrix if successful, null otherwise
*/
public static Matrix4f invert(Matrix4f src, Matrix4f dest) {
float determinant = src.determinant();
if (determinant != 0) {
/*
* m00 m01 m02 m03
* m10 m11 m12 m13
* m20 m21 m22 m23
* m30 m31 m32 m33
*/
if (dest == null)
dest = new Matrix4f();
float determinant_inv = 1f/determinant;
// first row
float t00 = determinant3x3(src.m11, src.m12, src.m13, src.m21, src.m22, src.m23, src.m31, src.m32, src.m33);
float t01 = -determinant3x3(src.m10, src.m12, src.m13, src.m20, src.m22, src.m23, src.m30, src.m32, src.m33);
float t02 = determinant3x3(src.m10, src.m11, src.m13, src.m20, src.m21, src.m23, src.m30, src.m31, src.m33);
float t03 = -determinant3x3(src.m10, src.m11, src.m12, src.m20, src.m21, src.m22, src.m30, src.m31, src.m32);
// second row
float t10 = -determinant3x3(src.m01, src.m02, src.m03, src.m21, src.m22, src.m23, src.m31, src.m32, src.m33);
float t11 = determinant3x3(src.m00, src.m02, src.m03, src.m20, src.m22, src.m23, src.m30, src.m32, src.m33);
float t12 = -determinant3x3(src.m00, src.m01, src.m03, src.m20, src.m21, src.m23, src.m30, src.m31, src.m33);
float t13 = determinant3x3(src.m00, src.m01, src.m02, src.m20, src.m21, src.m22, src.m30, src.m31, src.m32);
// third row
float t20 = determinant3x3(src.m01, src.m02, src.m03, src.m11, src.m12, src.m13, src.m31, src.m32, src.m33);
float t21 = -determinant3x3(src.m00, src.m02, src.m03, src.m10, src.m12, src.m13, src.m30, src.m32, src.m33);
float t22 = determinant3x3(src.m00, src.m01, src.m03, src.m10, src.m11, src.m13, src.m30, src.m31, src.m33);
float t23 = -determinant3x3(src.m00, src.m01, src.m02, src.m10, src.m11, src.m12, src.m30, src.m31, src.m32);
// fourth row
float t30 = -determinant3x3(src.m01, src.m02, src.m03, src.m11, src.m12, src.m13, src.m21, src.m22, src.m23);
float t31 = determinant3x3(src.m00, src.m02, src.m03, src.m10, src.m12, src.m13, src.m20, src.m22, src.m23);
float t32 = -determinant3x3(src.m00, src.m01, src.m03, src.m10, src.m11, src.m13, src.m20, src.m21, src.m23);
float t33 = determinant3x3(src.m00, src.m01, src.m02, src.m10, src.m11, src.m12, src.m20, src.m21, src.m22);
// transpose and divide by the determinant
dest.m00 = t00*determinant_inv;
dest.m11 = t11*determinant_inv;
dest.m22 = t22*determinant_inv;
dest.m33 = t33*determinant_inv;
dest.m01 = t10*determinant_inv;
dest.m10 = t01*determinant_inv;
dest.m20 = t02*determinant_inv;
dest.m02 = t20*determinant_inv;
dest.m12 = t21*determinant_inv;
dest.m21 = t12*determinant_inv;
dest.m03 = t30*determinant_inv;
dest.m30 = t03*determinant_inv;
dest.m13 = t31*determinant_inv;
dest.m31 = t13*determinant_inv;
dest.m32 = t23*determinant_inv;
dest.m23 = t32*determinant_inv;
return dest;
} else
return null;
}
/**
* Negate this matrix
* @return this
*/
public Matrix negate() {
return negate(this);
}
/**
* Negate this matrix and place the result in a destination matrix.
* @param dest The destination matrix, or null if a new matrix is to be created
* @return the negated matrix
*/
public Matrix4f negate(Matrix4f dest) {
return negate(this, dest);
}
/**
* Negate this matrix and place the result in a destination matrix.
* @param src The source matrix
* @param dest The destination matrix, or null if a new matrix is to be created
* @return The negated matrix
*/
public static Matrix4f negate(Matrix4f src, Matrix4f dest) {
if (dest == null)
dest = new Matrix4f();
dest.m00 = -src.m00;
dest.m01 = -src.m01;
dest.m02 = -src.m02;
dest.m03 = -src.m03;
dest.m10 = -src.m10;
dest.m11 = -src.m11;
dest.m12 = -src.m12;
dest.m13 = -src.m13;
dest.m20 = -src.m20;
dest.m21 = -src.m21;
dest.m22 = -src.m22;
dest.m23 = -src.m23;
dest.m30 = -src.m30;
dest.m31 = -src.m31;
dest.m32 = -src.m32;
dest.m33 = -src.m33;
return dest;
}
}

View File

@ -0,0 +1,20 @@
package utils.vectors;
import java.nio.FloatBuffer;
public interface ReadableVector {
/**
* @return the length of the vector
*/
float length();
/**
* @return the length squared of the vector
*/
float lengthSquared();
/**
* Store this vector in a FloatBuffer
* @param buf The buffer to store it in, at the current position
* @return this
*/
Vector store(FloatBuffer buf);
}

View File

@ -0,0 +1,12 @@
package utils.vectors;
public interface ReadableVector2f {
/**
* @return x
*/
float getX();
/**
* @return y
*/
float getY();
}

View File

@ -0,0 +1,8 @@
package utils.vectors;
public interface ReadableVector3f extends ReadableVector2f {
/**
* @return z
*/
float getZ();
}

View File

@ -0,0 +1,10 @@
package utils.vectors;
public interface ReadableVector4f extends ReadableVector3f {
/**
* @return w
*/
float getW();
}

View File

@ -0,0 +1,82 @@
package utils.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
*
* Base class for vectors.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public abstract class Vector implements Serializable, ReadableVector {
/**
* Constructor for Vector.
*/
protected Vector() {
super();
}
/**
* @return the length of the vector
*/
public final float length() {
return (float) Math.sqrt(lengthSquared());
}
/**
* @return the length squared of the vector
*/
public abstract float lengthSquared();
/**
* Load this vector from a FloatBuffer
* @param buf The buffer to load it from, at the current position
* @return this
*/
public abstract Vector load(FloatBuffer buf);
/**
* Negate a vector
* @return this
*/
public abstract Vector negate();
/**
* Normalise this vector
* @return this
*/
public final Vector normalise() {
float len = length();
if (len != 0.0f) {
float l = 1.0f / len;
return scale(l);
} else
throw new IllegalStateException("Zero length vector");
}
/**
* Store this vector in a FloatBuffer
* @param buf The buffer to store it in, at the current position
* @return this
*/
public abstract Vector store(FloatBuffer buf);
/**
* Scale this vector
* @param scale The scale factor
* @return this
*/
public abstract Vector scale(float scale);
}

View File

@ -0,0 +1,269 @@
package utils.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
*
* Holds a 2-tuple vector.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public class Vector2f extends Vector implements Serializable, ReadableVector2f, WriteableVector2f {
private static final long serialVersionUID = 1L;
public float x, y;
/**
* Constructor for Vector2f.
*/
public Vector2f() {
super();
}
/**
* Constructor.
*/
public Vector2f(ReadableVector2f src) {
set(src);
}
/**
* Constructor.
*/
public Vector2f(float x, float y) {
set(x, y);
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
public void set(float x, float y) {
this.x = x;
this.y = y;
}
/**
* Load from another Vector2f
* @param src The source vector
* @return this
*/
public Vector2f set(ReadableVector2f src) {
x = src.getX();
y = src.getY();
return this;
}
/**
* @return the length squared of the vector
*/
public float lengthSquared() {
return x * x + y * y;
}
/**
* Translate a vector
* @param x The translation in x
* @param y the translation in y
* @return this
*/
public Vector2f translate(float x, float y) {
this.x += x;
this.y += y;
return this;
}
/**
* Negate a vector
* @return this
*/
public Vector negate() {
x = -x;
y = -y;
return this;
}
/**
* Negate a vector and place the result in a destination vector.
* @param dest The destination vector or null if a new vector is to be created
* @return the negated vector
*/
public Vector2f negate(Vector2f dest) {
if (dest == null)
dest = new Vector2f();
dest.x = -x;
dest.y = -y;
return dest;
}
/**
* Normalise this vector and place the result in another vector.
* @param dest The destination vector, or null if a new vector is to be created
* @return the normalised vector
*/
public Vector2f normalise(Vector2f dest) {
float l = length();
if (dest == null)
dest = new Vector2f(x / l, y / l);
else
dest.set(x / l, y / l);
return dest;
}
/**
* The dot product of two vectors is calculated as
* v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
* @param left The LHS vector
* @param right The RHS vector
* @return left dot right
*/
public static float dot(Vector2f left, Vector2f right) {
return left.x * right.x + left.y * right.y;
}
/**
* Calculate the angle between two vectors, in radians
* @param a A vector
* @param b The other vector
* @return the angle between the two vectors, in radians
*/
public static float angle(Vector2f a, Vector2f b) {
float dls = dot(a, b) / (a.length() * b.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float)Math.acos(dls);
}
/**
* Add a vector to another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return the sum of left and right in dest
*/
public static Vector2f add(Vector2f left, Vector2f right, Vector2f dest) {
if (dest == null)
return new Vector2f(left.x + right.x, left.y + right.y);
else {
dest.set(left.x + right.x, left.y + right.y);
return dest;
}
}
/**
* Subtract a vector from another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return left minus right in dest
*/
public static Vector2f sub(Vector2f left, Vector2f right, Vector2f dest) {
if (dest == null)
return new Vector2f(left.x - right.x, left.y - right.y);
else {
dest.set(left.x - right.x, left.y - right.y);
return dest;
}
}
/**
* Store this vector in a FloatBuffer
* @param buf The buffer to store it in, at the current position
* @return this
*/
public Vector store(FloatBuffer buf) {
buf.put(x);
buf.put(y);
return this;
}
/**
* Load this vector from a FloatBuffer
* @param buf The buffer to load it from, at the current position
* @return this
*/
public Vector load(FloatBuffer buf) {
x = buf.get();
y = buf.get();
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#scale(float)
*/
public Vector scale(float scale) {
x *= scale;
y *= scale;
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuilder sb = new StringBuilder(64);
sb.append("Vector2f[");
sb.append(x);
sb.append(", ");
sb.append(y);
sb.append(']');
return sb.toString();
}
/**
* @return x
*/
public final float getX() {
return x;
}
/**
* @return y
*/
public final float getY() {
return y;
}
/**
* Set X
* @param x
*/
public final void setX(float x) {
this.x = x;
}
/**
* Set Y
* @param y
*/
public final void setY(float y) {
this.y = y;
}
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector2f other = (Vector2f)obj;
if (x == other.x && y == other.y) return true;
return false;
}
}

View File

@ -0,0 +1,328 @@
package utils.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
*
* Holds a 3-tuple vector.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public class Vector3f extends Vector implements Serializable, ReadableVector3f, WriteableVector3f {
private static final long serialVersionUID = 1L;
public float x, y, z;
/**
* Constructor for Vector3f.
*/
public Vector3f() {
super();
}
/**
* Constructor
*/
public Vector3f(ReadableVector3f src) {
set(src);
}
/**
* Constructor
*/
public Vector3f(float x, float y, float z) {
set(x, y, z);
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
public void set(float x, float y) {
this.x = x;
this.y = y;
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float)
*/
public void set(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Load from another Vector3f
* @param src The source vector
* @return this
*/
public Vector3f set(ReadableVector3f src) {
x = src.getX();
y = src.getY();
z = src.getZ();
return this;
}
/**
* @return the length squared of the vector
*/
public float lengthSquared() {
return x * x + y * y + z * z;
}
/**
* Translate a vector
* @param x The translation in x
* @param y the translation in y
* @return this
*/
public Vector3f translate(float x, float y, float z) {
this.x += x;
this.y += y;
this.z += z;
return this;
}
/**
* Add a vector to another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return the sum of left and right in dest
*/
public static Vector3f add(Vector3f left, Vector3f right, Vector3f dest) {
if (dest == null)
return new Vector3f(left.x + right.x, left.y + right.y, left.z + right.z);
else {
dest.set(left.x + right.x, left.y + right.y, left.z + right.z);
return dest;
}
}
/**
* Subtract a vector from another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return left minus right in dest
*/
public static Vector3f sub(Vector3f left, Vector3f right, Vector3f dest) {
if (dest == null)
return new Vector3f(left.x - right.x, left.y - right.y, left.z - right.z);
else {
dest.set(left.x - right.x, left.y - right.y, left.z - right.z);
return dest;
}
}
/**
* The cross product of two vectors.
*
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination result, or null if a new vector is to be created
* @return left cross right
*/
public static Vector3f cross(
Vector3f left,
Vector3f right,
Vector3f dest)
{
if (dest == null)
dest = new Vector3f();
dest.set(
left.y * right.z - left.z * right.y,
right.x * left.z - right.z * left.x,
left.x * right.y - left.y * right.x
);
return dest;
}
/**
* Negate a vector
* @return this
*/
public Vector negate() {
x = -x;
y = -y;
z = -z;
return this;
}
/**
* Negate a vector and place the result in a destination vector.
* @param dest The destination vector or null if a new vector is to be created
* @return the negated vector
*/
public Vector3f negate(Vector3f dest) {
if (dest == null)
dest = new Vector3f();
dest.x = -x;
dest.y = -y;
dest.z = -z;
return dest;
}
/**
* Normalise this vector and place the result in another vector.
* @param dest The destination vector, or null if a new vector is to be created
* @return the normalised vector
*/
public Vector3f normalise(Vector3f dest) {
float l = length();
if (dest == null)
dest = new Vector3f(x / l, y / l, z / l);
else
dest.set(x / l, y / l, z / l);
return dest;
}
/**
* The dot product of two vectors is calculated as
* v1.x * v2.x + v1.y * v2.y + v1.z * v2.z
* @param left The LHS vector
* @param right The RHS vector
* @return left dot right
*/
public static float dot(Vector3f left, Vector3f right) {
return left.x * right.x + left.y * right.y + left.z * right.z;
}
/**
* Calculate the angle between two vectors, in radians
* @param a A vector
* @param b The other vector
* @return the angle between the two vectors, in radians
*/
public static float angle(Vector3f a, Vector3f b) {
float dls = dot(a, b) / (a.length() * b.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float)Math.acos(dls);
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#load(FloatBuffer)
*/
public Vector load(FloatBuffer buf) {
x = buf.get();
y = buf.get();
z = buf.get();
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#scale(float)
*/
public Vector scale(float scale) {
x *= scale;
y *= scale;
z *= scale;
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#store(FloatBuffer)
*/
public Vector store(FloatBuffer buf) {
buf.put(x);
buf.put(y);
buf.put(z);
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuilder sb = new StringBuilder(64);
sb.append("Vector3f[");
sb.append(x);
sb.append(", ");
sb.append(y);
sb.append(", ");
sb.append(z);
sb.append(']');
return sb.toString();
}
/**
* @return x
*/
public final float getX() {
return x;
}
/**
* @return y
*/
public final float getY() {
return y;
}
/**
* Set X
* @param x
*/
public final void setX(float x) {
this.x = x;
}
/**
* Set Y
* @param y
*/
public final void setY(float y) {
this.y = y;
}
/**
* Set Z
* @param z
*/
public void setZ(float z) {
this.z = z;
}
/* (Overrides)
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
public float getZ() {
return z;
}
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector3f other = (Vector3f)obj;
if (x == other.x && y == other.y && z == other.z) return true;
return false;
}
}

View File

@ -0,0 +1,320 @@
package utils.vectors;
import java.io.Serializable;
import java.nio.FloatBuffer;
/**
*
* Holds a 4-tuple vector.
*
* @author cix_foo <cix_foo@users.sourceforge.net>
* @version $Revision$
* $Id$
*/
public class Vector4f extends Vector implements Serializable, ReadableVector4f, WriteableVector4f {
private static final long serialVersionUID = 1L;
public float x, y, z, w;
/**
* Constructor for Vector4f.
*/
public Vector4f() {
super();
}
/**
* Constructor
*/
public Vector4f(ReadableVector4f src) {
set(src);
}
/**
* Constructor
*/
public Vector4f(float x, float y, float z, float w) {
set(x, y, z, w);
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector2f#set(float, float)
*/
public void set(float x, float y) {
this.x = x;
this.y = y;
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector3f#set(float, float, float)
*/
public void set(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
/* (non-Javadoc)
* @see org.lwjgl.util.vector.WritableVector4f#set(float, float, float, float)
*/
public void set(float x, float y, float z, float w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
/**
* Load from another Vector4f
* @param src The source vector
* @return this
*/
public Vector4f set(ReadableVector4f src) {
x = src.getX();
y = src.getY();
z = src.getZ();
w = src.getW();
return this;
}
/**
* @return the length squared of the vector
*/
public float lengthSquared() {
return x * x + y * y + z * z + w * w;
}
/**
* Translate a vector
* @param x The translation in x
* @param y the translation in y
* @return this
*/
public Vector4f translate(float x, float y, float z, float w) {
this.x += x;
this.y += y;
this.z += z;
this.w += w;
return this;
}
/**
* Add a vector to another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return the sum of left and right in dest
*/
public static Vector4f add(Vector4f left, Vector4f right, Vector4f dest) {
if (dest == null)
return new Vector4f(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w);
else {
dest.set(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w);
return dest;
}
}
/**
* Subtract a vector from another vector and place the result in a destination
* vector.
* @param left The LHS vector
* @param right The RHS vector
* @param dest The destination vector, or null if a new vector is to be created
* @return left minus right in dest
*/
public static Vector4f sub(Vector4f left, Vector4f right, Vector4f dest) {
if (dest == null)
return new Vector4f(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w);
else {
dest.set(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w);
return dest;
}
}
/**
* Negate a vector
* @return this
*/
public Vector negate() {
x = -x;
y = -y;
z = -z;
w = -w;
return this;
}
/**
* Negate a vector and place the result in a destination vector.
* @param dest The destination vector or null if a new vector is to be created
* @return the negated vector
*/
public Vector4f negate(Vector4f dest) {
if (dest == null)
dest = new Vector4f();
dest.x = -x;
dest.y = -y;
dest.z = -z;
dest.w = -w;
return dest;
}
/**
* Normalise this vector and place the result in another vector.
* @param dest The destination vector, or null if a new vector is to be created
* @return the normalised vector
*/
public Vector4f normalise(Vector4f dest) {
float l = length();
if (dest == null)
dest = new Vector4f(x / l, y / l, z / l, w / l);
else
dest.set(x / l, y / l, z / l, w / l);
return dest;
}
/**
* The dot product of two vectors is calculated as
* v1.x * v2.x + v1.y * v2.y + v1.z * v2.z + v1.w * v2.w
* @param left The LHS vector
* @param right The RHS vector
* @return left dot right
*/
public static float dot(Vector4f left, Vector4f right) {
return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
}
/**
* Calculate the angle between two vectors, in radians
* @param a A vector
* @param b The other vector
* @return the angle between the two vectors, in radians
*/
public static float angle(Vector4f a, Vector4f b) {
float dls = dot(a, b) / (a.length() * b.length());
if (dls < -1f)
dls = -1f;
else if (dls > 1.0f)
dls = 1.0f;
return (float)Math.acos(dls);
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#load(FloatBuffer)
*/
public Vector load(FloatBuffer buf) {
x = buf.get();
y = buf.get();
z = buf.get();
w = buf.get();
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#scale(float)
*/
public Vector scale(float scale) {
x *= scale;
y *= scale;
z *= scale;
w *= scale;
return this;
}
/* (non-Javadoc)
* @see org.lwjgl.vector.Vector#store(FloatBuffer)
*/
public Vector store(FloatBuffer buf) {
buf.put(x);
buf.put(y);
buf.put(z);
buf.put(w);
return this;
}
public String toString() {
return "Vector4f: " + x + " " + y + " " + z + " " + w;
}
/**
* @return x
*/
public final float getX() {
return x;
}
/**
* @return y
*/
public final float getY() {
return y;
}
/**
* Set X
* @param x
*/
public final void setX(float x) {
this.x = x;
}
/**
* Set Y
* @param y
*/
public final void setY(float y) {
this.y = y;
}
/**
* Set Z
* @param z
*/
public void setZ(float z) {
this.z = z;
}
/* (Overrides)
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
public float getZ() {
return z;
}
/**
* Set W
* @param w
*/
public void setW(float w) {
this.w = w;
}
/* (Overrides)
* @see org.lwjgl.vector.ReadableVector3f#getZ()
*/
public float getW() {
return w;
}
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vector4f other = (Vector4f)obj;
if (x == other.x && y == other.y && z == other.z && w == other.w) return true;
return false;
}
}

View File

@ -0,0 +1,23 @@
package utils.vectors;
public interface WriteableVector2f {
/**
* Set the X value
* @param x
*/
void setX(float x);
/**
* Set the Y value
* @param y
*/
void setY(float y);
/**
* Set the X,Y values
* @param x
* @param y
*/
void set(float x, float y);
}

View File

@ -0,0 +1,17 @@
package utils.vectors;
public interface WriteableVector3f extends WriteableVector2f {
/**
* Set the Z value
* @param z
*/
void setZ(float z);
/**
* Set the X,Y,Z values
* @param x
* @param y
* @param z
*/
void set(float x, float y, float z);
}

View File

@ -0,0 +1,20 @@
package utils.vectors;
public interface WriteableVector4f extends WriteableVector3f {
/**
* Set the W value
* @param w
*/
void setW(float w);
/**
* Set the X,Y,Z,W values
* @param x
* @param y
* @param z
* @param w
*/
void set(float x, float y, float z, float w);
}