1
0
Fork 0

First commit

This commit is contained in:
Florian 2015-12-23 18:38:34 +01:00
commit 58c64ab472
62 changed files with 29291 additions and 0 deletions

12
src/mrdev023/Main.java Normal file
View file

@ -0,0 +1,12 @@
package mrdev023;
import mrdev023.gameengine.*;
import mrdev023.math.*;
public class Main {
public static void main(String[] args) {
GameEngine.start("Test", 800, 800);
}
}

9
src/mrdev023/Test.java Normal file
View file

@ -0,0 +1,9 @@
package mrdev023;
public class Test {
public static void main(String[] args) {
}
}

View file

@ -0,0 +1,273 @@
package mrdev023.audio;
import static org.lwjgl.openal.AL10.*;
import static org.lwjgl.openal.ALC10.*;
import static org.lwjgl.openal.ALC11.*;
import static org.lwjgl.openal.ALUtil.*;
import static org.lwjgl.stb.STBVorbis.*;
import static org.lwjgl.system.MemoryUtil.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import org.lwjgl.*;
import static org.lwjgl.BufferUtils.*;
import org.lwjgl.openal.ALCCapabilities;
import org.lwjgl.openal.ALContext;
import org.lwjgl.openal.ALDevice;
import org.lwjgl.stb.STBVorbisInfo;
public class Audio {
//Variables global
//------------------------------------------------------
public static ALDevice device;
public static ALCCapabilities caps;
public static ALContext context;
public static final int INITIAL_STATE = 4113,PAUSED_STATE = 4115,STOPPED_STATE = 4116,PLAYING_STATE = 4114;
//------------------------------------------------------
//Variable de l'objet audio ou du son a lire
//------------------------------------------------------
private int buffer,source;
private String fileName;
//------------------------------------------------------
//Fonction global
//------------------------------------------------------
public static void create(){
device = ALDevice.create(null);
if ( device == null )
throw new IllegalStateException("Failed to open the default device.");
caps = device.getCapabilities();
System.out.println("OpenALC10: " + caps.OpenALC10);
System.out.println("OpenALC11: " + caps.OpenALC11);
System.out.println("caps.ALC_EXT_EFX = " + caps.ALC_EXT_EFX);
String defaultDeviceSpecifier = alcGetString(0L, ALC_DEFAULT_DEVICE_SPECIFIER);
System.out.println("Default device: " + defaultDeviceSpecifier);
context = ALContext.create(device);
System.out.println("ALC_FREQUENCY: " + alcGetInteger(device.address(), ALC_FREQUENCY) + "Hz");
System.out.println("ALC_REFRESH: " + alcGetInteger(device.address(), ALC_REFRESH) + "Hz");
System.out.println("ALC_SYNC: " + (alcGetInteger(device.address(), ALC_SYNC) == ALC_TRUE));
System.out.println("ALC_MONO_SOURCES: " + alcGetInteger(device.address(), ALC_MONO_SOURCES));
System.out.println("ALC_STEREO_SOURCES: " + alcGetInteger(device.address(), ALC_STEREO_SOURCES));
}
public static void destroy(){
context.destroy();
device.destroy();
}
//------------------------------------------------------
//Fonction de l'objet audio ou du son a lire
//------------------------------------------------------
public Audio(String fileName) throws Exception{
this.fileName = fileName;
setSound();
}
private void setSound() throws Exception{
if(fileName.endsWith(".ogg")){
loadOGGFormat();
}else{
throw new Exception("Format not supported !");
}
alSourcei(source, AL_BUFFER, buffer);
checkALError();
}
public void loadOGGFormat(){
STBVorbisInfo info = STBVorbisInfo.malloc();
ByteBuffer buff = BufferUtils.createByteBuffer(0);
//lecture du fichier
//----------------------------------------------------------------------------------------------------------------
try {
File file = new File(fileName);
if ( file.isFile() ) {
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
buff = BufferUtils.createByteBuffer((int)fc.size() + 1);
while ( fc.read(buff) != -1 ) ;
fis.close();
fc.close();
} else {
System.err.println("File not found !");
return;
}
buff.flip();
} catch (IOException e) {
throw new RuntimeException(e);
}
//----------------------------------------------------------------------------------------------------------------
IntBuffer error = BufferUtils.createIntBuffer(1);
long decoder = stb_vorbis_open_memory(buff, error, null);
if ( decoder == NULL )
throw new RuntimeException("Failed to open Ogg Vorbis file. Error: " + error.get(0));
stb_vorbis_get_info(decoder, info);
int channels = info.channels();
stb_vorbis_seek_start(decoder);
int lengthSamples = stb_vorbis_stream_length_in_samples(decoder);
ByteBuffer pcm = BufferUtils.createByteBuffer(lengthSamples * channels);
stb_vorbis_get_samples_short_interleaved(decoder, channels, pcm, lengthSamples);
float duration = stb_vorbis_stream_length_in_seconds(decoder);
stb_vorbis_close(decoder);
buffer = alGenBuffers();
checkALError();
source = alGenSources();
checkALError();
if(channels == 1)alBufferData(buffer, AL_FORMAT_MONO16, pcm, info.sample_rate());
else alBufferData(buffer, AL_FORMAT_STEREO16, pcm, info.sample_rate());
checkALError();
}
public void playSound(){
if(source == 0 || buffer == 0) return;
alSourcePlay(source);
}
public int getPosition(){
return alGetSourcei(source, AL_POSITION);
}
public int getDurationInSeconds(){
if(source == 0 || buffer == 0) return 0;
int size = alGetBufferi(buffer,AL_SIZE);
int bits = alGetBufferi(buffer, AL_BITS);
int channels = alGetBufferi(buffer, AL_CHANNELS);
int freq = alGetBufferi(buffer, AL_FREQUENCY);
System.out.println("SIZE : " + size + " | BITS : " + bits + " | CHANNELS : " + channels + " | FREQUENCE : " + freq);
return size/channels/(bits/8)/freq;
}
public int getStateSound(){
if(source == 0 || buffer == 0) return 0;
return alGetSourcei(source, AL_SOURCE_STATE);
}
public boolean isStopped(){
if(source == 0 || buffer == 0) return false;
if(alGetSourcei(source, AL_SOURCE_STATE) == STOPPED_STATE)return true;
else return false;
}
public boolean isPaused(){
if(source == 0 || buffer == 0) return false;
if(alGetSourcei(source, AL_SOURCE_STATE) == PAUSED_STATE)return true;
else return false;
}
public boolean isPlaying(){
if(source == 0 || buffer == 0) return false;
if(alGetSourcei(source, AL_SOURCE_STATE) == PLAYING_STATE)return true;
else return false;
}
public boolean isInitial(){
if(source == 0 || buffer == 0) return false;
if(alGetSourcei(source, AL_SOURCE_STATE) == INITIAL_STATE)return true;
else return false;
}
public void stopSound(){
if(source == 0 || buffer == 0) return;
alSourceStop(source);
}
public void pauseSound(){
if(source == 0 || buffer == 0) return;
alSourcePause(source);
}
public void rewindSound(){
if(source == 0 || buffer == 0) return;
alSourceRewind(source);
}
public void setGain(float gain){
if(source == 0 || buffer == 0) return;
if(gain > 1.0f)gain = 1.0f;
if(gain < 0.0f)gain = 0.0f;
alSourcef(source, AL_GAIN, gain);
}
public void setPitch(float pitch){
if(source == 0 || buffer == 0) return;
if(pitch < 0.0f)pitch = 0.0f;
alSourcef(source, AL_PITCH, pitch);
}
public float getGain(){
if(source == 0 || buffer == 0) return 0;
return alGetSourcef(source, AL_GAIN);
}
public float getPitch(){
if(source == 0 || buffer == 0) return 0;
return alGetSourcef(source, AL_PITCH);
}
public void setLooping(boolean looping){
if(source == 0 || buffer == 0) return;
if(looping){
alSourcef(source, AL_LOOPING, AL_TRUE);
}else{
alSourcef(source, AL_LOOPING, AL_FALSE);
}
}
public void destroySound(){
alDeleteSources(source);
alDeleteBuffers(buffer);
source = 0;
buffer = 0;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) throws Exception {
this.fileName = fileName;
destroySound();
setSound();
}
public int getBuffer() {
return buffer;
}
public void setBuffer(int buffer) {
this.buffer = buffer;
}
public int getSource() {
return source;
}
public void setSource(int source) {
this.source = source;
}
//------------------------------------------------------
}

View file

@ -0,0 +1,202 @@
package mrdev023.audio;
import org.lwjgl.BufferUtils;
import org.lwjgl.openal.ALCCapabilities;
import org.lwjgl.openal.ALContext;
import org.lwjgl.openal.ALDevice;
import org.lwjgl.openal.ALUtil;
import org.lwjgl.stb.STBVorbisInfo;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.List;
import static org.lwjgl.openal.AL10.*;
import static org.lwjgl.openal.ALC10.*;
import static org.lwjgl.openal.ALC11.*;
import static org.lwjgl.openal.ALUtil.*;
import static org.lwjgl.stb.STBVorbis.*;
import static org.lwjgl.system.MemoryUtil.*;
import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import static org.lwjgl.BufferUtils.*;
public class AudioTest {
public static void main(String[] args) {
ALDevice device = ALDevice.create(null);
if ( device == null )
throw new IllegalStateException("Failed to open the default device.");
ALCCapabilities caps = device.getCapabilities();
System.out.println("OpenALC10: " + caps.OpenALC10);
System.out.println("OpenALC11: " + caps.OpenALC11);
System.out.println("caps.ALC_EXT_EFX = " + caps.ALC_EXT_EFX);
String defaultDeviceSpecifier = alcGetString(0L, ALC_DEFAULT_DEVICE_SPECIFIER);
System.out.println("Default device: " + defaultDeviceSpecifier);
ALContext context = ALContext.create(device);
System.out.println("ALC_FREQUENCY: " + alcGetInteger(device.address(), ALC_FREQUENCY) + "Hz");
System.out.println("ALC_REFRESH: " + alcGetInteger(device.address(), ALC_REFRESH) + "Hz");
System.out.println("ALC_SYNC: " + (alcGetInteger(device.address(), ALC_SYNC) == ALC_TRUE));
System.out.println("ALC_MONO_SOURCES: " + alcGetInteger(device.address(), ALC_MONO_SOURCES));
System.out.println("ALC_STEREO_SOURCES: " + alcGetInteger(device.address(), ALC_STEREO_SOURCES));
try {
testPlayback();
} finally {
context.destroy();
device.destroy();
}
}
private static void testPlayback() {
STBVorbisInfo info = STBVorbisInfo.malloc();
ByteBuffer pcm = readVorbis("res/audio/test.ogg", 32 * 1024, info);
// generate buffers and sources
int buffer = alGenBuffers();
checkALError();
int source = alGenSources();
checkALError();
//copy to buffer
alBufferData(buffer, AL_FORMAT_STEREO16, pcm, info.sample_rate());
checkALError();
info.free();
//set up source input
alSourcei(source, AL_BUFFER, buffer);
checkALError();
//lets loop the sound
alSourcei(source, AL_LOOPING, AL_TRUE);
checkALError();
//play source 0
alSourcePlay(source);
checkALError();
// //wait 5 secs
// try {
// System.out.println("Waiting 10 seconds for sound to complete");
// Thread.sleep(1);
// } catch (InterruptedException inte) {
// }
while(alGetSourcei(source, AL_SOURCE_STATE) != 4116);
//stop source 0
alSourceStop(source);
checkALError();
//delete buffers and sources
alDeleteSources(source);
checkALError();
alDeleteBuffers(buffer);
checkALError();
}
static ByteBuffer readVorbis(String resource, int bufferSize, STBVorbisInfo info) {
ByteBuffer vorbis;
try {
vorbis = ioResourceToByteBuffer(resource, bufferSize);
} catch (IOException e) {
throw new RuntimeException(e);
}
IntBuffer error = BufferUtils.createIntBuffer(1);
long decoder = stb_vorbis_open_memory(vorbis, error, null);
if ( decoder == NULL )
throw new RuntimeException("Failed to open Ogg Vorbis file. Error: " + error.get(0));
stb_vorbis_get_info(decoder, info);
int channels = info.channels();
int lengthSamples = stb_vorbis_stream_length_in_samples(decoder);
ByteBuffer pcm = BufferUtils.createByteBuffer(lengthSamples * 2);
stb_vorbis_get_samples_short_interleaved(decoder, channels, pcm, lengthSamples);
stb_vorbis_close(decoder);
return pcm;
}
private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) {
ByteBuffer newBuffer = BufferUtils.createByteBuffer(newCapacity);
buffer.flip();
newBuffer.put(buffer);
return newBuffer;
}
/**
* Reads the specified resource and returns the raw data as a ByteBuffer.
*
* @param resource the resource to read
* @param bufferSize the initial buffer size
*
* @return the resource data
*
* @throws IOException if an IO error occurs
*/
public static ByteBuffer ioResourceToByteBuffer(String resource, int bufferSize) throws IOException {
ByteBuffer buffer;
File file = new File(resource);
if ( file.isFile() ) {
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
buffer = BufferUtils.createByteBuffer((int)fc.size() + 1);
while ( fc.read(buffer) != -1 ) ;
fis.close();
fc.close();
} else {
buffer = createByteBuffer(bufferSize);
InputStream source = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
if ( source == null )
throw new FileNotFoundException(resource);
try {
ReadableByteChannel rbc = Channels.newChannel(source);
try {
while ( true ) {
int bytes = rbc.read(buffer);
if ( bytes == -1 )
break;
if ( buffer.remaining() == 0 )
buffer = resizeBuffer(buffer, buffer.capacity() * 2);
}
} finally {
rbc.close();
}
} finally {
source.close();
}
}
buffer.flip();
return buffer;
}
}

View file

@ -0,0 +1,23 @@
package mrdev023.entity;
import mrdev023.math.*;
public class Camera extends Player{
public Camera(float x,float y,float z){
super(x,y,z);
}
public Camera(){
super();
}
public void transform(){
transformMatrix.loadIdentity();
transformMatrix.rotate(new Quaternion(new Vector3f(1,0,0),rot.x));
transformMatrix.rotate(new Quaternion(new Vector3f(0,1,0),rot.y));
transformMatrix.rotate(new Quaternion(new Vector3f(0,0,1),rot.z));
transformMatrix.tranlate(-pos.x, -pos.y, -pos.z);
}
}

View file

@ -0,0 +1,57 @@
package mrdev023.entity;
import mrdev023.math.*;
import mrdev023.rendering.*;
public class Entity {
Matrix4f transformMatrix = new Matrix4f();
public Vector3f pos = new Vector3f();
public Vector3f rot = new Vector3f();
public Entity(){
pos = new Vector3f();
}
public Entity(float x,float y,float z){
pos = new Vector3f(x,y,z);
}
public void transform(){
transformMatrix.loadIdentity();
transformMatrix.tranlate(pos.x, pos.y, pos.z);
transformMatrix.rotate(new Quaternion(rot));
}
public Vector3f getPos() {
return pos;
}
public void setPos(Vector3f pos) {
this.pos = pos;
}
public Vector3f getRot() {
return rot;
}
public void setRot(Vector3f rot) {
this.rot = rot;
}
public Matrix4f getTransformMatrix() {
return transformMatrix;
}
public Quaternion getRotation(){
return new Quaternion(rot);
}
}

View file

@ -0,0 +1,13 @@
package mrdev023.entity;
public class Player extends Entity{
public Player(float x,float y,float z){
super(x,y,z);
}
public Player(){
super();
}
}

View file

@ -0,0 +1,12 @@
package mrdev023.exception;
public class DisplayException extends Exception{
public DisplayException(){
super();
}
public DisplayException(String error){
super(error);
}
}

View file

@ -0,0 +1,177 @@
package mrdev023.gameengine;
import java.util.concurrent.*;
import org.lwjgl.opengl.*;
import mrdev023.audio.Audio;
import mrdev023.entity.*;
import mrdev023.gamestate.*;
import mrdev023.gamestate.main.*;
import mrdev023.opengl.*;
import mrdev023.rendering.*;
import mrdev023.utils.*;
public class GameEngine {
public static String TITLE = "";
private static GameState state = GameState.MAIN_MENU;
private static boolean IsRunning = true;
private static int FPS = 0,TICKS = 0;
private static int FPS_LIMIT = 12000000;
private static Camera camera = new Camera();
private static Audio a;
public static void start(String title,int width,int height){
TITLE = title;
Display.create(title, width, height);
Display.createContext();
System.out.println("OpenGL " + GL11.glGetString(GL11.GL_VERSION));
init();
loop();
}
public static void init(){
Audio.create();
Shader.init();
Texture.init();
state.init();
Timer.init();
Input.init();
DisplayManager.init();
Timer.addTimer("info");
Timer.addTimer("ticks");
Timer.addTimer("fps");
Display.setMouseGrabbed(true);
try {
a = new Audio("res/audio/test.ogg");
System.err.println(a.getDurationInSeconds());
a.playSound();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void loop(){
while(IsRunning){
if(Display.isCloseRequested())IsRunning = false;
if(Display.wasResized())GL11.glViewport(0, 0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight());
update();
if(Timer.getNanoTime("ticks") >= 1000000000/60){
Timer.deltaUpdate();
Display.updateEvent();
Input.update();
state.updateKeyboard();
state.updateMouse();
state.update();
TICKS++;
Timer.setValue("ticks", Timer.getNanoTime("ticks") - 1000000000/60);
}else if(Timer.getNanoTime("fps") >= 1000000000/FPS_LIMIT){
DisplayManager.clearScreen();
DisplayManager.preRender3D();
DisplayManager.render3D();
DisplayManager.preRender2D();
DisplayManager.render2D();
DisplayManager.preRenderGUI();
DisplayManager.renderGUI();
FPS++;
Display.updateFrame();
Timer.setValue("fps", Timer.getNanoTime("fps") - 1000000000/FPS_LIMIT);
}
if(Timer.getMillisTime("info") >= 1000){
Display.setTitle(TITLE + " | Fps:" + FPS + " Ticks:" + TICKS + " | " + camera.getPos() + " " + camera.getRot());
System.out.println(a.getPosition());
FPS = 0;
TICKS = 0;
Timer.setValue("info", Timer.getNanoTime("info") - 1000000000);
}
}
destroy();
}
public static void update(){
Timer.udpate();
}
public static void destroy(){
state.destroy();
Input.destroy();
Audio.destroy();
Display.destroy();
}
public static void changeGameState(GameState gameState){
state.destroy();
state = gameState;
state.init();
}
public static GameState getGameState(){
return state;
}
public static String getTITLE() {
return TITLE;
}
public static void setTITLE(String tITLE) {
TITLE = tITLE;
}
public static GameState getState() {
return state;
}
public static void setState(GameState state) {
GameEngine.state = state;
}
public static boolean isIsRunning() {
return IsRunning;
}
public static void setIsRunning(boolean isRunning) {
IsRunning = isRunning;
}
public static int getFPS() {
return FPS;
}
public static void setFPS(int fPS) {
FPS = fPS;
}
public static int getTICKS() {
return TICKS;
}
public static void setTICKS(int tICKS) {
TICKS = tICKS;
}
public static int getFPS_LIMIT() {
return FPS_LIMIT;
}
public static void setFPS_LIMIT(int fPS_LIMIT) {
FPS_LIMIT = fPS_LIMIT;
}
public static Camera getCamera() {
return camera;
}
public static void setCamera(Camera camera) {
GameEngine.camera = camera;
}
}

View file

@ -0,0 +1,7 @@
package mrdev023.gameengine;
public class Settings {
public static float sens = 0.5f;
}

View file

@ -0,0 +1,100 @@
package mrdev023.gamestate;
import java.util.ArrayList;
import org.lwjgl.glfw.*;
import mrdev023.entity.*;
import mrdev023.gameengine.*;
import mrdev023.gamestate.main.*;
import mrdev023.math.*;
import mrdev023.model.*;
import mrdev023.opengl.*;
import mrdev023.rendering.*;
import mrdev023.rendering.lights.*;
import mrdev023.utils.*;
public class MainMenu extends Game implements IGameState{
public VAO vao,cube;
public int time = 0;
public static final float speed = 1.0f;
public ArrayList<Light> lights;
public void update() {
time+=Timer.getDeltaTime();
}
public void updateKeyboard() {
if(Input.isKeyDown(GLFW.GLFW_KEY_ESCAPE))GameEngine.setIsRunning(false);
Camera camera = GameEngine.getCamera();
Vector3f pos = camera.getPos();
Vector3f rot = camera.getRot();
rot.x += -Input.getDMouse().getY() * Settings.sens;
rot.y += -Input.getDMouse().getX() * Settings.sens;
if(rot.x > 90)rot.x = 90;
if(rot.x < -90)rot.x = -90;
if(Input.isKey(GLFW.GLFW_KEY_W)){
pos.x += Mathf.cos(Mathf.toRadians(rot.y + 90)) * speed;
pos.z += Mathf.sin(Mathf.toRadians(rot.y + 90)) * speed;
}
if(Input.isKey(GLFW.GLFW_KEY_S)){
pos.x += -Mathf.cos(Mathf.toRadians(rot.y + 90)) * speed;
pos.z += -Mathf.sin(Mathf.toRadians(rot.y + 90)) * speed;
}
if(Input.isKey(GLFW.GLFW_KEY_A)){
pos.x += -Mathf.cos(Mathf.toRadians(rot.y)) * speed;
pos.z += -Mathf.sin(Mathf.toRadians(rot.y)) * speed;
}
if(Input.isKey(GLFW.GLFW_KEY_D)){
pos.x += Mathf.cos(Mathf.toRadians(rot.y)) * speed;
pos.z += Mathf.sin(Mathf.toRadians(rot.y)) * speed;
}
if(Input.isKey(GLFW.GLFW_KEY_LEFT_SHIFT)){
pos.y -= speed;
}
if(Input.isKey(GLFW.GLFW_KEY_SPACE)){
pos.y += speed;
}
}
public void updateMouse() {
if(Input.isButtonDown(0))Display.setMouseGrabbed(true);
if(Input.isButtonDown(1))Display.setMouseGrabbed(false);
}
public void init() {
lights = new ArrayList<Light>();
lights.add(new AmbientLight(new Vector3f(100,100,100),Color4f.WHITE,Color4f.mul(Color4f.WHITE,1.0f)));
vao = MeshBuilder.createFloor(400, Color4f.WHITE,Texture.FLOOR);
cube = MeshBuilder.createCube(100, Color4f.WHITE,Texture.WOOD);
}
public void render2D() {
}
public void render3D() {
for(Light light : lights){
light.drawLight();
Matrix4f mvp = new Matrix4f();
mvp.loadIdentity();
Shader.MAIN.uniform("transform", mvp);
vao.render3D();
mvp.tranlate(0, 200, 0);
Shader.MAIN.uniform("transform", mvp);
cube.render3D();
}
}
public void renderGUI() {
}
public void destroy() {
vao.destroy();
cube.destroy();
}
}

View file

@ -0,0 +1,5 @@
package mrdev023.gamestate.main;
public abstract class Game {
}

View file

@ -0,0 +1,48 @@
package mrdev023.gamestate.main;
import mrdev023.gamestate.*;
public enum GameState {
MAIN_MENU(new MainMenu());
private IGameState state;
GameState(IGameState state){
this.state = state;
}
public void update(){
state.update();
}
public void updateKeyboard(){
state.updateKeyboard();
}
public void updateMouse(){
state.updateMouse();
}
public void init(){
state.init();
}
public void render2D(){
state.render2D();
}
public void render3D(){
state.render3D();
}
public void renderGUI(){
state.renderGUI();
}
public void destroy(){
state.destroy();
}
}

View file

@ -0,0 +1,14 @@
package mrdev023.gamestate.main;
public interface IGameState {
public void update();
public void updateKeyboard();
public void updateMouse();
public void init();
public void render2D();
public void render3D();
public void renderGUI();
public void destroy();
}

View file

@ -0,0 +1,69 @@
package mrdev023.math;
public class Color4f {
public static final Color4f
RED = new Color4f(1,0,0,1),
BLUE = new Color4f(0,0,1,1),
GREEN = new Color4f(0,1,0,1),
YELLOW = new Color4f(1,1,0,1),
PURPLE = new Color4f(1,0,1,1),
CYAN = new Color4f(0,1,1,1),
BLACK = new Color4f(0,0,0,1),
WHITE = new Color4f(1,1,1,1);
public float r,g,b,a;
public Color4f(float r,float g,float b,float a){
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
public static Color4f mul (Color4f a, float b){
return new Color4f(a.r * b,a.g * b,a.b * b,a.a * b);
}
public static Color4f mul (Color4f a, Color4f b){
return new Color4f((a.r + b.r)/2.0f,(a.g + b.g)/2.0f,(a.b + b.b)/2.0f,(a.a + b.a)/2.0f);
}
public Color4f() {
}
public float getR() {
return r;
}
public void setR(float r) {
this.r = r;
}
public float getG() {
return g;
}
public void setG(float g) {
this.g = g;
}
public float getB() {
return b;
}
public void setB(float b) {
this.b = b;
}
public float getA() {
return a;
}
public void setA(float a) {
this.a = a;
}
}

View file

@ -0,0 +1,58 @@
package mrdev023.math;
public class Mathf {
public static final float PI = (float)Math.PI;
public static final float EPSILON = 1.401298e-45f;
public static float cos(float angle){
return (float)Math.cos(angle);
}
public static float acos(float angle){
return (float)Math.acos(angle);
}
public static float sin(float angle){
return (float)Math.sin(angle);
}
public static float asin(float angle){
return (float)Math.asin(angle);
}
public static float toRadians(float angle){
return (float)Math.toRadians(angle);
}
public static float toDegrees(float angle){
return (float)Math.toDegrees(angle);
}
public static float atan2(float a,float b){
return (float)Math.atan2(a,b);
}
public static float cut(float nbre,float a){
return (float)((int)(nbre*Math.pow(10, a))/Math.pow(10, a));
}
public static boolean equals(float a,float b,float tolerance){
return (a + tolerance >= b) && (a - tolerance <= b);
}
public static float sqrt(float a){
return (float)Math.sqrt(a);
}
public static float clamp(float value, float min, float max) {
if(value < min){
value = min;
}
if(value > max){
value = max;
}
return value;
}
}

View file

@ -0,0 +1,184 @@
package mrdev023.math;
import java.nio.*;
import java.util.*;
import org.lwjgl.*;
public class Matrix4f {
public float[][] m = null;
public Matrix4f(){
m = new float[][]{
{1,0,0,0},
{0,1,0,0},
{0,0,1,0},
{0,0,0,1}
};
}
public Matrix4f(float[][] m){
this.m = m;
}
public void loadIdentity(){
m = new float[][]{
{1,0,0,0},
{0,1,0,0},
{0,0,1,0},
{0,0,0,1}
};
}
public void rotate(Quaternion q){
Matrix4f rot = q.toMatrixRotation();
m = mul(rot).getM();
}
public void rotate(float x,float y,float z){
x = Mathf.toRadians(x);
y = Mathf.toRadians(y);
z = Mathf.toRadians(z);
Matrix4f rx = new Matrix4f(new float[][]{
{1,0,0,0},
{0,Mathf.cos(x),-Mathf.sin(x),0},
{0,Mathf.sin(x),Mathf.cos(x),0},
{0,0,0,1}
});
Matrix4f ry = new Matrix4f(new float[][]{
{Mathf.cos(y),0,Mathf.sin(y),0},
{0,1,0,0},
{-Mathf.sin(y),0,Mathf.cos(y),0},
{0,0,0,1}
});
Matrix4f rz = new Matrix4f(new float[][]{
{Mathf.cos(z),-Mathf.sin(z),0,0},
{Mathf.sin(z),Mathf.cos(z),0,0},
{0,0,1,0},
{0,0,0,1}
});
Matrix4f m1 = (rz.mul(ry.mul(rx)));
m = mul(m1).getM();
}
public static Matrix4f rotate(Vector3f forward, Vector3f up, Vector3f right)
{
Matrix4f mat = new Matrix4f(new float[][]{
{right.getX(), right.getY(), right.getZ() ,0},
{up.getX(), up.getY(), up.getZ() ,0},
{forward.getX(),forward.getY(), forward.getZ() ,0},
{0,0,0,1}
});
return mat;
}
public void tranlate(float x,float y,float z){
Matrix4f mat = new Matrix4f(new float[][]{
{1,0,0,x},
{0,1,0,y},
{0,0,1,z},
{0,0,0,1}
});
m = mul(mat).getM();
}
public void scale(float x,float y,float z){
Matrix4f mat = new Matrix4f(new float[][]{
{x,0,0,0},
{0,y,0,0},
{0,0,z,0},
{0,0,0,1}
});
m = mul(mat).getM();
}
public Matrix4f mul(Matrix4f mat){
Matrix4f ma = new Matrix4f();
for(int i = 0;i < 4;i++){
for(int j = 0;j < 4;j++){
ma.m[i][j] = m[i][0] * mat.m[0][j] +
m[i][1] * mat.m[1][j] +
m[i][2] * mat.m[2][j] +
m[i][3] * mat.m[3][j];
}
}
return ma;
}
public Matrix4f Ortho2D(float left, float right, float bottom, float top, float near, float far)
{
float width = right - left;
float height = top - bottom;
float depth = far - near;
m = new float[][]{
{2/width,0,0,-(right + left)/width},
{0,2/height,0,-(top + bottom)/height},
{0,0,-2/depth,-(far + near)/depth},
{0,0,0,1}
};
return this;
}
public Matrix4f perspective(float fov, float aspectRatio, float zNear, float zFar)
{
float f = fov;
fov = Mathf.toRadians(f);
float tanHalfFOV = (float)Math.tan(fov / 2);
float zRange = zNear - zFar;
m = new float[][]{
{1.0f / (tanHalfFOV * aspectRatio),0,0,0},
{0,1.0f / tanHalfFOV,0,0},
{0,0,(-zNear -zFar)/zRange,2.0f * zFar * zNear / zRange},
{0,0,1,0}
};
return this;
}
public FloatBuffer getBuffer(){
FloatBuffer buffer = BufferUtils.createFloatBuffer(4 * 4);
for(int i = 0;i < 4;i++){
buffer.put(m[i]);
}
buffer.flip();
return buffer;
}
public String toString(){
int size = 3;
int max = 10;
StringJoiner st = new StringJoiner("\n","--------Mat4-Begin--------\n","\n--------Mat4-End----------");
for(int i = 0;i < 4;i++){
StringJoiner st2 = new StringJoiner(" | ");
for(int j = 0;j < 4;j++){
String value = Mathf.cut(m[i][j], size) + "";
for(int k = value.length();k < max;k++){
value += " ";
}
st2.add(value);
}
st.add(st2.toString());
}
return st.toString();
}
public float[][] getM() {
return m;
}
public void setM(float[][] m) {
this.m = m;
}
public Matrix4f copy(){
return new Matrix4f(this.getM());
}
}

View file

@ -0,0 +1,131 @@
package mrdev023.math;
public class Quaternion {
public float x,y,z,w;
public Quaternion(){
x = 0;
y = 0;
z = 0;
w = 0;
}
public Quaternion(Vector3f axis,float angle){
float sin = Mathf.sin(Mathf.toRadians(angle/2.0f));
float cos = Mathf.cos(Mathf.toRadians(angle/2.0f));
x = axis.getX() * sin;
y = axis.getY() * sin;
z = axis.getZ() * sin;
w = cos;
}
public Quaternion(Vector3f rot){
this(rot.x,rot.y,rot.z);
}
public Quaternion (float yaw, float roll, float pitch) {
yaw = Mathf.toRadians(yaw);
roll = Mathf.toRadians(roll);
pitch = Mathf.toRadians(pitch);
float angle;
float sinRoll, sinPitch, sinYaw, cosRoll, cosPitch, cosYaw;
angle = pitch * 0.5f;
sinPitch = Mathf.sin(angle);
cosPitch = Mathf.cos(angle);
angle = roll * 0.5f;
sinRoll = Mathf.sin(angle);
cosRoll = Mathf.cos(angle);
angle = yaw * 0.5f;
sinYaw = Mathf.sin(angle);
cosYaw = Mathf.cos(angle);
// variables used to reduce multiplication calls.
float cosRollXcosPitch = cosRoll * cosPitch;
float sinRollXsinPitch = sinRoll * sinPitch;
float cosRollXsinPitch = cosRoll * sinPitch;
float sinRollXcosPitch = sinRoll * cosPitch;
w = (cosRollXcosPitch * cosYaw - sinRollXsinPitch * sinYaw);
x = (cosRollXcosPitch * sinYaw + sinRollXsinPitch * cosYaw);
y = (sinRollXcosPitch * cosYaw + cosRollXsinPitch * sinYaw);
z = (cosRollXsinPitch * cosYaw - sinRollXcosPitch * sinYaw);
normalize();
}
public void normalize(){
float n = (float)(1.0/Math.sqrt(norm()));
x *= n;
y *= n;
z *= n;
w *= n;
}
public float norm(){
return w * w + x * x + y * y + z * z;
}
public Quaternion Euler(Vector3f rot) {
x = Mathf.toRadians(rot.x);
y = Mathf.toRadians(rot.y);
z = Mathf.toRadians(rot.z);
float c1 = Mathf.cos(y/2);
float s1 = Mathf.sin(y/2);
float c2 = Mathf.cos(z/2);
float s2 = Mathf.sin(z/2);
float c3 = Mathf.cos(x/2);
float s3 = Mathf.sin(x/2);
float c1c2 = c1*c2;
float s1s2 = s1*s2;
this.w =c1c2*c3 - s1s2*s3;
this.x =c1c2*s3 + s1s2*c3;
this.y =s1*c2*c3 + c1*s2*s3;
this.z =c1*s2*c3 - s1*c2*s3;
return new Quaternion(x, y, z, w);
}
public Vector3f toEulerAngles(){
Vector3f euler = new Vector3f();
float sqw = w * w;
float sqx = x * x;
float sqy = y * y;
float sqz = z * z;
float unit = sqx + sqy + sqz + sqw; // if normalized is one, otherwise
// is correction factor
float test = x * y + z * w;
if (test > 0.499 * unit) { // singularity at north pole
euler.y = 2 * Mathf.atan2(x, w);
euler.z = Mathf.PI/2.0f;
euler.x = 0;
} else if (test < -0.499 * unit) { // singularity at south pole
euler.y = -2 * Mathf.atan2(x, w);
euler.z = -Mathf.PI/2.0f;
euler.x = 0;
} else {
euler.y = Mathf.atan2(2 * y * w - 2 * x * z, sqx - sqy - sqz + sqw); // roll or heading
euler.z = Mathf.asin(2 * test / unit); // pitch or attitude
euler.x = Mathf.atan2(2 * x * w - 2 * y * z, -sqx + sqy - sqz + sqw); // yaw or bank
}
return euler.toDegrees();
}
public Quaternion(float axisX,float axisY,float axisZ,float angle){
float sin = Mathf.sin(Mathf.toRadians(angle/2.0f));
float cos = Mathf.cos(Mathf.toRadians(angle/2.0f));
x = axisX * sin;
y = axisY * sin;
z = axisZ * sin;
w = cos;
}
public Matrix4f toMatrixRotation(){
Vector3f forward = new Vector3f(2.0f * (x * z - w * y), 2.0f * (y * z + w * x), 1.0f - 2.0f * (x * x + y * y));
Vector3f up = new Vector3f(2.0f * (x * y + w * z), 1.0f - 2.0f * (x * x + z * z), 2.0f * (y * z - w * x));
Vector3f right = new Vector3f(1.0f - 2.0f * (y * y + z * z), 2.0f * (x * y - w * z), 2.0f * (x * z + w * y));
return Matrix4f.rotate(forward, up, right);
}
}

View file

@ -0,0 +1,41 @@
package mrdev023.math;
import java.util.*;
public class Vector2f {
public float x,y;
public Vector2f(){
x = 0;
y = 0;
}
public Vector2f(float x,float y){
this.x = x;
this.y = y;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public String toString(){
StringJoiner st = new StringJoiner(",","vec2(",")");
st.add("" + x);
st.add("" + y);
return st.toString();
}
}

View file

@ -0,0 +1,99 @@
package mrdev023.math;
import java.util.*;
public class Vector3f {
public float x,y,z;
public Vector3f(){
x = 0;
y = 0;
z = 0;
}
public Vector3f(float x,float y,float z){
this.x = x;
this.y = y;
this.z = z;
}
public Vector3f(Vector2f vec,float z){
this(vec.x,vec.y,z);
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public float getZ() {
return z;
}
public void setZ(float z) {
this.z = z;
}
public float length(){
return Mathf.sqrt(x * x + y * y + z * z);
}
public Vector3f lookAt(Vector3f d){
Vector3f rot = new Vector3f();
float x1 = d.x - x;
float y1 = d.y - y;
float z1 = d.z - z;
return rot;
}
public Vector3f normalize(){
float length = length();
x /= length;
y /= length;
z /= length;
return this;
}
public Vector3f mul(float m){
x *= m;
y *= m;
z *= m;
return this;
}
public String toString(){
StringJoiner st = new StringJoiner(",","vec3(",")");
st.add("" + x);
st.add("" + y);
st.add("" + z);
return st.toString();
}
public Vector3f toRadians() {
x = Mathf.toRadians(x);
y = Mathf.toRadians(y);
z = Mathf.toRadians(z);
return this;
}
public Vector3f toDegrees() {
x = Mathf.toDegrees(x);
y = Mathf.toDegrees(y);
z = Mathf.toDegrees(z);
return this;
}
}

View file

@ -0,0 +1,57 @@
package mrdev023.model;
import mrdev023.math.*;
import mrdev023.rendering.*;
public class MeshBuilder {
public static VAO createCube(float size,Color4f color,Texture texture){
float half_size = size/2.0f;
VAO vao = new VAO();
vao.addData(half_size,half_size,half_size, 0,1,0, color.getR(),color.getG(),color.getB(),color.getA(), 0,0,
half_size,half_size,-half_size, 0,1,0, color.getR(),color.getG(),color.getB(),color.getA(), 0,1,
-half_size,half_size,-half_size, 0,1,0, color.getR(),color.getG(),color.getB(),color.getA(), 1,1,//top
-half_size,half_size,half_size, 0,1,0, color.getR(),color.getG(),color.getB(),color.getA(), 1,0,
half_size,-half_size,half_size, 1,0,0, color.getR(),color.getG(),color.getB(),color.getA(), 0,0,
half_size,-half_size,-half_size, 1,0,0, color.getR(),color.getG(),color.getB(),color.getA(), 0,1,
half_size,half_size,-half_size, 1,0,0, color.getR(),color.getG(),color.getB(),color.getA(), 1,1,//right
half_size,half_size,half_size, 1,0,0, color.getR(),color.getG(),color.getB(),color.getA(), 1,0,
-half_size,-half_size,half_size, 0,-1,0, color.getR(),color.getG(),color.getB(),color.getA(), 0,0,
-half_size,-half_size,-half_size, 0,-1,0, color.getR(),color.getG(),color.getB(),color.getA(), 0,1,//bottom
half_size,-half_size,-half_size, 0,-1,0, color.getR(),color.getG(),color.getB(),color.getA(), 1,1,
half_size,-half_size,half_size, 0,-1,0, color.getR(),color.getG(),color.getB(),color.getA(), 1,0,
-half_size,half_size,half_size, -1,0,0, color.getR(),color.getG(),color.getB(),color.getA(), 0,0,
-half_size,half_size,-half_size, -1,0,0, color.getR(),color.getG(),color.getB(),color.getA(), 0,1,//left
-half_size,-half_size,-half_size, -1,0,0, color.getR(),color.getG(),color.getB(),color.getA(), 1,1,
-half_size,-half_size,half_size, -1,0,0, color.getR(),color.getG(),color.getB(),color.getA(), 1,0,
half_size,half_size,-half_size, 0,0,-1, color.getR(),color.getG(),color.getB(),color.getA(), 0,0,
half_size,-half_size,-half_size, 0,0,-1, color.getR(),color.getG(),color.getB(),color.getA(), 0,1,//back
-half_size,-half_size,-half_size, 0,0,-1, color.getR(),color.getG(),color.getB(),color.getA(), 1,1,
-half_size,half_size,-half_size, 0,0,-1, color.getR(),color.getG(),color.getB(),color.getA(), 1,0,
half_size,-half_size,half_size, 0,0,1, color.getR(),color.getG(),color.getB(),color.getA(), 0,0,
half_size,half_size,half_size, 0,0,1, color.getR(),color.getG(),color.getB(),color.getA(), 0,1,//front
-half_size,half_size,half_size, 0,0,1, color.getR(),color.getG(),color.getB(),color.getA(), 1,1,
-half_size,-half_size,half_size, 0,0,1, color.getR(),color.getG(),color.getB(),color.getA(), 1,0);
vao.bindBuffer();
vao.setTexture(texture.getID());
return vao;
}
public static VAO createFloor(float size,Color4f color,Texture texture){
float half_size = size/2.0f;
VAO vao = new VAO();
vao.addData(half_size,0,half_size, 0,1,0, color.getR(),color.getG(),color.getB(),color.getA(), 0,0,
half_size,0,-half_size, 0,1,0, color.getR(),color.getG(),color.getB(),color.getA(), 0,1,
-half_size,0,-half_size, 0,1,0, color.getR(),color.getG(),color.getB(),color.getA(), 1,1,//up
-half_size,0,half_size, 0,1,0, color.getR(),color.getG(),color.getB(),color.getA(), 1,0);
vao.bindBuffer();
vao.setTexture(texture.getID());
return vao;
}
}

View file

@ -0,0 +1,5 @@
package mrdev023.model;
public class OBJModel {
}

View file

@ -0,0 +1,143 @@
package mrdev023.opengl;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.*;
import java.awt.*;
import java.nio.*;
import org.lwjgl.*;
import org.lwjgl.opengl.*;
import mrdev023.exception.*;
public class Display {
private static DisplayMode displayMode;
private static String TITLE = "";
private static long window;
private static boolean hasResized = false;
public static void create(String title,int width,int height){
if ( glfwInit() != GL11.GL_TRUE )
throw new IllegalStateException("Unable to initialize GLFW");
TITLE = title;
displayMode = new DisplayMode(width,height);
window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL);
}
public static void create(String title,int width,int height,int major,int minor){
if ( glfwInit() != GL11.GL_TRUE )
throw new IllegalStateException("Unable to initialize GLFW");
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); // Nous voulons OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
TITLE = title;
displayMode = new DisplayMode(width,height);
window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL);
}
public static void setMouseGrabbed(boolean a){
if(a){
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}else{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
public static void setVSync(boolean a) throws DisplayException{
if(a)glfwSwapInterval(1);
else glfwSwapInterval(0);
}
public static void create(String title,int width,int height,int major,int minor,int sample){
if ( glfwInit() != GL11.GL_TRUE )
throw new IllegalStateException("Unable to initialize GLFW");
glfwWindowHint(GLFW_SAMPLES, sample); // antialiasing 4x
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major); // Nous voulons OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
TITLE = title;
displayMode = new DisplayMode(width,height);
window = glfwCreateWindow(displayMode.getWidth(),displayMode.getHeight(), TITLE, NULL, NULL);
}
public static void setSample(int sample){
glfwWindowHint(GLFW_SAMPLES, sample);
}
public static void setResizable(boolean a){
if(a)glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
else glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
}
public static void setTitle(String title){
TITLE = title;
glfwSetWindowTitle(window, TITLE);
}
public static String getTitle(){
return TITLE;
}
public static boolean wasResized(){
ByteBuffer w = BufferUtils.createByteBuffer(4);
ByteBuffer h = BufferUtils.createByteBuffer(4);
glfwGetWindowSize(window, w, h);
int width = w.getInt(0);
int height = h.getInt(0);
if(Display.getDisplayMode().getWidth() != width || Display.getDisplayMode().getHeight() != height || hasResized){
setDisplayMode(new DisplayMode(width, height));
hasResized = false;
return true;
}else{
return false;
}
}
public static boolean isCloseRequested(){
return glfwWindowShouldClose(window) == GL_TRUE;
}
public static void createContext(){
glfwMakeContextCurrent(window);
GL.createCapabilities();
}
public static void updateEvent(){
glfwPollEvents();
}
public static void updateFrame(){
glfwSwapBuffers(window);
}
public static DisplayMode getDisplayMode() {
return displayMode;
}
public static void setDisplayMode(DisplayMode displayMode) {
if(Display.displayMode == null || displayMode == null)return;
Display.displayMode.setDisplayMode(displayMode);
hasResized = true;
}
public static void destroy(){
glfwDestroyWindow(window);
glfwTerminate();
}
public static long getWindow() {
return window;
}
}

View file

@ -0,0 +1,58 @@
package mrdev023.opengl;
import static org.lwjgl.opengl.GL11.*;
import mrdev023.gameengine.*;
import mrdev023.math.*;
import mrdev023.rendering.*;
public class DisplayManager {
private static Matrix4f projection = new Matrix4f();
public static void init(){
}
public static void clearScreen(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
Shader.MAIN.bind();
}
public static void preRender2D(){
projection.loadIdentity();
projection.Ortho2D(0, Display.getDisplayMode().getWidth(), 0, Display.getDisplayMode().getHeight(), 1, -1);
Shader.MAIN.uniform("projection", projection);
}
public static void preRender3D(){
projection.loadIdentity();
projection.perspective(45f, (float)Display.getDisplayMode().getWidth()/(float)Display.getDisplayMode().getHeight(), 0.01f, 1000f);
Shader.MAIN.uniform("projection", projection);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
}
public static void preRenderGUI(){
projection.loadIdentity();
projection.Ortho2D(0, Display.getDisplayMode().getWidth(), 0, Display.getDisplayMode().getHeight(), 1, -1);
Shader.MAIN.uniform("projection", projection);
}
public static void render2D(){
GameEngine.getGameState().render2D();
}
public static void render3D(){
GameEngine.getCamera().transform();
Shader.MAIN.uniform("camera", GameEngine.getCamera().getTransformMatrix());
GameEngine.getGameState().render3D();
}
public static void renderGUI(){
GameEngine.getGameState().renderGUI();
}
}

View file

@ -0,0 +1,52 @@
package mrdev023.opengl;
import static org.lwjgl.glfw.GLFW.*;
public class DisplayMode {
private int width = 0,height = 0;
private boolean fullscreen = false;
public DisplayMode(int width,int height){
this.width = width;
this.height = height;
}
public void setDisplayMode(DisplayMode displayMode){
this.width = displayMode.getWidth();
this.height = displayMode.getHeight();
this.fullscreen = displayMode.isFullscreen();
setDisplayMode();
}
public void setDisplayMode(){
glfwSetWindowSize(Display.getWindow(), width,height);
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public boolean isFullscreen() {
return fullscreen;
}
public void setFullscreen(boolean fullscreen) {
this.fullscreen = fullscreen;
setDisplayMode();
}
}

View file

@ -0,0 +1,245 @@
package mrdev023.opengl;
import static org.lwjgl.glfw.GLFW.*;
import java.util.*;
import java.util.Map.*;
import org.lwjgl.glfw.*;
import mrdev023.math.*;
import mrdev023.opengl.*;
import mrdev023.rendering.*;
public class Input{
public static GLFWScrollCallback scroll;
public static GLFWCursorPosCallback mousePos;
private static Vector2f mousePosition = new Vector2f();
private static Vector2f dMouse = new Vector2f();
private static Vector2f previousDMouse = new Vector2f();
public static final int NONE = 0,PRESSED = 1,RELEASED = 2,REPEATED = 3,UP = 4,DOWN = 5,
NBRE_KEY = 0x15D,NBRE_BUTTON = 10,
MOUSE_OFFSET = NBRE_KEY + 1,MOUSE_WHEEL_OFFSET = MOUSE_OFFSET + 1;
private static HashMap<Integer,Integer> state = new HashMap<Integer,Integer>();
private static double ywheel = 0;
public static void init(){
glfwSetScrollCallback(Display.getWindow(), scroll = new GLFWScrollCallback() {
public void invoke(long window, double xoffset, double yoffset) {
scroll(window, xoffset, yoffset);
}
});
glfwSetCursorPosCallback(Display.getWindow(), mousePos = new GLFWCursorPosCallback() {
public void invoke(long window, double xpos, double ypos) {
mousepos(window, xpos, ypos);
}
});
for(int i = 0;i < NBRE_KEY;i++){
state.put(i, NONE);
}
for(int i = 0;i < NBRE_BUTTON;i++){
state.put(i + MOUSE_OFFSET, NONE);
}
state.put(MOUSE_WHEEL_OFFSET, NONE);
}
public static void update(){
for(Entry<Integer, Integer> set : state.entrySet()){
int i = set.getKey();
int st = set.getValue();
if(i > -1 && i < NBRE_KEY){
if(glfwGetKey(Display.getWindow(), i) == 0 && st == NONE)continue;
if(glfwGetKey(Display.getWindow(), i) == 1 && st == NONE){
state.replace(i, PRESSED);
}else if(glfwGetKey(Display.getWindow(), i) == 1 && st == PRESSED){
state.replace(i, REPEATED);
}else if(glfwGetKey(Display.getWindow(), i) == 0 && (st == PRESSED || st == REPEATED)){
state.replace(i, RELEASED);
}else if(glfwGetKey(Display.getWindow(), i) == 0 && st == RELEASED){
state.replace(i, NONE);
}
}else if(i >= MOUSE_OFFSET && i < MOUSE_OFFSET + NBRE_BUTTON){
if(glfwGetMouseButton(Display.getWindow(), i - MOUSE_OFFSET) == 0 && st == NONE)continue;
if(glfwGetMouseButton(Display.getWindow(), i - MOUSE_OFFSET) == 1 && st == NONE){
state.replace(i, PRESSED);
}else if(glfwGetMouseButton(Display.getWindow(), i - MOUSE_OFFSET) == 1 && st == PRESSED){
state.replace(i, REPEATED);
}else if(glfwGetMouseButton(Display.getWindow(), i - MOUSE_OFFSET) == 0 && (st == PRESSED || st == REPEATED)){
state.replace(i, RELEASED);
}else if(glfwGetMouseButton(Display.getWindow(), i - MOUSE_OFFSET) == 0 && st == RELEASED){
state.replace(i, NONE);
}
}
}
int st = state.get(MOUSE_WHEEL_OFFSET);
if(ywheel > 0 && (st == NONE || st == UP)){
state.replace(MOUSE_WHEEL_OFFSET, UP);
}else if(ywheel < 0 && (st == NONE || st == DOWN)){
state.replace(MOUSE_WHEEL_OFFSET, DOWN);
}else if(ywheel == 0 && (st == DOWN || st == UP)){
state.replace(MOUSE_WHEEL_OFFSET, NONE);
}
ywheel = 0;
if(dMouse.equals(previousDMouse)){
dMouse = new Vector2f();
}else{
previousDMouse = dMouse;
}
}
public static void destroy(){
mousePos.release();
scroll.release();
}
public static void scroll(long window, double xoffset, double yoffset) {
ywheel = yoffset;
}
public static void mousepos(long window, double xpos, double ypos) {
dMouse.x = (float) (xpos - mousePosition.x);
dMouse.y = (float) (ypos - mousePosition.y);
mousePosition.x = (float) xpos;
mousePosition.y = (float) ypos;
}
public static boolean isButtonDown(int button){
return state.get(button + MOUSE_OFFSET) == PRESSED;
}
public static boolean isButtonUp(int button){
return state.get(button + MOUSE_OFFSET) == RELEASED;
}
public static boolean isButton(int button){
return state.get(button + MOUSE_OFFSET) == PRESSED || state.get(button + MOUSE_OFFSET) == REPEATED;
}
public static int isButtonState(int button){
return state.get(button + MOUSE_OFFSET);
}
public static boolean isKeyDown(int key){
return state.get(key) == PRESSED;
}
public static boolean isKeyUp(int key){
return state.get(key) == RELEASED;
}
public static boolean isKey(int key){
return state.get(key) == PRESSED || state.get(key) == REPEATED;
}
public static int isKeyState(int key){
return state.get(key);
}
public static int isMouseWheelState(){
return state.get(MOUSE_WHEEL_OFFSET);
}
public static boolean isMouseWheelUp(){
return state.get(MOUSE_WHEEL_OFFSET) == UP;
}
public static boolean isMouseWheelDown(){
return state.get(MOUSE_WHEEL_OFFSET) == DOWN;
}
public static GLFWScrollCallback getScroll() {
return scroll;
}
public static void setScroll(GLFWScrollCallback scroll) {
Input.scroll = scroll;
}
public static GLFWCursorPosCallback getMousePos() {
return mousePos;
}
public static void setMousePos(GLFWCursorPosCallback mousePos) {
Input.mousePos = mousePos;
}
public static Vector2f getMousePosition() {
return mousePosition;
}
public static void setMousePosition(Vector2f mousePosition) {
Input.mousePosition = mousePosition;
}
public static Vector2f getDMouse() {
return dMouse;
}
public static void setDMouse(Vector2f dMouse) {
Input.dMouse = dMouse;
}
public static HashMap<Integer, Integer> getState() {
return state;
}
public static void setState(HashMap<Integer, Integer> state) {
Input.state = state;
}
public static double getYwheel() {
return ywheel;
}
public static void setYwheel(double ywheel) {
Input.ywheel = ywheel;
}
public static int getNone() {
return NONE;
}
public static int getPressed() {
return PRESSED;
}
public static int getReleased() {
return RELEASED;
}
public static int getRepeated() {
return REPEATED;
}
public static int getUp() {
return UP;
}
public static int getDown() {
return DOWN;
}
public static int getNbreKey() {
return NBRE_KEY;
}
public static int getNbreButton() {
return NBRE_BUTTON;
}
public static int getMouseOffset() {
return MOUSE_OFFSET;
}
public static int getMouseWheelOffset() {
return MOUSE_WHEEL_OFFSET;
}
}

View file

@ -0,0 +1,117 @@
package mrdev023.rendering;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL20.*;
import java.io.*;
import mrdev023.math.*;
import mrdev023.utils.*;
public class Shader {
public int program;
public int includeV = 0,includeF = 0;
public static Shader MAIN,LIGHT,LIGHT_AMBIENT;
public static void init() {
MAIN = new Shader("res/shaders/main");
LIGHT = new Shader("res/shaders/light");
LIGHT_AMBIENT = new Shader("res/shaders/light_ambient");
}
public Shader(String file){
String vertexShader = "";
try {
vertexShader = IO.loadFile(file + ".vert");
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
vertexShader = loadShader(vertexShader,0,file + ".vert");
String fragmentShader = "";
try {
fragmentShader = IO.loadFile(file + ".frag");
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
fragmentShader = loadShader(fragmentShader,1,file + ".vert");
program = glCreateProgram();
int vert = glCreateShader(GL_VERTEX_SHADER);
int frag = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vert, vertexShader);
glShaderSource(frag, fragmentShader);
glCompileShader(vert);
if (glGetShaderi(vert, GL_COMPILE_STATUS) == GL_FALSE) {
System.err.println(glGetShaderInfoLog(vert, 2048));
System.exit(1);
}
glCompileShader(frag);
if (glGetShaderi(frag, GL_COMPILE_STATUS) == GL_FALSE) {
System.err.println(glGetShaderInfoLog(frag, 2048));
System.exit(1);
}
glAttachShader(program, vert);
glAttachShader(program, frag);
glLinkProgram(program);
glValidateProgram(program);
System.out.println("Shader " + file + ".vert loaded with " + includeV + " include !");
System.out.println("Shader " + file + ".frag loaded with " + includeF + " include !");
}
public String loadShader(String shader,int a,String name){
String st = "";
BufferedReader reader = new BufferedReader(new StringReader(shader));
String buffer = "";
int line = 0;
try {
while ((buffer = reader.readLine()) != null) {
line++;
if(buffer.startsWith("#include")){
if(a == 0){
includeV++;
}else{
includeF++;
}
String path = buffer.substring(10, buffer.length() - 1);
String sh = IO.loadFile("res/shaders/" + path);
buffer += sh;
}else{
st += buffer + "\n";
}
}
reader.close();
} catch (IOException e) {
System.err.println("include file not found in " + name + " #" + line + " !");
System.exit(-1);
}
return st;
}
public void bind(){
glUseProgram(program);
}
public void unbind(){
glUseProgram(0);
}
public void uniform(String name,float v){
glUniform1f(glGetUniformLocation(program, name), v);
}
public void uniform(String name,Vector3f vec){
glUniform3f(glGetUniformLocation(program, name), vec.x,vec.y,vec.z);
}
public void uniform(String name,Matrix4f mat){
glUniformMatrix4fv(glGetUniformLocation(program, name),true, mat.getBuffer());
}
public void uniform(String name, Color4f v) {
glUniform4f(glGetUniformLocation(program, name), v.getR(),v.getG(),v.getB(),v.getA());
}
}

View file

@ -0,0 +1,96 @@
package mrdev023.rendering;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL12.*;
import java.awt.image.*;
import java.io.*;
import java.nio.*;
import javax.imageio.*;
import org.lwjgl.*;
public class Texture {
public static Texture FLOOR,WOOD;
int width, height;
int id;
public static void init() {
FLOOR = Texture.loadTexture("res/textures/floor.jpg");
WOOD = Texture.loadTexture("res/textures/wood.jpg");
}
public Texture(int width,int height,int id){
this.id = id;
this.width = width;
this.height = height;
}
public static Texture loadTexture(String path){
try {
BufferedImage image = ImageIO.read(new File(path));
int width = image.getWidth();
int height = image.getHeight();
int[] pixels = new int[width * height];
image.getRGB(0, 0, width, height, pixels, 0,width);
ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * 4);
for(int y = 0; y < width; y++){
for(int x = 0; x < height; x++){
int i = pixels[x + y * width];//0xAARRGGBB
buffer.put((byte) ((i >> 16) & 0xFF));//r
buffer.put((byte) ((i >> 8) & 0xFF));//g
buffer.put((byte) ((i) & 0xFF));//b
buffer.put((byte) ((i >> 24) & 0xFF));//a
}
}
buffer.flip();
int id = glGenTextures();
glBindTexture(GL_TEXTURE_2D, id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
glBindTexture(GL_TEXTURE_2D, 0);
System.out.println("Texture loaded ! " + width + "x" + height + " id:" + id);
return new Texture(width, height, id);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public int getID(){
return id;
}
public void bind(){
glBindTexture(GL_TEXTURE_2D, id);
}
public void unbind(){
glBindTexture(GL_TEXTURE_2D, 0);
}
}

View file

@ -0,0 +1,121 @@
package mrdev023.rendering;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL30.*;
import static org.lwjgl.opengl.GL11.*;
import java.nio.*;
import java.util.*;
import org.lwjgl.*;
public class VAO {
private int vbo,vao,size = 0,textureid = 0;
public static final int SIZE_OF_FLOAT = 4;
public ArrayList<Float> data = new ArrayList<Float>();
public VAO(){
vao = glGenVertexArrays();
vbo = glGenBuffers();
}
public void setTexture(int id){
this.textureid = id;
}
public void addData(float... d){
for(float f : d){
data.add(f);
}
}
public void addData(double... d){
for(double f : d){
data.add((float)f);
}
}
public void clearBuffer(){
data.clear();
}
public void bindBuffer(){
FloatBuffer buffer = BufferUtils.createFloatBuffer(data.size());
for(float f : data){
buffer.put(f);
}
buffer.flip();
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, buffer, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
size = data.size();
}
public void render2D(){
glBindTexture(GL_TEXTURE_2D, textureid);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glVertexAttribPointer(0, 2, GL_FLOAT, false, (2 + 3 + 4 + 2) * SIZE_OF_FLOAT, 0);
glVertexAttribPointer(3, 3, GL_FLOAT, false, (2 + 3 + 4 + 2) * SIZE_OF_FLOAT, 2 * SIZE_OF_FLOAT);
glVertexAttribPointer(1, 4, GL_FLOAT, false, (2 + 3 + 4 + 2) * SIZE_OF_FLOAT, (2 + 3) * SIZE_OF_FLOAT);
glVertexAttribPointer(2, 2, GL_FLOAT, false, (2 + 3 + 4 + 2) * SIZE_OF_FLOAT, (2 + 3 + 4) * SIZE_OF_FLOAT);
glDrawArrays(GL_QUADS, 0, size/(2 + 3 + 4 + 2));
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(3);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
}
public void render3D(){
glBindTexture(GL_TEXTURE_2D, textureid);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glEnableVertexAttribArray(3);
glVertexAttribPointer(0, 3, GL_FLOAT, false, (3 + 3 + 4 + 2) * SIZE_OF_FLOAT, 0);
glVertexAttribPointer(3, 3, GL_FLOAT, false, (3 + 3 + 4 + 2) * SIZE_OF_FLOAT, 3 * SIZE_OF_FLOAT);
glVertexAttribPointer(1, 4, GL_FLOAT, false, (3 + 3 + 4 + 2) * SIZE_OF_FLOAT, (3 + 3) * SIZE_OF_FLOAT);
glVertexAttribPointer(2, 2, GL_FLOAT, false, (3 + 3 + 4 + 2) * SIZE_OF_FLOAT, (3 + 3 + 4) * SIZE_OF_FLOAT);
glDrawArrays(GL_QUADS, 0, size/(3 + 3 + 4 + 2));
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
glDisableVertexAttribArray(3);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
}
public void destroy(){
glDeleteVertexArrays(vao);
glDeleteBuffers(vbo);
}
}

View file

@ -0,0 +1,19 @@
package mrdev023.rendering.lights;
import mrdev023.math.*;
import mrdev023.rendering.*;
public class AmbientLight extends Light{
public AmbientLight(Vector3f pos, Color4f color,Color4f ambientLight) {
super(pos, color,ambientLight);
}
public void drawLight() {
Shader.MAIN.uniform("light_position", lightPos);
Shader.MAIN.uniform("diffuse_light_color", lightColor);
Shader.MAIN.uniform("ambient_light", ambientLight);
}
}

View file

@ -0,0 +1,6 @@
package mrdev023.rendering.lights;
public class DirectionalLight {
}

View file

@ -0,0 +1,19 @@
package mrdev023.rendering.lights;
import mrdev023.math.*;
public abstract class Light {
public Vector3f lightPos = new Vector3f();
public Color4f lightColor = new Color4f();
public Color4f ambientLight = new Color4f();
public Light(Vector3f pos,Color4f color,Color4f ambientLight){
this.lightPos = pos;
this.lightColor = color;
this.ambientLight = ambientLight;
}
public abstract void drawLight();
}

View file

@ -0,0 +1,6 @@
package mrdev023.rendering.shadows;
public class ShadowMapping {
}

View file

@ -0,0 +1,16 @@
package mrdev023.utils;
import java.nio.*;
import org.lwjgl.*;
public class BufferTools {
public static FloatBuffer asFlippedFloatBuffer(float[] data){
FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length);
buffer.put(data);
buffer.flip();
return buffer;
}
}

View file

@ -0,0 +1,28 @@
package mrdev023.utils;
import java.io.*;
import mrdev023.utils.compile.*;
public class ClassCompiler {
public static Class compile(String path,String className,String packageName){
String f = "";
try {
f = IO.loadFile(path + className + ".java");
} catch (IOException e1) {
e1.printStackTrace();
System.exit(-1);
}
f = "package " + packageName + ";\n\n" + f;
System.out.println(f);
Class cl = null;
try {
cl = InMemoryJavaCompiler.compile(packageName + "." + className, f);
} catch (Exception e) {
e.printStackTrace();
}
return cl;
}
}

View file

@ -0,0 +1,24 @@
package mrdev023.utils;
import java.io.*;
public class IO {
public static String loadFile(String input) throws IOException {
String r = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
String buffer = "";
while ((buffer = reader.readLine()) != null) {
r += buffer + "\n";
}
reader.close();
return r;
}
public static void writeFile(String path,String output) throws Exception{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
writer.write(output);
writer.close();
}
}

View file

@ -0,0 +1,39 @@
package mrdev023.utils;
import java.io.*;
import java.util.*;
import mrdev023.math.*;
public class OBJLoader {
public static ArrayList<Vector3f> loadOBJ(String path){
ArrayList<Vector3f> vecList = new ArrayList<Vector3f>();
String file = "";
try {
file = IO.loadFile(path);
} catch (IOException e1) {
e1.printStackTrace();
System.exit(-1);
}
BufferedReader reader = new BufferedReader(new StringReader(file));
String buffer = "";
try {
while ((buffer = reader.readLine()) != null) {
if(buffer.contains("v ")){
String[] line = buffer.split(" ");
if(line.length == 4){
vecList.add(new Vector3f(Float.parseFloat(line[1]),Float.parseFloat(line[2]),Float.parseFloat(line[3])));
}
}
}
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(vecList.size());
return vecList;
}
}

View file

@ -0,0 +1,69 @@
package mrdev023.utils;
import java.lang.reflect.*;
import mrdev023.*;
import sun.misc.*;
public class Pointer{
private static Unsafe unsafe = null;
static{
try {
Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
unsafe = (sun.misc.Unsafe) field.get(null);
} catch (Exception e) {
throw new AssertionError(e);
}
}
private long address;
public Pointer(){
address = unsafe.allocateMemory(unsafe.addressSize());
}
public Pointer(long address){
this.address = address;
}
public Pointer(Object obj){
this.address = unsafe.allocateMemory(unsafe.addressSize());
setValue(obj);
}
public void setValue(Object value){
unsafe.putObject(0, address, value);
}
public Object getValue(){
return unsafe.getObject(0, address);
}
public void delete(){
unsafe.freeMemory(address);
}
public static Unsafe getUnsafe() {
return unsafe;
}
public static void setUnsafe(Unsafe unsafe) {
Pointer.unsafe = unsafe;
}
public String toString(){
return Long.toHexString(address).toUpperCase();
}
public long getAddress() {
return address;
}
public void setAddress(long address) {
this.address = address;
}
}

View file

@ -0,0 +1,53 @@
package mrdev023.utils;
import java.util.*;
import java.util.Map.*;
public class Timer {
public static HashMap<String,Long> timers = new HashMap<String,Long>();
private static long current,previous,currentDelta,previousDelta,delta;
public static void init(){
current = System.nanoTime();
previous = System.nanoTime();
currentDelta = System.currentTimeMillis();
}
public static void udpate(){
previous = current;
current = System.nanoTime();
for(Entry<String, Long> timer : timers.entrySet()){
timer.setValue(timer.getValue() + (current - previous));
}
}
public static void deltaUpdate(){
previousDelta = currentDelta;
currentDelta = System.currentTimeMillis();
delta = currentDelta - previousDelta;
}
public static void addTimer(String name){
timers.put(name, 0L);
}
public static Long getNanoTime(String name){
return timers.get(name);
}
public static Long getMillisTime(String name){
return timers.get(name)/1000000;
}
public static void setValue(String name,Long value){
timers.replace(name, value);
}
public static int getDeltaTime(){
return (int)delta;
}
}

View file

@ -0,0 +1,24 @@
package mrdev023.utils.compile;
import java.io.*;
import java.net.*;
import javax.tools.*;
import javax.tools.JavaFileObject.*;
public class CompiledCode extends SimpleJavaFileObject {
private ByteArrayOutputStream baos = new ByteArrayOutputStream();
public CompiledCode(String className) throws Exception {
super(new URI(className), Kind.CLASS);
}
@Override
public OutputStream openOutputStream() throws IOException {
return baos;
}
public byte[] getByteCode() {
return baos.toByteArray();
}
}

View file

@ -0,0 +1,28 @@
package mrdev023.utils.compile;
import java.util.*;
import mrdev023.*;
public class DynamicClassLoader extends ClassLoader {
private Map<String, CompiledCode> customCompiledCode = new HashMap<>();
public DynamicClassLoader(ClassLoader parent) {
super(parent);
}
public void setCode(CompiledCode cc) {
customCompiledCode.put(cc.getName(), cc);
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
CompiledCode cc = customCompiledCode.get(name);
if (cc == null) {
return super.findClass(name);
}
byte[] byteCode = cc.getByteCode();
return defineClass(name, byteCode, 0, byteCode.length);
}
}

View file

@ -0,0 +1,36 @@
package mrdev023.utils.compile;
import java.io.*;
import javax.tools.*;
import mrdev023.*;
public class ExtendedStandardJavaFileManager extends ForwardingJavaFileManager<JavaFileManager> {
private CompiledCode compiledCode;
private DynamicClassLoader cl;
/**
* Creates a new instance of ForwardingJavaFileManager.
*
* @param fileManager delegate to this file manager
* @param cl
*/
protected ExtendedStandardJavaFileManager(JavaFileManager fileManager, CompiledCode compiledCode, DynamicClassLoader cl) {
super(fileManager);
this.compiledCode = compiledCode;
this.cl = cl;
this.cl.setCode(compiledCode);
}
@Override
public JavaFileObject getJavaFileForOutput(JavaFileManager.Location location, String className, JavaFileObject.Kind kind, FileObject sibling) throws IOException {
return compiledCode;
}
@Override
public ClassLoader getClassLoader(JavaFileManager.Location location) {
return cl;
}
}

View file

@ -0,0 +1,27 @@
package mrdev023.utils.compile;
import java.util.*;
import javax.tools.*;
import mrdev023.*;
public class InMemoryJavaCompiler {
static JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
public static Class<?> compile(String className, String sourceCodeInText) throws Exception {
// System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.8.0_51\\bin");
SourceCode sourceCode = new SourceCode(className, sourceCodeInText);
CompiledCode compiledCode = new CompiledCode(className);
Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(sourceCode);
DynamicClassLoader cl = new DynamicClassLoader(ClassLoader.getSystemClassLoader());
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(javac.getStandardFileManager(diagnostics, null, null),compiledCode, cl);
JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, null, null, null, compilationUnits);
boolean result = task.call();
if(!result)System.out.println(diagnostics.getDiagnostics());
if(cl != null)
return cl.loadClass(className);
else return null;
}
}

View file

@ -0,0 +1,20 @@
package mrdev023.utils.compile;
import java.io.*;
import java.net.*;
import javax.tools.*;
import javax.tools.JavaFileObject.*;
public class SourceCode extends SimpleJavaFileObject {
private String contents = null;
public SourceCode(String className, String contents) throws Exception {
super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.contents = contents;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
return contents;
}
}