├── LICENSE ├── README.md ├── res ├── models │ ├── monkey3.obj │ └── plane3.obj ├── shaders │ ├── forward-ambient.fs │ ├── forward-ambient.vs │ ├── forward-ambient2.fs │ ├── forward-ambient2.vs │ ├── forward-directional.fs │ ├── forward-directional.vs │ ├── forward-point.fs │ ├── forward-point.vs │ ├── forward-spot.fs │ ├── forward-spot.vs │ ├── lighting.fsh │ ├── lighting.glh │ ├── lighting.vsh │ ├── lightingMain.fsh │ └── sampling.glh ├── test.dae └── textures │ ├── black.png │ ├── bricks.jpg │ ├── bricks2.jpg │ ├── bricks2_disp.jpg │ ├── bricks2_normal.jpg │ ├── bricks2_normal.png │ ├── bricks_disp.png │ ├── bricks_normal.jpg │ ├── defaultTexture.png │ ├── default_disp.png │ ├── default_normal.jpg │ ├── test.png │ └── white.png └── src └── com └── base ├── engine ├── components │ ├── BaseLight.java │ ├── Camera.java │ ├── DirectionalLight.java │ ├── FreeLook.java │ ├── FreeMove.java │ ├── GameComponent.java │ ├── MeshRenderer.java │ ├── PointLight.java │ └── SpotLight.java ├── core │ ├── CoreEngine.java │ ├── Game.java │ ├── GameObject.java │ ├── Input.java │ ├── Matrix4f.java │ ├── Quaternion.java │ ├── Time.java │ ├── Transform.java │ ├── Util.java │ ├── Vector2f.java │ └── Vector3f.java └── rendering │ ├── Attenuation.java │ ├── Material.java │ ├── Mesh.java │ ├── RenderingEngine.java │ ├── Shader.java │ ├── Shader_old.java │ ├── Texture.java │ ├── Vertex.java │ ├── Window.java │ ├── meshLoading │ ├── IndexedModel.java │ ├── OBJIndex.java │ └── OBJModel.java │ └── resourceManagement │ ├── MappedValues.java │ ├── MeshResource.java │ ├── ShaderResource.java │ └── TextureResource.java └── game ├── AnimatedComponent.java ├── AnimationUtil.java ├── Bone.java ├── LookAtComponent.java ├── Main.java └── TestGame.java /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 RagnarrIvarssen 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Assimp-Tutorial-LWJGL-3 2 | A Tutorial For How To Create Assimp Animations In LWJGL3 3 | -------------------------------------------------------------------------------- /res/models/plane3.obj: -------------------------------------------------------------------------------- 1 | # Blender v2.66 (sub 1) OBJ File: '' 2 | # www.blender.org 3 | mtllib plane3.mtl 4 | o Cube 5 | v 8.045116 -0.023363 -8.045115 6 | v 8.045116 -0.023363 8.045116 7 | v -8.045117 -0.023363 8.045115 8 | v -8.045114 -0.023363 -8.045119 9 | v 8.045120 0.023363 -8.045112 10 | v 8.045111 0.023363 8.045121 11 | v -8.045119 0.023363 8.045114 12 | v -8.045115 0.023363 -8.045116 13 | vt 0.000000 0.000000 14 | vt 1.000000 0.000000 15 | vt 1.000000 1.000000 16 | vt 0.000000 1.000000 17 | vn 0.000000 -1.000000 0.000000 18 | vn 0.000000 1.000000 0.000000 19 | vn 1.000000 0.000020 0.000000 20 | vn -0.000000 -0.000041 1.000000 21 | vn -1.000000 -0.000041 -0.000000 22 | vn 0.000000 0.000071 -1.000000 23 | usemtl Material 24 | s off 25 | f 1/1/1 2/2/1 3/3/1 4/4/1 26 | f 5/1/2 8/2/2 7/3/2 6/4/2 27 | f 1/1/3 5/2/3 6/3/3 2/4/3 28 | f 2/1/4 6/2/4 7/3/4 3/4/4 29 | f 3/1/5 7/2/5 8/3/5 4/4/5 30 | f 5/1/6 1/2/6 4/3/6 8/4/6 31 | -------------------------------------------------------------------------------- /res/shaders/forward-ambient.fs: -------------------------------------------------------------------------------- 1 | #version 120 2 | #include "sampling.glh" 3 | 4 | varying vec2 texCoord0; 5 | varying vec3 worldPos0; 6 | varying mat3 tbnMatrix; 7 | 8 | uniform vec3 R_ambient; 9 | uniform vec3 C_eyePos; 10 | uniform sampler2D diffuse; 11 | uniform sampler2D dispMap; 12 | 13 | uniform float dispMapScale; 14 | uniform float dispMapBias; 15 | 16 | void main() 17 | { 18 | vec3 directionToEye = normalize(C_eyePos - worldPos0); 19 | vec2 texCoords = CalcParallaxTexCoords(dispMap, tbnMatrix, directionToEye, texCoord0, dispMapScale, dispMapBias); 20 | gl_FragColor = texture2D(diffuse, texCoords) * vec4(R_ambient, 1); 21 | } 22 | -------------------------------------------------------------------------------- /res/shaders/forward-ambient.vs: -------------------------------------------------------------------------------- 1 | #version 120 2 | #include "lighting.vsh" 3 | -------------------------------------------------------------------------------- /res/shaders/forward-ambient2.fs: -------------------------------------------------------------------------------- 1 | #version 120 2 | #include "sampling.glh" 3 | 4 | varying vec2 texCoord0; 5 | varying vec3 worldPos0; 6 | varying mat3 tbnMatrix; 7 | 8 | uniform vec3 R_ambient; 9 | uniform vec3 C_eyePos; 10 | uniform sampler2D diffuse; 11 | uniform sampler2D dispMap; 12 | 13 | uniform float dispMapScale; 14 | uniform float dispMapBias; 15 | 16 | void main() 17 | { 18 | vec3 directionToEye = normalize(C_eyePos - worldPos0); 19 | vec2 texCoords = CalcParallaxTexCoords(dispMap, tbnMatrix, directionToEye, texCoord0, dispMapScale, dispMapBias); 20 | gl_FragColor = texture2D(diffuse, texCoords) * vec4(R_ambient, 1); 21 | } 22 | -------------------------------------------------------------------------------- /res/shaders/forward-ambient2.vs: -------------------------------------------------------------------------------- 1 | #version 440 2 | #define MAX_BONES 200 3 | in vec3 position; 4 | in vec2 texCoord; 5 | in vec3 normal; 6 | in vec3 tangent; 7 | in vec4 boneDataA; 8 | in vec4 boneDataB; 9 | 10 | out vec2 texCoord0; 11 | out vec3 worldPos0; 12 | out mat3 tbnMatrix; 13 | 14 | uniform mat4 T_model; 15 | uniform mat4 T_MVP; 16 | 17 | uniform mat4 gBones[200]; 18 | 19 | void main() 20 | { 21 | mat4 BoneTransform = gBones[uint(boneDataA.x)] * boneDataA.z + 22 | gBones[uint(boneDataA.y)] * boneDataA.w + 23 | gBones[uint(boneDataB.x)] * boneDataB.z + 24 | gBones[uint(boneDataB.y)] * boneDataB.w ; 25 | 26 | vec4 pos = BoneTransform * vec4(position, 1.0); 27 | 28 | gl_Position = T_MVP * pos; 29 | texCoord0 = texCoord; 30 | worldPos0 = (T_model * pos).xyz; 31 | 32 | vec3 n = normalize((T_model * vec4(normal, 0.0)).xyz); 33 | vec3 t = normalize((T_model * vec4(tangent, 0.0)).xyz); 34 | t = normalize(t - dot(t, n) * n); 35 | 36 | vec3 biTangent = cross(t, n); 37 | tbnMatrix = mat3(t, biTangent, n); 38 | } -------------------------------------------------------------------------------- /res/shaders/forward-directional.fs: -------------------------------------------------------------------------------- 1 | #version 120 2 | #include "lighting.fsh" 3 | 4 | uniform DirectionalLight R_directionalLight; 5 | 6 | vec4 CalcLightingEffect(vec3 normal, vec3 worldPos) 7 | { 8 | return CalcDirectionalLight(R_directionalLight, normal, worldPos); 9 | } 10 | 11 | #include "lightingMain.fsh" 12 | -------------------------------------------------------------------------------- /res/shaders/forward-directional.vs: -------------------------------------------------------------------------------- 1 | #version 120 2 | #include "lighting.vsh" 3 | -------------------------------------------------------------------------------- /res/shaders/forward-point.fs: -------------------------------------------------------------------------------- 1 | #version 120 2 | #include "lighting.fsh" 3 | 4 | uniform PointLight R_pointLight; 5 | 6 | vec4 CalcLightingEffect(vec3 normal, vec3 worldPos) 7 | { 8 | return CalcPointLight(R_pointLight, normal, worldPos); 9 | } 10 | 11 | #include "lightingMain.fsh" 12 | -------------------------------------------------------------------------------- /res/shaders/forward-point.vs: -------------------------------------------------------------------------------- 1 | #version 120 2 | #include "lighting.vsh" 3 | -------------------------------------------------------------------------------- /res/shaders/forward-spot.fs: -------------------------------------------------------------------------------- 1 | #version 120 2 | #include "lighting.fsh" 3 | 4 | uniform SpotLight R_spotLight; 5 | 6 | vec4 CalcLightingEffect(vec3 normal, vec3 worldPos) 7 | { 8 | return CalcSpotLight(R_spotLight, normal, worldPos); 9 | } 10 | 11 | #include "lightingMain.fsh" 12 | -------------------------------------------------------------------------------- /res/shaders/forward-spot.vs: -------------------------------------------------------------------------------- 1 | #version 120 2 | #include "lighting.vsh" 3 | -------------------------------------------------------------------------------- /res/shaders/lighting.fsh: -------------------------------------------------------------------------------- 1 | varying vec2 texCoord0; 2 | varying vec3 worldPos0; 3 | varying mat3 tbnMatrix; 4 | 5 | uniform sampler2D diffuse; 6 | uniform sampler2D normalMap; 7 | uniform sampler2D dispMap; 8 | 9 | uniform float dispMapScale; 10 | uniform float dispMapBias; 11 | 12 | #include "lighting.glh" 13 | -------------------------------------------------------------------------------- /res/shaders/lighting.glh: -------------------------------------------------------------------------------- 1 | uniform vec3 C_eyePos; 2 | uniform float specularIntensity; 3 | uniform float specularPower; 4 | 5 | struct BaseLight 6 | { 7 | vec3 color; 8 | float intensity; 9 | }; 10 | 11 | struct Attenuation 12 | { 13 | float constant; 14 | float linear; 15 | float exponent; 16 | }; 17 | 18 | struct DirectionalLight 19 | { 20 | BaseLight base; 21 | vec3 direction; 22 | }; 23 | 24 | struct PointLight 25 | { 26 | BaseLight base; 27 | Attenuation atten; 28 | vec3 position; 29 | float range; 30 | }; 31 | 32 | struct SpotLight 33 | { 34 | PointLight pointLight; 35 | vec3 direction; 36 | float cutoff; 37 | }; 38 | 39 | vec4 CalcLight(BaseLight base, vec3 direction, vec3 normal, vec3 worldPos) 40 | { 41 | float diffuseFactor = dot(normal, -direction); 42 | 43 | vec4 diffuseColor = vec4(0,0,0,0); 44 | vec4 specularColor = vec4(0,0,0,0); 45 | 46 | if(diffuseFactor > 0) 47 | { 48 | diffuseColor = vec4(base.color, 1.0) * base.intensity * diffuseFactor; 49 | 50 | vec3 directionToEye = normalize(C_eyePos - worldPos); 51 | //vec3 reflectDirection = normalize(reflect(direction, normal)); 52 | vec3 halfDirection = normalize(directionToEye - direction); 53 | 54 | float specularFactor = dot(halfDirection, normal); 55 | //float specularFactor = dot(directionToEye, reflectDirection); 56 | specularFactor = pow(specularFactor, specularPower); 57 | 58 | if(specularFactor > 0) 59 | { 60 | specularColor = vec4(base.color, 1.0) * specularIntensity * specularFactor; 61 | } 62 | } 63 | 64 | return diffuseColor + specularColor; 65 | } 66 | 67 | vec4 CalcPointLight(PointLight pointLight, vec3 normal, vec3 worldPos) 68 | { 69 | vec3 lightDirection = worldPos - pointLight.position; 70 | float distanceToPoint = length(lightDirection); 71 | 72 | if(distanceToPoint > pointLight.range) 73 | return vec4(0,0,0,0); 74 | 75 | lightDirection = normalize(lightDirection); 76 | 77 | vec4 color = CalcLight(pointLight.base, lightDirection, normal, worldPos); 78 | 79 | float attenuation = pointLight.atten.constant + 80 | pointLight.atten.linear * distanceToPoint + 81 | pointLight.atten.exponent * distanceToPoint * distanceToPoint + 82 | 0.0001; 83 | 84 | return color / attenuation; 85 | } 86 | 87 | vec4 CalcSpotLight(SpotLight spotLight, vec3 normal, vec3 worldPos) 88 | { 89 | vec3 lightDirection = normalize(worldPos - spotLight.pointLight.position); 90 | float spotFactor = dot(lightDirection, spotLight.direction); 91 | 92 | vec4 color = vec4(0,0,0,0); 93 | 94 | if(spotFactor > spotLight.cutoff) 95 | { 96 | color = CalcPointLight(spotLight.pointLight, normal, worldPos) * 97 | (1.0 - (1.0 - spotFactor)/(1.0 - spotLight.cutoff)); 98 | } 99 | 100 | return color; 101 | } 102 | 103 | vec4 CalcDirectionalLight(DirectionalLight directionalLight, vec3 normal, vec3 worldPos) 104 | { 105 | return CalcLight(directionalLight.base, -directionalLight.direction, normal, worldPos); 106 | } 107 | -------------------------------------------------------------------------------- /res/shaders/lighting.vsh: -------------------------------------------------------------------------------- 1 | attribute vec3 position; 2 | attribute vec2 texCoord; 3 | attribute vec3 normal; 4 | attribute vec3 tangent; 5 | 6 | varying vec2 texCoord0; 7 | varying vec3 worldPos0; 8 | varying mat3 tbnMatrix; 9 | 10 | uniform mat4 T_model; 11 | uniform mat4 T_MVP; 12 | 13 | void main() 14 | { 15 | gl_Position = T_MVP * vec4(position, 1.0); 16 | texCoord0 = texCoord; 17 | worldPos0 = (T_model * vec4(position, 1.0)).xyz; 18 | 19 | vec3 n = normalize((T_model * vec4(normal, 0.0)).xyz); 20 | vec3 t = normalize((T_model * vec4(tangent, 0.0)).xyz); 21 | t = normalize(t - dot(t, n) * n); 22 | 23 | vec3 biTangent = cross(t, n); 24 | tbnMatrix = mat3(t, biTangent, n); 25 | } 26 | -------------------------------------------------------------------------------- /res/shaders/lightingMain.fsh: -------------------------------------------------------------------------------- 1 | #include "sampling.glh" 2 | 3 | void main() 4 | { 5 | vec3 directionToEye = normalize(C_eyePos - worldPos0); 6 | vec2 texCoords = CalcParallaxTexCoords(dispMap, tbnMatrix, directionToEye, texCoord0, dispMapScale, dispMapBias); 7 | 8 | vec3 normal = normalize(tbnMatrix * (255.0/128.0 * texture2D(normalMap, texCoords).xyz - 1)); 9 | gl_FragColor = texture2D(diffuse, texCoords) * 10 | CalcLightingEffect(normal, worldPos0); 11 | } 12 | -------------------------------------------------------------------------------- /res/shaders/sampling.glh: -------------------------------------------------------------------------------- 1 | 2 | vec2 CalcParallaxTexCoords(sampler2D dispMap, mat3 tbnMatrix, vec3 directionToEye, vec2 texCoords, float scale, float bias) 3 | { 4 | return texCoords.xy + (directionToEye * tbnMatrix).xy * (texture2D(dispMap, texCoords.xy).r * scale + bias); 5 | } 6 | -------------------------------------------------------------------------------- /res/textures/black.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/black.png -------------------------------------------------------------------------------- /res/textures/bricks.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/bricks.jpg -------------------------------------------------------------------------------- /res/textures/bricks2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/bricks2.jpg -------------------------------------------------------------------------------- /res/textures/bricks2_disp.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/bricks2_disp.jpg -------------------------------------------------------------------------------- /res/textures/bricks2_normal.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/bricks2_normal.jpg -------------------------------------------------------------------------------- /res/textures/bricks2_normal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/bricks2_normal.png -------------------------------------------------------------------------------- /res/textures/bricks_disp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/bricks_disp.png -------------------------------------------------------------------------------- /res/textures/bricks_normal.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/bricks_normal.jpg -------------------------------------------------------------------------------- /res/textures/defaultTexture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/defaultTexture.png -------------------------------------------------------------------------------- /res/textures/default_disp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/default_disp.png -------------------------------------------------------------------------------- /res/textures/default_normal.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/default_normal.jpg -------------------------------------------------------------------------------- /res/textures/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/test.png -------------------------------------------------------------------------------- /res/textures/white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RagnarrIvarssen/Assimp-Tutorial-LWJGL-3/b2f425461ba825a51be1409b682daa74635a4128/res/textures/white.png -------------------------------------------------------------------------------- /src/com/base/engine/components/BaseLight.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.components; 18 | 19 | import com.base.engine.core.CoreEngine; 20 | import com.base.engine.core.Vector3f; 21 | import com.base.engine.rendering.Shader; 22 | 23 | public class BaseLight extends GameComponent 24 | { 25 | private Vector3f m_color; 26 | private float m_intensity; 27 | private Shader m_shader; 28 | 29 | public BaseLight(Vector3f color, float intensity) 30 | { 31 | this.m_color = color; 32 | this.m_intensity = intensity; 33 | } 34 | 35 | @Override 36 | public void AddToEngine(CoreEngine engine) 37 | { 38 | engine.GetRenderingEngine().AddLight(this); 39 | } 40 | 41 | public void SetShader(Shader shader) 42 | { 43 | this.m_shader = shader; 44 | } 45 | 46 | public Shader GetShader() 47 | { 48 | return m_shader; 49 | } 50 | 51 | public Vector3f GetColor() 52 | { 53 | return m_color; 54 | } 55 | 56 | public void SetColor(Vector3f color) 57 | { 58 | this.m_color = color; 59 | } 60 | 61 | public float GetIntensity() 62 | { 63 | return m_intensity; 64 | } 65 | 66 | public void SetIntensity(float intensity) 67 | { 68 | this.m_intensity = intensity; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/com/base/engine/components/Camera.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.components; 18 | 19 | import com.base.engine.core.*; 20 | 21 | public class Camera extends GameComponent 22 | { 23 | private Matrix4f m_projection; 24 | 25 | public Camera(Matrix4f projection) 26 | { 27 | this.m_projection = projection; 28 | } 29 | 30 | public Matrix4f GetViewProjection() 31 | { 32 | Matrix4f cameraRotation = GetTransform().GetTransformedRot().Conjugate().ToRotationMatrix(); 33 | Vector3f cameraPos = GetTransform().GetTransformedPos().Mul(-1); 34 | 35 | Matrix4f cameraTranslation = new Matrix4f().InitTranslation(cameraPos.GetX(), cameraPos.GetY(), cameraPos.GetZ()); 36 | 37 | return m_projection.Mul(cameraRotation.Mul(cameraTranslation)); 38 | } 39 | 40 | @Override 41 | public void AddToEngine(CoreEngine engine) 42 | { 43 | engine.GetRenderingEngine().AddCamera(this); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/com/base/engine/components/DirectionalLight.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.components; 18 | 19 | import com.base.engine.core.Vector3f; 20 | import com.base.engine.rendering.Shader; 21 | 22 | public class DirectionalLight extends BaseLight 23 | { 24 | public DirectionalLight(Vector3f color, float intensity) 25 | { 26 | super(color, intensity); 27 | 28 | SetShader(new Shader("forward-directional")); 29 | } 30 | 31 | public Vector3f GetDirection() 32 | { 33 | return GetTransform().GetTransformedRot().GetForward(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/com/base/engine/components/FreeLook.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.components; 18 | 19 | import com.base.engine.core.Input; 20 | import com.base.engine.core.Vector2f; 21 | import com.base.engine.core.Vector3f; 22 | import com.base.engine.rendering.Window; 23 | 24 | public class FreeLook extends GameComponent 25 | { 26 | private static final Vector3f Y_AXIS = new Vector3f(0,1,0); 27 | 28 | private boolean m_mouseLocked = false; 29 | private float m_sensitivity; 30 | private int m_unlockMouseKey; 31 | 32 | public FreeLook(float sensitivity) 33 | { 34 | this(sensitivity, Input.KEY_ESCAPE); 35 | } 36 | 37 | public FreeLook(float sensitivity, int unlockMouseKey) 38 | { 39 | this.m_sensitivity = sensitivity; 40 | this.m_unlockMouseKey = unlockMouseKey; 41 | } 42 | 43 | @Override 44 | public void Input(float delta) 45 | { 46 | Vector2f centerPosition = new Vector2f(Window.GetWidth()/2, Window.GetHeight()/2); 47 | 48 | if(Input.GetKey(m_unlockMouseKey)) 49 | { 50 | Input.SetCursor(true); 51 | m_mouseLocked = false; 52 | } 53 | if(Input.GetMouseDown(0)) 54 | { 55 | Input.SetMousePosition(centerPosition); 56 | Input.SetCursor(false); 57 | m_mouseLocked = true; 58 | } 59 | 60 | if(m_mouseLocked) 61 | { 62 | Vector2f deltaPos = Input.GetMousePosition().Sub(centerPosition); 63 | 64 | boolean rotY = deltaPos.GetX() != 0; 65 | boolean rotX = deltaPos.GetY() != 0; 66 | 67 | if(rotY) 68 | GetTransform().Rotate(Y_AXIS, (float) Math.toRadians(deltaPos.GetX() * m_sensitivity)); 69 | if(rotX) 70 | GetTransform().Rotate(GetTransform().GetRot().GetRight(), (float) Math.toRadians(-deltaPos.GetY() * m_sensitivity)); 71 | 72 | if(rotY || rotX) 73 | Input.SetMousePosition(centerPosition); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/com/base/engine/components/FreeMove.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.components; 18 | 19 | import com.base.engine.core.Input; 20 | import com.base.engine.core.Vector3f; 21 | 22 | public class FreeMove extends GameComponent 23 | { 24 | private float m_speed; 25 | private int m_forwardKey; 26 | private int m_backKey; 27 | private int m_leftKey; 28 | private int m_rightKey; 29 | 30 | public FreeMove(float speed) 31 | { 32 | this(speed, Input.KEY_W, Input.KEY_S, Input.KEY_A, Input.KEY_D); 33 | } 34 | 35 | public FreeMove(float speed, int forwardKey, int backKey, int leftKey, int rightKey) 36 | { 37 | this.m_speed = speed; 38 | this.m_forwardKey = forwardKey; 39 | this.m_backKey = backKey; 40 | this.m_leftKey = leftKey; 41 | this.m_rightKey = rightKey; 42 | } 43 | 44 | @Override 45 | public void Input(float delta) 46 | { 47 | float movAmt = m_speed * delta; 48 | 49 | if(Input.GetKey(m_forwardKey)) 50 | Move(GetTransform().GetRot().GetForward(), movAmt); 51 | if(Input.GetKey(m_backKey)) 52 | Move(GetTransform().GetRot().GetForward(), -movAmt); 53 | if(Input.GetKey(m_leftKey)) 54 | Move(GetTransform().GetRot().GetLeft(), movAmt); 55 | if(Input.GetKey(m_rightKey)) 56 | Move(GetTransform().GetRot().GetRight(), movAmt); 57 | } 58 | 59 | private void Move(Vector3f dir, float amt) 60 | { 61 | GetTransform().SetPos(GetTransform().GetPos().Add(dir.Mul(amt))); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/com/base/engine/components/GameComponent.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.components; 18 | 19 | import com.base.engine.core.CoreEngine; 20 | import com.base.engine.core.GameObject; 21 | import com.base.engine.rendering.RenderingEngine; 22 | import com.base.engine.core.Transform; 23 | import com.base.engine.rendering.Shader; 24 | 25 | public abstract class GameComponent 26 | { 27 | private GameObject m_parent; 28 | 29 | public void Input(float delta) {} 30 | public void Update(float delta) {} 31 | public void Render(Shader shader, RenderingEngine renderingEngine) {} 32 | 33 | public void SetParent(GameObject parent) 34 | { 35 | this.m_parent = parent; 36 | } 37 | 38 | public Transform GetTransform() 39 | { 40 | return m_parent.GetTransform(); 41 | } 42 | 43 | public void AddToEngine(CoreEngine engine) {} 44 | } 45 | 46 | -------------------------------------------------------------------------------- /src/com/base/engine/components/MeshRenderer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.components; 18 | 19 | import com.base.engine.rendering.Material; 20 | import com.base.engine.rendering.Mesh; 21 | import com.base.engine.rendering.RenderingEngine; 22 | import com.base.engine.rendering.Shader; 23 | 24 | public class MeshRenderer extends GameComponent 25 | { 26 | private Mesh m_mesh; 27 | private Material m_material; 28 | 29 | public MeshRenderer(Mesh mesh, Material material) 30 | { 31 | this.m_mesh = mesh; 32 | this.m_material = material; 33 | } 34 | 35 | @Override 36 | public void Render(Shader shader, RenderingEngine renderingEngine) 37 | { 38 | shader.Bind(); 39 | shader.UpdateUniforms(GetTransform(), m_material, renderingEngine); 40 | m_mesh.Draw(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/com/base/engine/components/PointLight.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.components; 18 | 19 | import com.base.engine.core.Vector3f; 20 | import com.base.engine.rendering.Attenuation; 21 | import com.base.engine.rendering.Shader; 22 | 23 | public class PointLight extends BaseLight 24 | { 25 | private static final int COLOR_DEPTH = 256; 26 | 27 | private Attenuation m_attenuation; 28 | private float m_range; 29 | 30 | public PointLight(Vector3f color, float intensity, Attenuation attenuation) 31 | { 32 | super(color, intensity); 33 | this.m_attenuation = attenuation; 34 | 35 | float a = attenuation.GetExponent(); 36 | float b = attenuation.GetLinear(); 37 | float c = attenuation.GetConstant() - COLOR_DEPTH * GetIntensity() * GetColor().Max(); 38 | 39 | this.m_range = (float)((-b + Math.sqrt(b * b - 4 * a * c))/(2 * a)); 40 | 41 | SetShader(new Shader("forward-point")); 42 | } 43 | 44 | public float GetRange() 45 | { 46 | return m_range; 47 | } 48 | 49 | public void SetRange(float range) 50 | { 51 | this.m_range = range; 52 | } 53 | 54 | public Attenuation GetAttenuation() 55 | { 56 | return m_attenuation; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/com/base/engine/components/SpotLight.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.components; 18 | 19 | import com.base.engine.core.Vector3f; 20 | import com.base.engine.rendering.Attenuation; 21 | import com.base.engine.rendering.Shader; 22 | 23 | public class SpotLight extends PointLight 24 | { 25 | private float m_cutoff; 26 | 27 | public SpotLight(Vector3f color, float intensity, Attenuation attenuation, float cutoff) 28 | { 29 | super(color, intensity, attenuation); 30 | this.m_cutoff = cutoff; 31 | 32 | SetShader(new Shader("forward-spot")); 33 | } 34 | 35 | public Vector3f GetDirection() 36 | { 37 | return GetTransform().GetTransformedRot().GetForward(); 38 | } 39 | 40 | public float GetCutoff() 41 | { 42 | return m_cutoff; 43 | } 44 | 45 | public void SetCutoff(float cutoff) 46 | { 47 | this.m_cutoff = cutoff; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/com/base/engine/core/CoreEngine.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | import com.base.engine.rendering.RenderingEngine; 20 | import com.base.engine.rendering.Window; 21 | 22 | public class CoreEngine 23 | { 24 | private boolean m_isRunning; 25 | private Game m_game; 26 | private RenderingEngine m_renderingEngine; 27 | private int m_width; 28 | private int m_height; 29 | private double m_frameTime; 30 | 31 | public CoreEngine(int width, int height, double framerate, Game game) 32 | { 33 | this.m_isRunning = false; 34 | this.m_game = game; 35 | this.m_width = width; 36 | this.m_height = height; 37 | this.m_frameTime = 1.0/framerate; 38 | game.SetEngine(this); 39 | } 40 | 41 | public void CreateWindow(String title) 42 | { 43 | Window.CreateWindow(m_width, m_height, title); 44 | this.m_renderingEngine = new RenderingEngine(); 45 | } 46 | 47 | public void Start() 48 | { 49 | if(m_isRunning) 50 | return; 51 | 52 | Run(); 53 | } 54 | 55 | public void Stop() 56 | { 57 | if(!m_isRunning) 58 | return; 59 | 60 | m_isRunning = false; 61 | } 62 | 63 | private void Run() 64 | { 65 | m_isRunning = true; 66 | 67 | int frames = 0; 68 | double frameCounter = 0; 69 | 70 | m_game.Init(); 71 | 72 | double lastTime = Time.GetTime(); 73 | double unprocessedTime = 0; 74 | 75 | while(m_isRunning) 76 | { 77 | boolean render = false; 78 | 79 | double startTime = Time.GetTime(); 80 | double passedTime = startTime - lastTime; 81 | lastTime = startTime; 82 | 83 | unprocessedTime += passedTime; 84 | frameCounter += passedTime; 85 | 86 | while(unprocessedTime > m_frameTime) 87 | { 88 | render = true; 89 | 90 | unprocessedTime -= m_frameTime; 91 | 92 | if(Window.IsCloseRequested()) 93 | Stop(); 94 | 95 | Window.Update(); 96 | m_game.Input((float) m_frameTime); 97 | Input.Update(); 98 | 99 | m_game.Update((float) m_frameTime); 100 | 101 | if(frameCounter >= 1.0) 102 | { 103 | System.out.println(frames); 104 | frames = 0; 105 | frameCounter = 0; 106 | } 107 | } 108 | if(render) 109 | { 110 | m_game.Render(m_renderingEngine); 111 | Window.Render(); 112 | frames++; 113 | } 114 | else 115 | { 116 | try 117 | { 118 | Thread.sleep(1); 119 | } 120 | catch (InterruptedException e) 121 | { 122 | e.printStackTrace(); 123 | } 124 | } 125 | } 126 | 127 | CleanUp(); 128 | } 129 | 130 | private void CleanUp() 131 | { 132 | Window.Dispose(); 133 | } 134 | 135 | public RenderingEngine GetRenderingEngine() { 136 | return m_renderingEngine; 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /src/com/base/engine/core/Game.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | import com.base.engine.rendering.RenderingEngine; 20 | 21 | public abstract class Game 22 | { 23 | private GameObject m_root; 24 | 25 | public void Init() {} 26 | 27 | public void Input(float delta) 28 | { 29 | GetRootObject().InputAll(delta); 30 | } 31 | 32 | public void Update(float delta) 33 | { 34 | GetRootObject().UpdateAll(delta); 35 | } 36 | 37 | public void Render(RenderingEngine renderingEngine) 38 | { 39 | renderingEngine.Render(GetRootObject()); 40 | } 41 | 42 | public void AddObject(GameObject object) 43 | { 44 | GetRootObject().AddChild(object); 45 | } 46 | 47 | private GameObject GetRootObject() 48 | { 49 | if(m_root == null) 50 | m_root = new GameObject(); 51 | 52 | return m_root; 53 | } 54 | 55 | public void SetEngine(CoreEngine engine) { GetRootObject().SetEngine(engine); } 56 | } 57 | -------------------------------------------------------------------------------- /src/com/base/engine/core/GameObject.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | import com.base.engine.components.GameComponent; 20 | import com.base.engine.rendering.RenderingEngine; 21 | import com.base.engine.rendering.Shader; 22 | 23 | import java.util.ArrayList; 24 | 25 | public class GameObject 26 | { 27 | private ArrayList m_children; 28 | private ArrayList m_components; 29 | private Transform m_transform; 30 | private CoreEngine m_engine; 31 | 32 | public GameObject() 33 | { 34 | m_children = new ArrayList(); 35 | m_components = new ArrayList(); 36 | m_transform = new Transform(); 37 | m_engine = null; 38 | } 39 | 40 | public GameObject AddChild(GameObject child) 41 | { 42 | m_children.add(child); 43 | child.SetEngine(m_engine); 44 | child.GetTransform().SetParent(m_transform); 45 | 46 | return this; 47 | } 48 | 49 | public GameObject AddComponent(GameComponent component) 50 | { 51 | m_components.add(component); 52 | component.SetParent(this); 53 | 54 | return this; 55 | } 56 | 57 | public void InputAll(float delta) 58 | { 59 | Input(delta); 60 | 61 | for(GameObject child : m_children) 62 | child.InputAll(delta); 63 | } 64 | 65 | public void UpdateAll(float delta) 66 | { 67 | Update(delta); 68 | 69 | for(GameObject child : m_children) 70 | child.UpdateAll(delta); 71 | } 72 | 73 | public void RenderAll(Shader shader, RenderingEngine renderingEngine) 74 | { 75 | Render(shader, renderingEngine); 76 | 77 | for(GameObject child : m_children) 78 | child.RenderAll(shader, renderingEngine); 79 | } 80 | 81 | public void Input(float delta) 82 | { 83 | m_transform.Update(); 84 | 85 | for(GameComponent component : m_components) 86 | component.Input(delta); 87 | } 88 | 89 | public void Update(float delta) 90 | { 91 | for(GameComponent component : m_components) 92 | component.Update(delta); 93 | } 94 | 95 | public void Render(Shader shader, RenderingEngine renderingEngine) 96 | { 97 | for(GameComponent component : m_components) 98 | component.Render(shader, renderingEngine); 99 | } 100 | 101 | public ArrayList GetAllAttached() 102 | { 103 | ArrayList result = new ArrayList(); 104 | 105 | for(GameObject child : m_children) 106 | result.addAll(child.GetAllAttached()); 107 | 108 | result.add(this); 109 | return result; 110 | } 111 | 112 | public Transform GetTransform() 113 | { 114 | return m_transform; 115 | } 116 | 117 | public void SetEngine(CoreEngine engine) 118 | { 119 | if(this.m_engine != engine) 120 | { 121 | this.m_engine = engine; 122 | 123 | for(GameComponent component : m_components) 124 | component.AddToEngine(engine); 125 | 126 | for(GameObject child : m_children) 127 | child.SetEngine(engine); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/com/base/engine/core/Input.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | import java.util.ArrayList; 20 | import java.util.HashMap; 21 | 22 | import org.lwjgl.glfw.GLFW; 23 | 24 | import com.base.engine.rendering.Window; 25 | 26 | public class Input 27 | { 28 | public static ArrayList keys = new ArrayList<>(); 29 | public static final int NUM_MOUSEBUTTONS = 5; 30 | 31 | //All these constants come from LWJGL's Keyboard class 32 | public static final int KEY_ESCAPE = Key(GLFW.GLFW_KEY_ESCAPE); 33 | public static final int KEY_1 = Key(GLFW.GLFW_KEY_1); 34 | public static final int KEY_2 = Key(GLFW.GLFW_KEY_2); 35 | public static final int KEY_3 = Key(GLFW.GLFW_KEY_3); 36 | public static final int KEY_4 = Key(GLFW.GLFW_KEY_4); 37 | public static final int KEY_5 = Key(GLFW.GLFW_KEY_5); 38 | public static final int KEY_6 = Key(GLFW.GLFW_KEY_6); 39 | public static final int KEY_7 = Key(GLFW.GLFW_KEY_7); 40 | public static final int KEY_8 = Key(GLFW.GLFW_KEY_8); 41 | public static final int KEY_9 = Key(GLFW.GLFW_KEY_9); 42 | public static final int KEY_0 = Key(GLFW.GLFW_KEY_0); 43 | public static final int KEY_MINUS = Key(GLFW.GLFW_KEY_MINUS); /* - on main keyboard */ 44 | public static final int KEY_EQUALS = Key(GLFW.GLFW_KEY_EQUAL); 45 | public static final int KEY_BACKSPACE = Key(GLFW.GLFW_KEY_BACKSPACE); /* backspace */ 46 | public static final int KEY_TAB = Key(GLFW.GLFW_KEY_TAB); 47 | public static final int KEY_Q = Key(GLFW.GLFW_KEY_Q); 48 | public static final int KEY_W = Key(GLFW.GLFW_KEY_W); 49 | public static final int KEY_E = Key(GLFW.GLFW_KEY_E); 50 | public static final int KEY_R = Key(GLFW.GLFW_KEY_R); 51 | public static final int KEY_T = Key(GLFW.GLFW_KEY_T); 52 | public static final int KEY_Y = Key(GLFW.GLFW_KEY_Y); 53 | public static final int KEY_U = Key(GLFW.GLFW_KEY_U); 54 | public static final int KEY_I = Key(GLFW.GLFW_KEY_I); 55 | public static final int KEY_O = Key(GLFW.GLFW_KEY_O); 56 | public static final int KEY_P = Key(GLFW.GLFW_KEY_P); 57 | public static final int KEY_LBRACKET = Key(GLFW.GLFW_KEY_LEFT_BRACKET); 58 | public static final int KEY_RBRACKET = Key(GLFW.GLFW_KEY_RIGHT_BRACKET); 59 | public static final int KEY_RETURN = Key(GLFW.GLFW_KEY_ENTER); /* Enter on main keyboard */ 60 | public static final int KEY_ENTER = Key(GLFW.GLFW_KEY_ENTER); /* Enter on main keyboard */ 61 | public static final int KEY_LCONTROL = Key(GLFW.GLFW_KEY_LEFT_CONTROL); 62 | public static final int KEY_A = Key(GLFW.GLFW_KEY_A); 63 | public static final int KEY_S = Key(GLFW.GLFW_KEY_S); 64 | public static final int KEY_D = Key(GLFW.GLFW_KEY_D); 65 | public static final int KEY_F = Key(GLFW.GLFW_KEY_F); 66 | public static final int KEY_G = Key(GLFW.GLFW_KEY_G); 67 | public static final int KEY_H = Key(GLFW.GLFW_KEY_H); 68 | public static final int KEY_J = Key(GLFW.GLFW_KEY_J); 69 | public static final int KEY_K = Key(GLFW.GLFW_KEY_K); 70 | public static final int KEY_L = Key(GLFW.GLFW_KEY_L); 71 | public static final int KEY_SEMICOLON = Key(GLFW.GLFW_KEY_SEMICOLON); 72 | public static final int KEY_APOSTROPHE = Key(GLFW.GLFW_KEY_APOSTROPHE); 73 | public static final int KEY_GRAVE = Key(GLFW.GLFW_KEY_GRAVE_ACCENT); /* accent grave */ 74 | public static final int KEY_LSHIFT = Key(GLFW.GLFW_KEY_LEFT_SHIFT); 75 | public static final int KEY_BACKSLASH = Key(GLFW.GLFW_KEY_BACKSLASH); 76 | public static final int KEY_Z = Key(GLFW.GLFW_KEY_Z); 77 | public static final int KEY_X = Key(GLFW.GLFW_KEY_X); 78 | public static final int KEY_C = Key(GLFW.GLFW_KEY_C); 79 | public static final int KEY_V = Key(GLFW.GLFW_KEY_V); 80 | public static final int KEY_B = Key(GLFW.GLFW_KEY_B); 81 | public static final int KEY_N = Key(GLFW.GLFW_KEY_N); 82 | public static final int KEY_M = Key(GLFW.GLFW_KEY_M); 83 | public static final int KEY_COMMA = Key(GLFW.GLFW_KEY_COMMA); 84 | public static final int KEY_PERIOD = Key(GLFW.GLFW_KEY_PERIOD); /* . on main keyboard */ 85 | public static final int KEY_SLASH = Key(GLFW.GLFW_KEY_SLASH); /* / on main keyboard */ 86 | public static final int KEY_RSHIFT = Key(GLFW.GLFW_KEY_RIGHT_SHIFT); 87 | public static final int KEY_MULTIPLY = Key(GLFW.GLFW_KEY_KP_MULTIPLY); /* * on numeric keypad */ 88 | public static final int KEY_LMENU = Key(GLFW.GLFW_KEY_LEFT_ALT); /* left Alt */ 89 | public static final int KEY_LALT = Key(GLFW.GLFW_KEY_LEFT_ALT); /* left Alt */ 90 | public static final int KEY_SPACE = Key(GLFW.GLFW_KEY_SPACE); 91 | public static final int KEY_CAPS_LOCK = Key(GLFW.GLFW_KEY_CAPS_LOCK); 92 | public static final int KEY_F1 = Key(GLFW.GLFW_KEY_F1); 93 | public static final int KEY_F2 = Key(GLFW.GLFW_KEY_F2); 94 | public static final int KEY_F3 = Key(GLFW.GLFW_KEY_F3); 95 | public static final int KEY_F4 = Key(GLFW.GLFW_KEY_F4); 96 | public static final int KEY_F5 = Key(GLFW.GLFW_KEY_F5); 97 | public static final int KEY_F6 = Key(GLFW.GLFW_KEY_F6); 98 | public static final int KEY_F7 = Key(GLFW.GLFW_KEY_F7); 99 | public static final int KEY_F8 = Key(GLFW.GLFW_KEY_F8); 100 | public static final int KEY_F9 = Key(GLFW.GLFW_KEY_F9); 101 | public static final int KEY_F10 = Key(GLFW.GLFW_KEY_F10); 102 | public static final int KEY_NUMLOCK = Key(GLFW.GLFW_KEY_NUM_LOCK); 103 | public static final int KEY_SCROLL = Key(GLFW.GLFW_KEY_SCROLL_LOCK); /* Scroll Lock */ 104 | public static final int KEY_NUMPAD7 = Key(GLFW.GLFW_KEY_KP_7); 105 | public static final int KEY_NUMPAD8 = Key(GLFW.GLFW_KEY_KP_8); 106 | public static final int KEY_NUMPAD9 = Key(GLFW.GLFW_KEY_KP_9); 107 | public static final int KEY_SUBTRACT = Key(GLFW.GLFW_KEY_KP_SUBTRACT); /* - on numeric keypad */ 108 | public static final int KEY_NUMPAD4 = Key(GLFW.GLFW_KEY_KP_4); 109 | public static final int KEY_NUMPAD5 = Key(GLFW.GLFW_KEY_KP_5); 110 | public static final int KEY_NUMPAD6 = Key(GLFW.GLFW_KEY_KP_6); 111 | public static final int KEY_ADD = Key(GLFW.GLFW_KEY_KP_ADD); /* + on numeric keypad */ 112 | public static final int KEY_NUMPAD1 = Key(GLFW.GLFW_KEY_KP_1); 113 | public static final int KEY_NUMPAD2 = Key(GLFW.GLFW_KEY_KP_2); 114 | public static final int KEY_NUMPAD3 = Key(GLFW.GLFW_KEY_KP_3); 115 | public static final int KEY_NUMPAD0 = Key(GLFW.GLFW_KEY_KP_0); 116 | public static final int KEY_DECIMAL = Key(GLFW.GLFW_KEY_KP_DECIMAL); /* . on numeric keypad */ 117 | public static final int KEY_F11 = Key(GLFW.GLFW_KEY_F11); 118 | public static final int KEY_F12 = Key(GLFW.GLFW_KEY_F12); 119 | public static final int KEY_F13 = Key(GLFW.GLFW_KEY_F13); /* (NEC PC98) */ 120 | public static final int KEY_F14 = Key(GLFW.GLFW_KEY_F14); /* (NEC PC98) */ 121 | public static final int KEY_F15 = Key(GLFW.GLFW_KEY_F15); /* (NEC PC98) */ 122 | // public static final int KEY_KANA = Key(GLFW.GLFW_KEY_ka; /* (Japanese keyboard) */ 123 | // public static final int KEY_CONVERT = Key(GLFW.GLFW_KEY_; /* (Japanese keyboard) */ 124 | // public static final int KEY_NOCONVERT = Key(GLFW.GLFW_KEY_; /* (Japanese keyboard) */ 125 | // public static final int KEY_YEN = Key(GLFW.GLFW_KEY_; /* (Japanese keyboard) */ 126 | // public static final int KEY_NUMPADEQUALS Key(GLFW.GLFW_KEY_; /* = on numeric keypad (NEC PC98) */ 127 | // public static final int KEY_CIRCUMFLEX = Key(GLFW.GLFW_KEY_; /* (Japanese keyboard) */ 128 | // public static final int KEY_AT = Key(GLFW.GLFW_KEY_at; /* (NEC PC98) */ 129 | // public static final int KEY_COLON = Key(GLFW.GLFW_KEY_sem; /* (NEC PC98) */ 130 | // public static final int KEY_UNDERLINE = Key(GLFW.GLFW_KEY_; /* (NEC PC98) */ 131 | // public static final int KEY_KANJI = Key(GLFW.GLFW_KEY_; /* (Japanese keyboard) */ 132 | // public static final int KEY_STOP = Key(GLFW.GLFW_KEY_; /* (NEC PC98) */ 133 | // public static final int KEY_AX = Key(GLFW.GLFW_KEY_; /* (Japan AX) */ 134 | // public static final int KEY_UNLABELED = Key(GLFW.GLFW_KEY_; /* (J3100) */ 135 | public static final int KEY_NUMPADENTER = Key(GLFW.GLFW_KEY_KP_ENTER); /* Enter on numeric keypad */ 136 | public static final int KEY_RCONTROL = Key(GLFW.GLFW_KEY_RIGHT_CONTROL); 137 | // public static final int KEY_NUMPADCOMMA = Key(GLFW.GLFW_KEY_; /* , on numeric keypad (NEC PC98) */ 138 | // public static final int KEY_DIVIDE = Key(GLFW.GLFW_KEY_kp; /* / on numeric keypad */ 139 | // public static final int KEY_SYSRQ = Key(GLFW.GLFW_KEY_; 140 | public static final int KEY_RMENU = Key(GLFW.GLFW_KEY_RIGHT_ALT); /* right Alt */ 141 | public static final int KEY_RALT = Key(KEY_RMENU); /* right Alt */ 142 | public static final int KEY_PAUSE = Key(GLFW.GLFW_KEY_PAUSE); /* Pause */ 143 | public static final int KEY_HOME = Key(GLFW.GLFW_KEY_HOME); /* Home on arrow keypad */ 144 | public static final int KEY_UP = Key(GLFW.GLFW_KEY_UP); /* UpArrow on arrow keypad */ 145 | public static final int KEY_PRIOR = Key(GLFW.GLFW_KEY_PAGE_UP); /* PgUp on arrow keypad */ 146 | public static final int KEY_LEFT = Key(GLFW.GLFW_KEY_LEFT); /* LeftArrow on arrow keypad */ 147 | public static final int KEY_RIGHT = Key(GLFW.GLFW_KEY_RIGHT); /* RightArrow on arrow keypad */ 148 | public static final int KEY_END = Key(GLFW.GLFW_KEY_END); /* End on arrow keypad */ 149 | public static final int KEY_DOWN = Key(GLFW.GLFW_KEY_DOWN); /* DownArrow on arrow keypad */ 150 | public static final int KEY_NEXT = Key(GLFW.GLFW_KEY_PAGE_DOWN); /* PgDn on arrow keypad */ 151 | public static final int KEY_INSERT = Key(GLFW.GLFW_KEY_INSERT); /* Insert on arrow keypad */ 152 | public static final int KEY_DELETE = Key(GLFW.GLFW_KEY_DELETE); /* Delete on arrow keypad */ 153 | // public static final int KEY_LMETA = Key(GLFW.GLFW_KEY_; /* Left Windows/Option key */ 154 | // public static final int KEY_LWIN = Key(GLFW.GLFW_KEY_; /* Left Windows key */ 155 | // public static final int KEY_RMETA = Key(GLFW.GLFW_KEY_; /* Right Windows/Option key */ 156 | // public static final int KEY_RWIN = Key(GLFW.GLFW_KEY_; /* Right Windows key */ 157 | // public static final int KEY_APPS = Key(GLFW.GLFW_KEY_; /* AppMenu key */ 158 | // public static final int KEY_POWER = Key(GLFW.GLFW_KEY_; 159 | // public static final int KEY_SLEEP = Key(GLFW.GLFW_KEY_; 160 | 161 | 162 | // public class Key 163 | // { 164 | // int code; 165 | // public Key(int keyCode) {code=keyCode;} 166 | // } 167 | 168 | public static int Key(int code) 169 | { 170 | keys.add(code); 171 | return code; 172 | } 173 | 174 | public static final int NUM_KEYCODES = keys.size(); 175 | // private static boolean[] m_lastKeys = new boolean[keys.size()]; 176 | private static HashMap m_lastKeys = new HashMap<>(); 177 | private static boolean[] m_lastMouse = new boolean[NUM_MOUSEBUTTONS]; 178 | 179 | public static void Update() 180 | { 181 | // for(int i = 0; i < NUM_KEYCODES; i++) 182 | // m_lastKeys[i] = GetKey(i); 183 | 184 | // for(int i = 0; i < NUM_KEYCODES; i++) 185 | for(int key : keys) 186 | m_lastKeys.put(key, GetKey(key)); 187 | 188 | 189 | for(int i = 0; i < NUM_MOUSEBUTTONS; i++) 190 | m_lastMouse[i] = GetMouse(i); 191 | Window.Mouse.Update(); 192 | } 193 | 194 | public static boolean GetKey(int keyCode) 195 | { 196 | try{ 197 | return GLFW.glfwGetKey(Window.CurrentWindow(), keyCode) == GLFW.GLFW_PRESS;//Keyboard.isKeyDown(keyCode); 198 | } catch(Exception e) 199 | { 200 | return false; 201 | } 202 | } 203 | 204 | public static boolean GetKeyDown(int keyCode) 205 | { 206 | return GetKey(keyCode) && !m_lastKeys.get(keyCode); 207 | } 208 | 209 | public static boolean GetKeyUp(int keyCode) 210 | { 211 | return !GetKey(keyCode) && m_lastKeys.get(keyCode); 212 | } 213 | 214 | public static boolean Next() 215 | { 216 | for(boolean bool : m_lastKeys.values()) 217 | if(bool) return true; 218 | return false; 219 | } 220 | 221 | public static boolean GetMouse(int mouseButton) 222 | { 223 | return GLFW.glfwGetMouseButton(Window.CurrentWindow(), mouseButton) == GLFW.GLFW_PRESS;//Mouse.isButtonDown(mouseButton); 224 | } 225 | 226 | public static boolean GetMouseDown(int mouseButton) 227 | { 228 | return GetMouse(mouseButton) && !m_lastMouse[mouseButton]; 229 | } 230 | 231 | public static boolean GetMouseUp(int mouseButton) 232 | { 233 | return !GetMouse(mouseButton) && m_lastMouse[mouseButton]; 234 | } 235 | 236 | public static Vector2f GetMousePosition() 237 | { 238 | return new Vector2f((float)Window.Mouse.getX(), (float)Window.Mouse.getY()); 239 | } 240 | 241 | public static void SetMousePosition(Vector2f pos) 242 | { 243 | Window.Mouse.setCursorPosition(pos.GetX(), pos.GetY()); 244 | } 245 | 246 | public static void SetCursor(boolean enabled) 247 | { 248 | Window.Mouse.setGrabbed(!enabled); 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /src/com/base/engine/core/Matrix4f.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | import org.lwjgl.assimp.AIMatrix4x4; 20 | 21 | public class Matrix4f 22 | { 23 | private float[][] m; 24 | 25 | public Matrix4f() 26 | { 27 | m = new float[4][4]; 28 | } 29 | 30 | public Matrix4f InitIdentity() 31 | { 32 | m[0][0] = 1; m[0][1] = 0; m[0][2] = 0; m[0][3] = 0; 33 | m[1][0] = 0; m[1][1] = 1; m[1][2] = 0; m[1][3] = 0; 34 | m[2][0] = 0; m[2][1] = 0; m[2][2] = 1; m[2][3] = 0; 35 | m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; 36 | 37 | return this; 38 | } 39 | 40 | public Matrix4f InitTranslation(float x, float y, float z) 41 | { 42 | m[0][0] = 1; m[0][1] = 0; m[0][2] = 0; m[0][3] = x; 43 | m[1][0] = 0; m[1][1] = 1; m[1][2] = 0; m[1][3] = y; 44 | m[2][0] = 0; m[2][1] = 0; m[2][2] = 1; m[2][3] = z; 45 | m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; 46 | 47 | return this; 48 | } 49 | 50 | public Matrix4f InitRotation(float x, float y, float z) 51 | { 52 | Matrix4f rx = new Matrix4f(); 53 | Matrix4f ry = new Matrix4f(); 54 | Matrix4f rz = new Matrix4f(); 55 | 56 | x = (float)Math.toRadians(x); 57 | y = (float)Math.toRadians(y); 58 | z = (float)Math.toRadians(z); 59 | 60 | rz.m[0][0] = (float)Math.cos(z);rz.m[0][1] = -(float)Math.sin(z);rz.m[0][2] = 0; rz.m[0][3] = 0; 61 | rz.m[1][0] = (float)Math.sin(z);rz.m[1][1] = (float)Math.cos(z);rz.m[1][2] = 0; rz.m[1][3] = 0; 62 | rz.m[2][0] = 0; rz.m[2][1] = 0; rz.m[2][2] = 1; rz.m[2][3] = 0; 63 | rz.m[3][0] = 0; rz.m[3][1] = 0; rz.m[3][2] = 0; rz.m[3][3] = 1; 64 | 65 | rx.m[0][0] = 1; rx.m[0][1] = 0; rx.m[0][2] = 0; rx.m[0][3] = 0; 66 | rx.m[1][0] = 0; rx.m[1][1] = (float)Math.cos(x);rx.m[1][2] = -(float)Math.sin(x);rx.m[1][3] = 0; 67 | rx.m[2][0] = 0; rx.m[2][1] = (float)Math.sin(x);rx.m[2][2] = (float)Math.cos(x);rx.m[2][3] = 0; 68 | rx.m[3][0] = 0; rx.m[3][1] = 0; rx.m[3][2] = 0; rx.m[3][3] = 1; 69 | 70 | ry.m[0][0] = (float)Math.cos(y);ry.m[0][1] = 0; ry.m[0][2] = -(float)Math.sin(y);ry.m[0][3] = 0; 71 | ry.m[1][0] = 0; ry.m[1][1] = 1; ry.m[1][2] = 0; ry.m[1][3] = 0; 72 | ry.m[2][0] = (float)Math.sin(y);ry.m[2][1] = 0; ry.m[2][2] = (float)Math.cos(y);ry.m[2][3] = 0; 73 | ry.m[3][0] = 0; ry.m[3][1] = 0; ry.m[3][2] = 0; ry.m[3][3] = 1; 74 | 75 | m = rz.Mul(ry.Mul(rx)).GetM(); 76 | 77 | return this; 78 | } 79 | 80 | public Matrix4f InitScale(float x, float y, float z) 81 | { 82 | m[0][0] = x; m[0][1] = 0; m[0][2] = 0; m[0][3] = 0; 83 | m[1][0] = 0; m[1][1] = y; m[1][2] = 0; m[1][3] = 0; 84 | m[2][0] = 0; m[2][1] = 0; m[2][2] = z; m[2][3] = 0; 85 | m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; 86 | 87 | return this; 88 | } 89 | 90 | public Matrix4f InitPerspective(float fov, float aspectRatio, float zNear, float zFar) 91 | { 92 | float tanHalfFOV = (float)Math.tan(fov / 2); 93 | float zRange = zNear - zFar; 94 | 95 | m[0][0] = 1.0f / (tanHalfFOV * aspectRatio); m[0][1] = 0; m[0][2] = 0; m[0][3] = 0; 96 | m[1][0] = 0; m[1][1] = 1.0f / tanHalfFOV; m[1][2] = 0; m[1][3] = 0; 97 | m[2][0] = 0; m[2][1] = 0; m[2][2] = (-zNear -zFar)/zRange; m[2][3] = 2 * zFar * zNear / zRange; 98 | m[3][0] = 0; m[3][1] = 0; m[3][2] = 1; m[3][3] = 0; 99 | 100 | 101 | return this; 102 | } 103 | 104 | public Matrix4f InitOrthographic(float left, float right, float bottom, float top, float near, float far) 105 | { 106 | float width = right - left; 107 | float height = top - bottom; 108 | float depth = far - near; 109 | 110 | m[0][0] = 2/width;m[0][1] = 0; m[0][2] = 0; m[0][3] = -(right + left)/width; 111 | m[1][0] = 0; m[1][1] = 2/height;m[1][2] = 0; m[1][3] = -(top + bottom)/height; 112 | m[2][0] = 0; m[2][1] = 0; m[2][2] = -2/depth;m[2][3] = -(far + near)/depth; 113 | m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; 114 | 115 | return this; 116 | } 117 | 118 | public Matrix4f InitRotation(Vector3f forward, Vector3f up) 119 | { 120 | Vector3f f = forward.Normalized(); 121 | 122 | Vector3f r = up.Normalized(); 123 | r = r.Cross(f); 124 | 125 | Vector3f u = f.Cross(r); 126 | 127 | return InitRotation(f, u, r); 128 | } 129 | 130 | public Matrix4f InitRotation(Vector3f forward, Vector3f up, Vector3f right) 131 | { 132 | Vector3f f = forward; 133 | Vector3f r = right; 134 | Vector3f u = up; 135 | 136 | m[0][0] = r.GetX(); m[0][1] = r.GetY(); m[0][2] = r.GetZ(); m[0][3] = 0; 137 | m[1][0] = u.GetX(); m[1][1] = u.GetY(); m[1][2] = u.GetZ(); m[1][3] = 0; 138 | m[2][0] = f.GetX(); m[2][1] = f.GetY(); m[2][2] = f.GetZ(); m[2][3] = 0; 139 | m[3][0] = 0; m[3][1] = 0; m[3][2] = 0; m[3][3] = 1; 140 | 141 | return this; 142 | } 143 | 144 | public Vector3f Transform(Vector3f r) 145 | { 146 | return new Vector3f(m[0][0] * r.GetX() + m[0][1] * r.GetY() + m[0][2] * r.GetZ() + m[0][3], 147 | m[1][0] * r.GetX() + m[1][1] * r.GetY() + m[1][2] * r.GetZ() + m[1][3], 148 | m[2][0] * r.GetX() + m[2][1] * r.GetY() + m[2][2] * r.GetZ() + m[2][3]); 149 | } 150 | 151 | public Matrix4f Mul(Matrix4f r) 152 | { 153 | Matrix4f res = new Matrix4f(); 154 | 155 | for(int i = 0; i < 4; i++) 156 | { 157 | for(int j = 0; j < 4; j++) 158 | { 159 | res.Set(i, j, m[i][0] * r.Get(0, j) + 160 | m[i][1] * r.Get(1, j) + 161 | m[i][2] * r.Get(2, j) + 162 | m[i][3] * r.Get(3, j)); 163 | } 164 | } 165 | 166 | return res; 167 | } 168 | 169 | public float[][] GetM() 170 | { 171 | float[][] res = new float[4][4]; 172 | 173 | for(int i = 0; i < 4; i++) 174 | for(int j = 0; j < 4; j++) 175 | res[i][j] = m[i][j]; 176 | 177 | return res; 178 | } 179 | 180 | public float Get(int x, int y) 181 | { 182 | return m[x][y]; 183 | } 184 | 185 | public void SetM(float[][] m) 186 | { 187 | this.m = m; 188 | } 189 | 190 | public void Set(int x, int y, float value) 191 | { 192 | m[x][y] = value; 193 | } 194 | 195 | public Matrix4f fromAssimp(AIMatrix4x4 m) 196 | { 197 | this.m[0][0] = m.a1(); 198 | this.m[0][1] = m.a2(); 199 | this.m[0][2] = m.a3(); 200 | this.m[0][3] = m.a4(); 201 | 202 | this.m[1][0] = m.b1(); 203 | this.m[1][1] = m.b2(); 204 | this.m[1][2] = m.b3(); 205 | this.m[1][3] = m.b4(); 206 | 207 | this.m[2][0] = m.c1(); 208 | this.m[2][1] = m.c2(); 209 | this.m[2][2] = m.c3(); 210 | this.m[2][3] = m.c4(); 211 | 212 | this.m[3][0] = m.d1(); 213 | this.m[3][1] = m.d2(); 214 | this.m[3][2] = m.d3(); 215 | this.m[3][3] = m.d4(); 216 | 217 | return this; 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /src/com/base/engine/core/Quaternion.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | import org.lwjgl.assimp.AIQuaternion; 20 | 21 | public class Quaternion 22 | { 23 | private float m_x; 24 | private float m_y; 25 | private float m_z; 26 | private float m_w; 27 | 28 | public Quaternion(float x, float y, float z, float w) 29 | { 30 | this.m_x = x; 31 | this.m_y = y; 32 | this.m_z = z; 33 | this.m_w = w; 34 | } 35 | 36 | public Quaternion(Vector3f axis, float angle) 37 | { 38 | float sinHalfAngle = (float)Math.sin(angle / 2); 39 | float cosHalfAngle = (float)Math.cos(angle / 2); 40 | 41 | this.m_x = axis.GetX() * sinHalfAngle; 42 | this.m_y = axis.GetY() * sinHalfAngle; 43 | this.m_z = axis.GetZ() * sinHalfAngle; 44 | this.m_w = cosHalfAngle; 45 | } 46 | 47 | public float Length() 48 | { 49 | return (float)Math.sqrt(m_x * m_x + m_y * m_y + m_z * m_z + m_w * m_w); 50 | } 51 | 52 | public Quaternion Normalized() 53 | { 54 | float length = Length(); 55 | 56 | return new Quaternion(m_x / length, m_y / length, m_z / length, m_w / length); 57 | } 58 | 59 | public Quaternion Conjugate() 60 | { 61 | return new Quaternion(-m_x, -m_y, -m_z, m_w); 62 | } 63 | 64 | public Quaternion Mul(float r) 65 | { 66 | return new Quaternion(m_x * r, m_y * r, m_z * r, m_w * r); 67 | } 68 | 69 | public Quaternion Mul(Quaternion r) 70 | { 71 | float w_ = m_w * r.GetW() - m_x * r.GetX() - m_y * r.GetY() - m_z * r.GetZ(); 72 | float x_ = m_x * r.GetW() + m_w * r.GetX() + m_y * r.GetZ() - m_z * r.GetY(); 73 | float y_ = m_y * r.GetW() + m_w * r.GetY() + m_z * r.GetX() - m_x * r.GetZ(); 74 | float z_ = m_z * r.GetW() + m_w * r.GetZ() + m_x * r.GetY() - m_y * r.GetX(); 75 | 76 | return new Quaternion(x_, y_, z_, w_); 77 | } 78 | 79 | public Quaternion Mul(Vector3f r) 80 | { 81 | float w_ = -m_x * r.GetX() - m_y * r.GetY() - m_z * r.GetZ(); 82 | float x_ = m_w * r.GetX() + m_y * r.GetZ() - m_z * r.GetY(); 83 | float y_ = m_w * r.GetY() + m_z * r.GetX() - m_x * r.GetZ(); 84 | float z_ = m_w * r.GetZ() + m_x * r.GetY() - m_y * r.GetX(); 85 | 86 | return new Quaternion(x_, y_, z_, w_); 87 | } 88 | 89 | public Quaternion Sub(Quaternion r) 90 | { 91 | return new Quaternion(m_x - r.GetX(), m_y - r.GetY(), m_z - r.GetZ(), m_w - r.GetW()); 92 | } 93 | 94 | public Quaternion Add(Quaternion r) 95 | { 96 | return new Quaternion(m_x + r.GetX(), m_y + r.GetY(), m_z + r.GetZ(), m_w + r.GetW()); 97 | } 98 | 99 | public Matrix4f ToRotationMatrix() 100 | { 101 | Vector3f forward = new Vector3f(2.0f * (m_x * m_z - m_w * m_y), 2.0f * (m_y * m_z + m_w * m_x), 1.0f - 2.0f * (m_x * m_x + m_y * m_y)); 102 | Vector3f up = new Vector3f(2.0f * (m_x * m_y + m_w * m_z), 1.0f - 2.0f * (m_x * m_x + m_z * m_z), 2.0f * (m_y * m_z - m_w * m_x)); 103 | Vector3f right = new Vector3f(1.0f - 2.0f * (m_y * m_y + m_z * m_z), 2.0f * (m_x * m_y - m_w * m_z), 2.0f * (m_x * m_z + m_w * m_y)); 104 | 105 | return new Matrix4f().InitRotation(forward, up, right); 106 | } 107 | 108 | public float Dot(Quaternion r) 109 | { 110 | return m_x * r.GetX() + m_y * r.GetY() + m_z * r.GetZ() + m_w * r.GetW(); 111 | } 112 | 113 | public Quaternion NLerp(Quaternion dest, float lerpFactor, boolean shortest) 114 | { 115 | Quaternion correctedDest = dest; 116 | 117 | if(shortest && this.Dot(dest) < 0) 118 | correctedDest = new Quaternion(-dest.GetX(), -dest.GetY(), -dest.GetZ(), -dest.GetW()); 119 | 120 | return correctedDest.Sub(this).Mul(lerpFactor).Add(this).Normalized(); 121 | } 122 | 123 | public Quaternion SLerp(Quaternion dest, float lerpFactor, boolean shortest) 124 | { 125 | final float EPSILON = 1e3f; 126 | 127 | float cos = this.Dot(dest); 128 | Quaternion correctedDest = dest; 129 | 130 | if(shortest && cos < 0) 131 | { 132 | cos = -cos; 133 | correctedDest = new Quaternion(-dest.GetX(), -dest.GetY(), -dest.GetZ(), -dest.GetW()); 134 | } 135 | 136 | if(Math.abs(cos) >= 1 - EPSILON) 137 | return NLerp(correctedDest, lerpFactor, false); 138 | 139 | float sin = (float)Math.sqrt(1.0f - cos * cos); 140 | float angle = (float)Math.atan2(sin, cos); 141 | float invSin = 1.0f/sin; 142 | 143 | float srcFactor = (float)Math.sin((1.0f - lerpFactor) * angle) * invSin; 144 | float destFactor = (float)Math.sin((lerpFactor) * angle) * invSin; 145 | 146 | return this.Mul(srcFactor).Add(correctedDest.Mul(destFactor)); 147 | } 148 | 149 | //From Ken Shoemake's "Quaternion Calculus and Fast Animation" article 150 | public Quaternion(Matrix4f rot) 151 | { 152 | float trace = rot.Get(0, 0) + rot.Get(1, 1) + rot.Get(2, 2); 153 | 154 | if(trace > 0) 155 | { 156 | float s = 0.5f / (float)Math.sqrt(trace+ 1.0f); 157 | m_w = 0.25f / s; 158 | m_x = (rot.Get(1, 2) - rot.Get(2, 1)) * s; 159 | m_y = (rot.Get(2, 0) - rot.Get(0, 2)) * s; 160 | m_z = (rot.Get(0, 1) - rot.Get(1, 0)) * s; 161 | } 162 | else 163 | { 164 | if(rot.Get(0, 0) > rot.Get(1, 1) && rot.Get(0, 0) > rot.Get(2, 2)) 165 | { 166 | float s = 2.0f * (float)Math.sqrt(1.0f + rot.Get(0, 0) - rot.Get(1, 1) - rot.Get(2, 2)); 167 | m_w = (rot.Get(1, 2) - rot.Get(2, 1)) / s; 168 | m_x = 0.25f * s; 169 | m_y = (rot.Get(1, 0) + rot.Get(0, 1)) / s; 170 | m_z = (rot.Get(2, 0) + rot.Get(0, 2)) / s; 171 | } 172 | else if(rot.Get(1, 1) > rot.Get(2, 2)) 173 | { 174 | float s = 2.0f * (float)Math.sqrt(1.0f + rot.Get(1, 1) - rot.Get(0, 0) - rot.Get(2, 2)); 175 | m_w = (rot.Get(2, 0) - rot.Get(0, 2)) / s; 176 | m_x = (rot.Get(1, 0) + rot.Get(0, 1)) / s; 177 | m_y = 0.25f * s; 178 | m_z = (rot.Get(2, 1) + rot.Get(1, 2)) / s; 179 | } 180 | else 181 | { 182 | float s = 2.0f * (float)Math.sqrt(1.0f + rot.Get(2, 2) - rot.Get(0, 0) - rot.Get(1, 1)); 183 | m_w = (rot.Get(0, 1) - rot.Get(1, 0) ) / s; 184 | m_x = (rot.Get(2, 0) + rot.Get(0, 2) ) / s; 185 | m_y = (rot.Get(1, 2) + rot.Get(2, 1) ) / s; 186 | m_z = 0.25f * s; 187 | } 188 | } 189 | 190 | float length = (float)Math.sqrt(m_x * m_x + m_y * m_y + m_z * m_z + m_w * m_w); 191 | m_x /= length; 192 | m_y /= length; 193 | m_z /= length; 194 | m_w /= length; 195 | } 196 | 197 | public Vector3f GetForward() 198 | { 199 | return new Vector3f(0,0,1).Rotate(this); 200 | } 201 | 202 | public Vector3f GetBack() 203 | { 204 | return new Vector3f(0,0,-1).Rotate(this); 205 | } 206 | 207 | public Vector3f GetUp() 208 | { 209 | return new Vector3f(0,1,0).Rotate(this); 210 | } 211 | 212 | public Vector3f GetDown() 213 | { 214 | return new Vector3f(0,-1,0).Rotate(this); 215 | } 216 | 217 | public Vector3f GetRight() 218 | { 219 | return new Vector3f(1,0,0).Rotate(this); 220 | } 221 | 222 | public Vector3f GetLeft() 223 | { 224 | return new Vector3f(-1,0,0).Rotate(this); 225 | } 226 | 227 | public Quaternion Set(float x, float y, float z, float w) { this.m_x = x; this.m_y = y; this.m_z = z; this.m_w = w; return this; } 228 | public Quaternion Set(Quaternion r) { Set(r.GetX(), r.GetY(), r.GetZ(), r.GetW()); return this; } 229 | 230 | public float GetX() 231 | { 232 | return m_x; 233 | } 234 | 235 | public void SetX(float x) 236 | { 237 | this.m_x = x; 238 | } 239 | 240 | public float GetY() 241 | { 242 | return m_y; 243 | } 244 | 245 | public void SetY(float m_y) 246 | { 247 | this.m_y = m_y; 248 | } 249 | 250 | public float GetZ() 251 | { 252 | return m_z; 253 | } 254 | 255 | public void SetZ(float z) 256 | { 257 | this.m_z = z; 258 | } 259 | 260 | public float GetW() 261 | { 262 | return m_w; 263 | } 264 | 265 | public void SetW(float w) 266 | { 267 | this.m_w = w; 268 | } 269 | 270 | public boolean equals(Quaternion r) 271 | { 272 | return m_x == r.GetX() && m_y == r.GetY() && m_z == r.GetZ() && m_w == r.GetW(); 273 | } 274 | 275 | public static Quaternion fromAssimp(AIQuaternion aiQuaternion) { 276 | return new Quaternion(aiQuaternion.x(), aiQuaternion.y(), aiQuaternion.z(), aiQuaternion.w()); 277 | } 278 | } 279 | -------------------------------------------------------------------------------- /src/com/base/engine/core/Time.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | public class Time 20 | { 21 | private static final long SECOND = 1000000000L; 22 | 23 | public static double GetTime() 24 | { 25 | return (double)System.nanoTime()/(double)SECOND; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/com/base/engine/core/Transform.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | public class Transform 20 | { 21 | private Transform m_parent; 22 | private Matrix4f m_parentMatrix; 23 | 24 | private Vector3f m_pos; 25 | private Quaternion m_rot; 26 | private Vector3f m_scale; 27 | 28 | private Vector3f m_oldPos; 29 | private Quaternion m_oldRot; 30 | private Vector3f m_oldScale; 31 | 32 | public Transform() 33 | { 34 | m_pos = new Vector3f(0,0,0); 35 | m_rot = new Quaternion(0,0,0,1); 36 | m_scale = new Vector3f(1,1,1); 37 | 38 | m_parentMatrix = new Matrix4f().InitIdentity(); 39 | } 40 | 41 | public void Update() 42 | { 43 | if(m_oldPos != null) 44 | { 45 | m_oldPos.Set(m_pos); 46 | m_oldRot.Set(m_rot); 47 | m_oldScale.Set(m_scale); 48 | } 49 | else 50 | { 51 | m_oldPos = new Vector3f(0,0,0).Set(m_pos).Add(1.0f); 52 | m_oldRot = new Quaternion(0,0,0,0).Set(m_rot).Mul(0.5f); 53 | m_oldScale = new Vector3f(0,0,0).Set(m_scale).Add(1.0f); 54 | } 55 | } 56 | 57 | public void Rotate(Vector3f axis, float angle) 58 | { 59 | m_rot = new Quaternion(axis, angle).Mul(m_rot).Normalized(); 60 | } 61 | 62 | public void LookAt(Vector3f point, Vector3f up) 63 | { 64 | m_rot = GetLookAtRotation(point, up); 65 | } 66 | 67 | public Quaternion GetLookAtRotation(Vector3f point, Vector3f up) 68 | { 69 | return new Quaternion(new Matrix4f().InitRotation(point.Sub(m_pos).Normalized(), up)); 70 | } 71 | 72 | public boolean HasChanged() 73 | { 74 | if(m_parent != null && m_parent.HasChanged()) 75 | return true; 76 | 77 | if(!m_pos.equals(m_oldPos)) 78 | return true; 79 | 80 | if(!m_rot.equals(m_oldRot)) 81 | return true; 82 | 83 | if(!m_scale.equals(m_oldScale)) 84 | return true; 85 | 86 | return false; 87 | } 88 | 89 | public Matrix4f GetTransformation() 90 | { 91 | Matrix4f translationMatrix = new Matrix4f().InitTranslation(m_pos.GetX(), m_pos.GetY(), m_pos.GetZ()); 92 | Matrix4f rotationMatrix = m_rot.ToRotationMatrix(); 93 | Matrix4f scaleMatrix = new Matrix4f().InitScale(m_scale.GetX(), m_scale.GetY(), m_scale.GetZ()); 94 | 95 | return GetParentMatrix().Mul(translationMatrix.Mul(rotationMatrix.Mul(scaleMatrix))); 96 | } 97 | 98 | private Matrix4f GetParentMatrix() 99 | { 100 | if(m_parent != null && m_parent.HasChanged()) 101 | m_parentMatrix = m_parent.GetTransformation(); 102 | 103 | return m_parentMatrix; 104 | } 105 | 106 | public void SetParent(Transform parent) 107 | { 108 | this.m_parent = parent; 109 | } 110 | 111 | public Vector3f GetTransformedPos() 112 | { 113 | return GetParentMatrix().Transform(m_pos); 114 | } 115 | 116 | public Quaternion GetTransformedRot() 117 | { 118 | Quaternion parentRotation = new Quaternion(0,0,0,1); 119 | 120 | if(m_parent != null) 121 | parentRotation = m_parent.GetTransformedRot(); 122 | 123 | return parentRotation.Mul(m_rot); 124 | } 125 | 126 | public Vector3f GetPos() 127 | { 128 | return m_pos; 129 | } 130 | 131 | public void SetPos(Vector3f pos) 132 | { 133 | this.m_pos = pos; 134 | } 135 | 136 | public Quaternion GetRot() 137 | { 138 | return m_rot; 139 | } 140 | 141 | public void SetRot(Quaternion rotation) 142 | { 143 | this.m_rot = rotation; 144 | } 145 | 146 | public Vector3f GetScale() 147 | { 148 | return m_scale; 149 | } 150 | 151 | public void SetScale(Vector3f scale) 152 | { 153 | this.m_scale = scale; 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /src/com/base/engine/core/Util.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | import java.nio.ByteBuffer; 20 | import java.nio.FloatBuffer; 21 | import java.nio.IntBuffer; 22 | import java.util.ArrayList; 23 | 24 | import com.base.engine.rendering.Vertex; 25 | import org.lwjgl.BufferUtils; 26 | 27 | public class Util 28 | { 29 | public static FloatBuffer CreateFloatBuffer(int size) 30 | { 31 | return BufferUtils.createFloatBuffer(size); 32 | } 33 | 34 | public static IntBuffer CreateIntBuffer(int size) 35 | { 36 | return BufferUtils.createIntBuffer(size); 37 | } 38 | 39 | public static ByteBuffer CreateByteBuffer(int size) 40 | { 41 | return BufferUtils.createByteBuffer(size); 42 | } 43 | 44 | public static IntBuffer CreateFlippedBuffer(int... values) 45 | { 46 | IntBuffer buffer = CreateIntBuffer(values.length); 47 | buffer.put(values); 48 | buffer.flip(); 49 | 50 | return buffer; 51 | } 52 | 53 | public static FloatBuffer CreateFlippedBuffer(Vertex[] vertices) 54 | { 55 | FloatBuffer buffer = CreateFloatBuffer(vertices.length * Vertex.SIZE); 56 | 57 | for(int i = 0; i < vertices.length; i++) 58 | { 59 | buffer.put(vertices[i].GetPos().GetX()); 60 | buffer.put(vertices[i].GetPos().GetY()); 61 | buffer.put(vertices[i].GetPos().GetZ()); 62 | buffer.put(vertices[i].GetTexCoord().GetX()); 63 | buffer.put(vertices[i].GetTexCoord().GetY()); 64 | buffer.put(vertices[i].GetNormal().GetX()); 65 | buffer.put(vertices[i].GetNormal().GetY()); 66 | buffer.put(vertices[i].GetNormal().GetZ()); 67 | buffer.put(vertices[i].GetTangent().GetX()); 68 | buffer.put(vertices[i].GetTangent().GetY()); 69 | buffer.put(vertices[i].GetTangent().GetZ()); 70 | } 71 | 72 | buffer.flip(); 73 | 74 | return buffer; 75 | } 76 | 77 | public static FloatBuffer CreateFlippedBuffer(Matrix4f value) 78 | { 79 | FloatBuffer buffer = CreateFloatBuffer(4 * 4); 80 | 81 | for(int i = 0; i < 4; i++) 82 | for(int j = 0; j < 4; j++) 83 | buffer.put(value.Get(i, j)); 84 | 85 | buffer.flip(); 86 | 87 | return buffer; 88 | } 89 | 90 | public static String[] RemoveEmptyStrings(String[] data) 91 | { 92 | ArrayList result = new ArrayList(); 93 | 94 | for(int i = 0; i < data.length; i++) 95 | if(!data[i].equals("")) 96 | result.add(data[i]); 97 | 98 | String[] res = new String[result.size()]; 99 | result.toArray(res); 100 | 101 | return res; 102 | } 103 | 104 | public static int[] ToIntArray(Integer[] data) 105 | { 106 | int[] result = new int[data.length]; 107 | 108 | for(int i = 0; i < data.length; i++) 109 | result[i] = data[i].intValue(); 110 | 111 | return result; 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/com/base/engine/core/Vector2f.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | public class Vector2f 20 | { 21 | private float m_x; 22 | private float m_y; 23 | 24 | public Vector2f(float x, float y) 25 | { 26 | this.m_x = x; 27 | this.m_y = y; 28 | } 29 | 30 | public float Length() 31 | { 32 | return (float)Math.sqrt(m_x * m_x + m_y * m_y); 33 | } 34 | 35 | public float Max() 36 | { 37 | return Math.max(m_x, m_y); 38 | } 39 | 40 | public float Dot(Vector2f r) 41 | { 42 | return m_x * r.GetX() + m_y * r.GetY(); 43 | } 44 | 45 | public Vector2f Normalized() 46 | { 47 | float length = Length(); 48 | 49 | return new Vector2f(m_x / length, m_y / length); 50 | } 51 | 52 | public float Cross(Vector2f r) 53 | { 54 | return m_x * r.GetY() - m_y * r.GetX(); 55 | } 56 | 57 | public Vector2f Lerp(Vector2f dest, float lerpFactor) 58 | { 59 | return dest.Sub(this).Mul(lerpFactor).Add(this); 60 | } 61 | 62 | public Vector2f Rotate(float angle) 63 | { 64 | double rad = Math.toRadians(angle); 65 | double cos = Math.cos(rad); 66 | double sin = Math.sin(rad); 67 | 68 | return new Vector2f((float)(m_x * cos - m_y * sin),(float)(m_x * sin + m_y * cos)); 69 | } 70 | 71 | public Vector2f Add(Vector2f r) 72 | { 73 | return new Vector2f(m_x + r.GetX(), m_y + r.GetY()); 74 | } 75 | 76 | public Vector2f Add(float r) 77 | { 78 | return new Vector2f(m_x + r, m_y + r); 79 | } 80 | 81 | public Vector2f Sub(Vector2f r) 82 | { 83 | return new Vector2f(m_x - r.GetX(), m_y - r.GetY()); 84 | } 85 | 86 | public Vector2f Sub(float r) 87 | { 88 | return new Vector2f(m_x - r, m_y - r); 89 | } 90 | 91 | public Vector2f Mul(Vector2f r) 92 | { 93 | return new Vector2f(m_x * r.GetX(), m_y * r.GetY()); 94 | } 95 | 96 | public Vector2f Mul(float r) 97 | { 98 | return new Vector2f(m_x * r, m_y * r); 99 | } 100 | 101 | public Vector2f Div(Vector2f r) 102 | { 103 | return new Vector2f(m_x / r.GetX(), m_y / r.GetY()); 104 | } 105 | 106 | public Vector2f Div(float r) 107 | { 108 | return new Vector2f(m_x / r, m_y / r); 109 | } 110 | 111 | public Vector2f Abs() 112 | { 113 | return new Vector2f(Math.abs(m_x), Math.abs(m_y)); 114 | } 115 | 116 | public String toString() 117 | { 118 | return "(" + m_x + " " + m_y + ")"; 119 | } 120 | 121 | public Vector2f Set(float x, float y) { this.m_x = x; this.m_y = y; return this; } 122 | public Vector2f Set(Vector2f r) { Set(r.GetX(), r.GetY()); return this; } 123 | 124 | public float GetX() 125 | { 126 | return m_x; 127 | } 128 | 129 | public void SetX(float x) 130 | { 131 | this.m_x = x; 132 | } 133 | 134 | public float GetY() 135 | { 136 | return m_y; 137 | } 138 | 139 | public void SetY(float y) 140 | { 141 | this.m_y = y; 142 | } 143 | 144 | public boolean equals(Vector2f r) 145 | { 146 | return m_x == r.GetX() && m_y == r.GetY(); 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /src/com/base/engine/core/Vector3f.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.core; 18 | 19 | import org.lwjgl.assimp.AIVector3D; 20 | 21 | public class Vector3f 22 | { 23 | private float m_x; 24 | private float m_y; 25 | private float m_z; 26 | 27 | public Vector3f(float x, float y, float z) 28 | { 29 | this.m_x = x; 30 | this.m_y = y; 31 | this.m_z = z; 32 | } 33 | 34 | public float Length() 35 | { 36 | return (float)Math.sqrt(m_x * m_x + m_y * m_y + m_z * m_z); 37 | } 38 | 39 | public float Max() 40 | { 41 | return Math.max(m_x, Math.max(m_y, m_z)); 42 | } 43 | 44 | public float Dot(Vector3f r) 45 | { 46 | return m_x * r.GetX() + m_y * r.GetY() + m_z * r.GetZ(); 47 | } 48 | 49 | public Vector3f Cross(Vector3f r) 50 | { 51 | float x_ = m_y * r.GetZ() - m_z * r.GetY(); 52 | float y_ = m_z * r.GetX() - m_x * r.GetZ(); 53 | float z_ = m_x * r.GetY() - m_y * r.GetX(); 54 | 55 | return new Vector3f(x_, y_, z_); 56 | } 57 | 58 | public Vector3f Normalized() 59 | { 60 | float length = Length(); 61 | 62 | return new Vector3f(m_x / length, m_y / length, m_z / length); 63 | } 64 | 65 | public Vector3f Rotate(Vector3f axis, float angle) 66 | { 67 | float sinAngle = (float)Math.sin(-angle); 68 | float cosAngle = (float)Math.cos(-angle); 69 | 70 | return this.Cross(axis.Mul(sinAngle)).Add( //Rotation on local X 71 | (this.Mul(cosAngle)).Add( //Rotation on local Z 72 | axis.Mul(this.Dot(axis.Mul(1 - cosAngle))))); //Rotation on local Y 73 | } 74 | 75 | public Vector3f Rotate(Quaternion rotation) 76 | { 77 | Quaternion conjugate = rotation.Conjugate(); 78 | 79 | Quaternion w = rotation.Mul(this).Mul(conjugate); 80 | 81 | return new Vector3f(w.GetX(), w.GetY(), w.GetZ()); 82 | } 83 | 84 | public Vector3f Lerp(Vector3f dest, float lerpFactor) 85 | { 86 | return dest.Sub(this).Mul(lerpFactor).Add(this); 87 | } 88 | 89 | public Vector3f Add(Vector3f r) 90 | { 91 | return new Vector3f(m_x + r.GetX(), m_y + r.GetY(), m_z + r.GetZ()); 92 | } 93 | 94 | public Vector3f Add(float r) 95 | { 96 | return new Vector3f(m_x + r, m_y + r, m_z + r); 97 | } 98 | 99 | public Vector3f Sub(Vector3f r) 100 | { 101 | return new Vector3f(m_x - r.GetX(), m_y - r.GetY(), m_z - r.GetZ()); 102 | } 103 | 104 | public Vector3f Sub(float r) 105 | { 106 | return new Vector3f(m_x - r, m_y - r, m_z - r); 107 | } 108 | 109 | public Vector3f Mul(Vector3f r) 110 | { 111 | return new Vector3f(m_x * r.GetX(), m_y * r.GetY(), m_z * r.GetZ()); 112 | } 113 | 114 | public Vector3f Mul(float r) 115 | { 116 | return new Vector3f(m_x * r, m_y * r, m_z * r); 117 | } 118 | 119 | public Vector3f Div(Vector3f r) 120 | { 121 | return new Vector3f(m_x / r.GetX(), m_y / r.GetY(), m_z / r.GetZ()); 122 | } 123 | 124 | public Vector3f Div(float r) 125 | { 126 | return new Vector3f(m_x / r, m_y / r, m_z / r); 127 | } 128 | 129 | public Vector3f Abs() 130 | { 131 | return new Vector3f(Math.abs(m_x), Math.abs(m_y), Math.abs(m_z)); 132 | } 133 | 134 | public String toString() 135 | { 136 | return "(" + m_x + " " + m_y + " " + m_z + ")"; 137 | } 138 | 139 | public Vector2f GetXY() { return new Vector2f(m_x, m_y); } 140 | public Vector2f GetYZ() { return new Vector2f(m_y, m_z); } 141 | public Vector2f GetZX() { return new Vector2f(m_z, m_x); } 142 | 143 | public Vector2f GetYX() { return new Vector2f(m_y, m_x); } 144 | public Vector2f GetZY() { return new Vector2f(m_z, m_y); } 145 | public Vector2f GetXZ() { return new Vector2f(m_x, m_z); } 146 | 147 | public Vector3f Set(float x, float y, float z) { this.m_x = x; this.m_y = y; this.m_z = z; return this; } 148 | public Vector3f Set(Vector3f r) { Set(r.GetX(), r.GetY(), r.GetZ()); return this; } 149 | 150 | public float GetX() 151 | { 152 | return m_x; 153 | } 154 | 155 | public void SetX(float x) 156 | { 157 | this.m_x = x; 158 | } 159 | 160 | public float GetY() 161 | { 162 | return m_y; 163 | } 164 | 165 | public void SetY(float y) 166 | { 167 | this.m_y = y; 168 | } 169 | 170 | public float GetZ() 171 | { 172 | return m_z; 173 | } 174 | 175 | public void SetZ(float z) 176 | { 177 | this.m_z = z; 178 | } 179 | 180 | public float x() 181 | { 182 | return m_x; 183 | } 184 | 185 | public float y() 186 | { 187 | return m_y; 188 | } 189 | 190 | public float z() 191 | { 192 | return m_z; 193 | } 194 | 195 | public boolean equals(Vector3f r) 196 | { 197 | return m_x == r.GetX() && m_y == r.GetY() && m_z == r.GetZ(); 198 | } 199 | 200 | public static Vector3f fromAssimp(AIVector3D aiVector3D) { 201 | return new Vector3f(aiVector3D.x(), aiVector3D.y(), aiVector3D.z()); 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/Attenuation.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering; 18 | 19 | import com.base.engine.core.Vector3f; 20 | 21 | public class Attenuation extends Vector3f 22 | { 23 | public Attenuation(float constant, float linear, float exponent) { 24 | super(constant, linear, exponent); 25 | } 26 | 27 | public float GetConstant() 28 | { 29 | return GetX(); 30 | } 31 | 32 | public float GetLinear() 33 | { 34 | return GetY(); 35 | } 36 | 37 | public float GetExponent() 38 | { 39 | return GetZ(); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/Material.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering; 18 | 19 | import com.base.engine.rendering.resourceManagement.MappedValues; 20 | 21 | import java.util.HashMap; 22 | 23 | public class Material extends MappedValues 24 | { 25 | private HashMap m_textureHashMap; 26 | 27 | public Material(Texture diffuse, float specularIntensity, float specularPower, Texture normal, 28 | Texture dispMap, float dispMapScale, float dispMapOffset) 29 | { 30 | super(); 31 | m_textureHashMap = new HashMap(); 32 | AddTexture("diffuse", diffuse); 33 | AddFloat("specularIntensity", specularIntensity); 34 | AddFloat("specularPower", specularPower); 35 | AddTexture("normalMap", normal); 36 | AddTexture("dispMap", dispMap); 37 | 38 | float baseBias = dispMapScale/2.0f; 39 | AddFloat("dispMapScale", dispMapScale); 40 | AddFloat("dispMapBias", -baseBias + baseBias * dispMapOffset); 41 | } 42 | 43 | public void AddTexture(String name, Texture texture) { m_textureHashMap.put(name, texture); } 44 | 45 | public Texture GetTexture(String name) 46 | { 47 | Texture result = m_textureHashMap.get(name); 48 | if(result != null) 49 | return result; 50 | 51 | return new Texture("test.png"); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/Mesh.java: -------------------------------------------------------------------------------- 1 | package com.base.engine.rendering; 2 | 3 | import static org.lwjgl.opengl.GL11.*; 4 | import static org.lwjgl.opengl.GL15.*; 5 | import static org.lwjgl.opengl.GL20.*; 6 | 7 | import java.util.ArrayList; 8 | import java.util.HashMap; 9 | 10 | import com.base.engine.core.Util; 11 | import com.base.engine.core.Vector3f; 12 | import com.base.engine.rendering.meshLoading.IndexedModel; 13 | import com.base.engine.rendering.meshLoading.OBJModel; 14 | import com.base.engine.rendering.resourceManagement.MeshResource; 15 | 16 | public class Mesh 17 | { 18 | private static HashMap s_loadedModels = new HashMap(); 19 | private MeshResource m_resource; 20 | private String m_fileName; 21 | 22 | public Mesh(String fileName) 23 | { 24 | this.m_fileName = fileName; 25 | MeshResource oldResource = s_loadedModels.get(fileName); 26 | 27 | if(oldResource != null) 28 | { 29 | m_resource = oldResource; 30 | m_resource.AddReference(); 31 | } 32 | else 33 | { 34 | LoadMesh(fileName); 35 | s_loadedModels.put(fileName, m_resource); 36 | } 37 | } 38 | 39 | public Mesh(Vertex[] vertices, int[] indices) 40 | { 41 | this(vertices, indices, false); 42 | } 43 | 44 | public Mesh(Vertex[] vertices, int[] indices, boolean calcNormals) 45 | { 46 | m_fileName = ""; 47 | AddVertices(vertices, indices, calcNormals); 48 | } 49 | 50 | @Override 51 | protected void finalize() 52 | { 53 | if(m_resource.RemoveReference() && !m_fileName.isEmpty()) 54 | { 55 | s_loadedModels.remove(m_fileName); 56 | } 57 | } 58 | 59 | private void AddVertices(Vertex[] vertices, int[] indices, boolean calcNormals) 60 | { 61 | if(calcNormals) 62 | { 63 | CalcNormals(vertices, indices); 64 | } 65 | 66 | m_resource = new MeshResource(indices.length); 67 | 68 | glBindBuffer(GL_ARRAY_BUFFER, m_resource.GetVbo()); 69 | glBufferData(GL_ARRAY_BUFFER, Util.CreateFlippedBuffer(vertices), GL_STATIC_DRAW); 70 | 71 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_resource.GetIbo()); 72 | glBufferData(GL_ELEMENT_ARRAY_BUFFER, Util.CreateFlippedBuffer(indices), GL_STATIC_DRAW); 73 | } 74 | 75 | public void Draw() 76 | { 77 | glEnableVertexAttribArray(0); 78 | glEnableVertexAttribArray(1); 79 | glEnableVertexAttribArray(2); 80 | glEnableVertexAttribArray(3); 81 | 82 | glBindBuffer(GL_ARRAY_BUFFER, m_resource.GetVbo()); 83 | glVertexAttribPointer(0, 3, GL_FLOAT, false, Vertex.SIZE * 4, 0); 84 | glVertexAttribPointer(1, 2, GL_FLOAT, false, Vertex.SIZE * 4, 12); 85 | glVertexAttribPointer(2, 3, GL_FLOAT, false, Vertex.SIZE * 4, 20); 86 | glVertexAttribPointer(3, 3, GL_FLOAT, false, Vertex.SIZE * 4, 32); 87 | 88 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_resource.GetIbo()); 89 | glDrawElements(GL_TRIANGLES, m_resource.GetSize(), GL_UNSIGNED_INT, 0); 90 | 91 | glDisableVertexAttribArray(0); 92 | glDisableVertexAttribArray(1); 93 | glDisableVertexAttribArray(2); 94 | glDisableVertexAttribArray(3); 95 | } 96 | 97 | private void CalcNormals(Vertex[] vertices, int[] indices) 98 | { 99 | for(int i = 0; i < indices.length; i += 3) 100 | { 101 | int i0 = indices[i]; 102 | int i1 = indices[i + 1]; 103 | int i2 = indices[i + 2]; 104 | 105 | Vector3f v1 = vertices[i1].GetPos().Sub(vertices[i0].GetPos()); 106 | Vector3f v2 = vertices[i2].GetPos().Sub(vertices[i0].GetPos()); 107 | 108 | Vector3f normal = v1.Cross(v2).Normalized(); 109 | 110 | vertices[i0].SetNormal(vertices[i0].GetNormal().Add(normal)); 111 | vertices[i1].SetNormal(vertices[i1].GetNormal().Add(normal)); 112 | vertices[i2].SetNormal(vertices[i2].GetNormal().Add(normal)); 113 | } 114 | 115 | for(int i = 0; i < vertices.length; i++) 116 | vertices[i].SetNormal(vertices[i].GetNormal().Normalized()); 117 | } 118 | 119 | private Mesh LoadMesh(String fileName) 120 | { 121 | String[] splitArray = fileName.split("\\."); 122 | String ext = splitArray[splitArray.length - 1]; 123 | 124 | if(!ext.equals("obj")) 125 | { 126 | System.err.println("Error: '" + ext + "' file format not supported for mesh data."); 127 | new Exception().printStackTrace(); 128 | System.exit(1); 129 | } 130 | 131 | OBJModel test = new OBJModel("./res/models/" + fileName); 132 | IndexedModel model = test.ToIndexedModel(); 133 | 134 | ArrayList vertices = new ArrayList(); 135 | 136 | for(int i = 0; i < model.GetPositions().size(); i++) 137 | { 138 | vertices.add(new Vertex(model.GetPositions().get(i), 139 | model.GetTexCoords().get(i), 140 | model.GetNormals().get(i), 141 | model.GetTangents().get(i))); 142 | } 143 | 144 | Vertex[] vertexData = new Vertex[vertices.size()]; 145 | vertices.toArray(vertexData); 146 | 147 | Integer[] indexData = new Integer[model.GetIndices().size()]; 148 | model.GetIndices().toArray(indexData); 149 | 150 | AddVertices(vertexData, Util.ToIntArray(indexData), false); 151 | 152 | return this; 153 | } 154 | } 155 | 156 | 157 | //private Mesh Mesh(String string) 158 | //{ 159 | // return new Mesh(string); 160 | //// IndexedModel model = LoadMeshData(new File(string)); 161 | //// 162 | //// ArrayList vertices = new ArrayList(); 163 | //// 164 | //// for(int i = 0; i < model.GetPositions().size(); i++) 165 | //// { 166 | //// vertices.add(new Vertex(model.GetPositions().get(i), 167 | //// model.GetTexCoords().get(i), 168 | //// model.GetNormals().get(i), 169 | //// model.GetTangents().get(i))); 170 | //// } 171 | //// 172 | //// Vertex[] vertexData = new Vertex[vertices.size()]; 173 | //// vertices.toArray(vertexData); 174 | //// 175 | //// Integer[] indexData = new Integer[model.GetIndices().size()]; 176 | //// model.GetIndices().toArray(indexData); 177 | // 178 | //// return new Mesh(Util.CreateFlippedBuffer(vertexData), Util.CreateFlippedBuffer(Util.ToIntArray(indexData))); 179 | //} 180 | 181 | //public ByteBuffer loadTexture(String fileName) throws IOException 182 | //{ 183 | // File file = new File(fileName); 184 | // 185 | // FileInputStream fileInputStream = new FileInputStream(file); 186 | // int byteLength=(int) file.length(); //bytecount of the file-content 187 | // byte[] filecontent = new byte[byteLength]; 188 | // fileInputStream.read(filecontent,0,byteLength); 189 | // 190 | // return (ByteBuffer) Util.CreateByteBuffer(byteLength).put(filecontent).flip(); 191 | //} 192 | // 193 | //private static IndexedModel LoadMeshData(File file) 194 | //{ 195 | // AIScene scene = Assimp.aiImportFile(file.toString(), 196 | // Assimp.aiProcess_Triangulate | 197 | // Assimp.aiProcess_GenSmoothNormals | 198 | // Assimp.aiProcess_FlipUVs | 199 | // Assimp.aiProcess_CalcTangentSpace); 200 | // 201 | // AIMesh mesh = AIMesh.create(scene.mMeshes().get(0)); 202 | // ArrayList vertices = new ArrayList<>(); 203 | // ArrayList normals = new ArrayList<>(); 204 | // ArrayList tangents = new ArrayList<>(); 205 | // ArrayList texcoords = new ArrayList<>(); 206 | // ArrayList indices = new ArrayList<>(); 207 | // for(int v = 0; v < mesh.mNumVertices(); v++) 208 | // { 209 | // AIVector3D pos = mesh.mVertices().get(v); 210 | // AIVector3D nor = mesh.mNormals().get(v); 211 | // if(mesh.mTangents() != null) 212 | // { 213 | // AIVector3D tan = mesh.mTangents().get(v); 214 | // tangents.add(new Vector3f(tan.x(), tan.y(), tan.z())); 215 | // } else tangents.add(new Vector3f(0,0,0)); 216 | // AIVector3D tex = mesh.mTextureCoords(0).get(v); 217 | // 218 | // vertices.add(new Vector3f(pos.x(), pos.y(), pos.z())); 219 | // normals.add(new Vector3f(nor.x(), nor.y(), nor.z())); 220 | // texcoords.add(new Vector2f(tex.x(), tex.y())); 221 | // } 222 | // 223 | // for(int f = 0; f < mesh.mNumFaces(); f++) 224 | // { 225 | // AIFace face = mesh.mFaces().get(f); 226 | //// OBJIndex index = new OBJIndex(); 227 | // for(int IND = 0; IND < face.mNumIndices(); IND++) 228 | // { 229 | // indices.add(face.mIndices().get(IND)); 230 | // } 231 | // } 232 | // 233 | // return (OBJModel.ToIndexedModel(vertices, normals, tangents, texcoords, indices, true, true)); 234 | //} -------------------------------------------------------------------------------- /src/com/base/engine/rendering/RenderingEngine.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering; 18 | 19 | import com.base.engine.components.BaseLight; 20 | import com.base.engine.components.Camera; 21 | import com.base.engine.core.GameObject; 22 | import com.base.engine.core.Transform; 23 | import com.base.engine.core.Vector3f; 24 | import com.base.engine.rendering.resourceManagement.MappedValues; 25 | 26 | import java.util.ArrayList; 27 | import java.util.HashMap; 28 | 29 | import static org.lwjgl.opengl.GL11.*; 30 | import static org.lwjgl.opengl.GL11.GL_VERSION; 31 | 32 | public class RenderingEngine extends MappedValues 33 | { 34 | private HashMap m_samplerMap; 35 | private ArrayList m_lights; 36 | private BaseLight m_activeLight; 37 | 38 | private Shader m_forwardAmbient; 39 | private Camera m_mainCamera; 40 | 41 | public RenderingEngine() 42 | { 43 | super(); 44 | m_lights = new ArrayList(); 45 | m_samplerMap = new HashMap(); 46 | m_samplerMap.put("diffuse", 0); 47 | m_samplerMap.put("normalMap", 1); 48 | m_samplerMap.put("dispMap", 2); 49 | 50 | AddVector3f("ambient", new Vector3f(0.1f, 0.1f, 0.1f)); 51 | 52 | m_forwardAmbient = new Shader("forward-ambient"); 53 | 54 | glClearColor(0.0f, 0.0f, 0.0f, 0.0f); 55 | 56 | glFrontFace(GL_CW); 57 | glCullFace(GL_BACK); 58 | glEnable(GL_CULL_FACE); 59 | glEnable(GL_DEPTH_TEST); 60 | 61 | // 62 | // glEnable(GL_DEPTH_CLAMP); 63 | 64 | glEnable(GL_TEXTURE_2D); 65 | } 66 | 67 | public void UpdateUniformStruct(Transform transform, Material material, Shader shader, String uniformName, String uniformType) 68 | { 69 | throw new IllegalArgumentException(uniformType + " is not a supported type in RenderingEngine"); 70 | } 71 | 72 | public void Render(GameObject object) 73 | { 74 | if (GetMainCamera() == null) System.err.println("Error! Main camera not found. This is very very big bug, and game will crash."); 75 | glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 76 | 77 | object.RenderAll(m_forwardAmbient, this); 78 | 79 | glEnable(GL_BLEND); 80 | glBlendFunc(GL_ONE, GL_ONE); 81 | glDepthMask(false); 82 | glDepthFunc(GL_EQUAL); 83 | 84 | for(BaseLight light : m_lights) 85 | { 86 | m_activeLight = light; 87 | object.RenderAll(light.GetShader(), this); 88 | } 89 | 90 | glDepthFunc(GL_LESS); 91 | glDepthMask(true); 92 | glDisable(GL_BLEND); 93 | } 94 | 95 | public static String GetOpenGLVersion() 96 | { 97 | return glGetString(GL_VERSION); 98 | } 99 | 100 | public void AddLight(BaseLight light) 101 | { 102 | m_lights.add(light); 103 | } 104 | 105 | public void AddCamera(Camera camera) 106 | { 107 | m_mainCamera = camera; 108 | } 109 | 110 | public int GetSamplerSlot(String samplerName) 111 | { 112 | return m_samplerMap.get(samplerName); 113 | } 114 | 115 | public BaseLight GetActiveLight() 116 | { 117 | return m_activeLight; 118 | } 119 | 120 | public Camera GetMainCamera() 121 | { 122 | return m_mainCamera; 123 | } 124 | 125 | public void SetMainCamera(Camera mainCamera) 126 | { 127 | this.m_mainCamera = mainCamera; 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/Shader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering; 18 | 19 | import static org.lwjgl.opengl.GL20.*; 20 | import static org.lwjgl.opengl.GL32.*; 21 | 22 | import java.io.BufferedReader; 23 | import java.io.FileReader; 24 | import java.util.ArrayList; 25 | import java.util.HashMap; 26 | import java.util.regex.Matcher; 27 | import java.util.regex.Pattern; 28 | 29 | import com.base.engine.components.BaseLight; 30 | import com.base.engine.components.DirectionalLight; 31 | import com.base.engine.components.PointLight; 32 | import com.base.engine.components.SpotLight; 33 | import com.base.engine.core.Matrix4f; 34 | import com.base.engine.core.Transform; 35 | import com.base.engine.core.Util; 36 | import com.base.engine.core.Vector3f; 37 | import com.base.engine.rendering.resourceManagement.ShaderResource; 38 | 39 | public class Shader 40 | { 41 | private static HashMap s_loadedShaders = new HashMap(); 42 | 43 | private ShaderResource m_resource; 44 | private String m_fileName; 45 | 46 | protected static Shader instance; 47 | 48 | public static Shader AccessShader() 49 | { 50 | return instance; 51 | } 52 | 53 | public Shader(String fileName) 54 | { 55 | this.m_fileName = fileName; 56 | 57 | ShaderResource oldResource = s_loadedShaders.get(fileName); 58 | 59 | if(oldResource != null) 60 | { 61 | m_resource = oldResource; 62 | m_resource.AddReference(); 63 | } 64 | else 65 | { 66 | m_resource = new ShaderResource(); 67 | 68 | String vertexShaderText = LoadShader(fileName + ".vs"); 69 | String fragmentShaderText = LoadShader(fileName + ".fs"); 70 | 71 | AddVertexShader(vertexShaderText); 72 | AddFragmentShader(fragmentShaderText); 73 | 74 | AddAllAttributes(vertexShaderText); 75 | 76 | CompileShader(); 77 | 78 | AddAllUniforms(vertexShaderText); 79 | AddAllUniforms(fragmentShaderText); 80 | 81 | s_loadedShaders.put(fileName, m_resource); 82 | } 83 | } 84 | 85 | @Override 86 | protected void finalize() 87 | { 88 | if(m_resource.RemoveReference() && !m_fileName.isEmpty()) 89 | { 90 | s_loadedShaders.remove(m_fileName); 91 | } 92 | } 93 | 94 | public void Bind() 95 | { 96 | glUseProgram(m_resource.GetProgram()); 97 | instance = this; 98 | } 99 | 100 | public void UpdateUniforms(Transform transform, Material material, RenderingEngine renderingEngine) 101 | { 102 | Matrix4f worldMatrix = transform.GetTransformation(); 103 | Matrix4f MVPMatrix = renderingEngine.GetMainCamera().GetViewProjection().Mul(worldMatrix); 104 | 105 | for(int i = 0; i < m_resource.GetUniformNames().size(); i++) 106 | { 107 | String uniformName = m_resource.GetUniformNames().get(i); 108 | String uniformType = m_resource.GetUniformTypes().get(i); 109 | 110 | if(uniformType.equals("sampler2D")) 111 | { 112 | int samplerSlot = renderingEngine.GetSamplerSlot(uniformName); 113 | material.GetTexture(uniformName).Bind(samplerSlot); 114 | SetUniformi(uniformName, samplerSlot); 115 | } 116 | else if(uniformName.startsWith("T_")) 117 | { 118 | if(uniformName.equals("T_MVP")) 119 | SetUniform(uniformName, MVPMatrix); 120 | else if(uniformName.equals("T_model")) 121 | SetUniform(uniformName, worldMatrix); 122 | else 123 | throw new IllegalArgumentException(uniformName + " is not a valid component of Transform"); 124 | } 125 | else if(uniformName.startsWith("R_")) 126 | { 127 | String unprefixedUniformName = uniformName.substring(2); 128 | if(uniformType.equals("vec3")) 129 | SetUniform(uniformName, renderingEngine.GetVector3f(unprefixedUniformName)); 130 | else if(uniformType.equals("float")) 131 | SetUniformf(uniformName, renderingEngine.GetFloat(unprefixedUniformName)); 132 | else if(uniformType.equals("DirectionalLight")) 133 | SetUniformDirectionalLight(uniformName, (DirectionalLight) renderingEngine.GetActiveLight()); 134 | else if(uniformType.equals("PointLight")) 135 | SetUniformPointLight(uniformName, (PointLight) renderingEngine.GetActiveLight()); 136 | else if(uniformType.equals("SpotLight")) 137 | SetUniformSpotLight(uniformName, (SpotLight) renderingEngine.GetActiveLight()); 138 | else 139 | renderingEngine.UpdateUniformStruct(transform, material, this, uniformName, uniformType); 140 | } 141 | else if(uniformName.startsWith("C_")) 142 | { 143 | if(uniformName.equals("C_eyePos")) 144 | SetUniform(uniformName, renderingEngine.GetMainCamera().GetTransform().GetTransformedPos()); 145 | else 146 | throw new IllegalArgumentException(uniformName + " is not a valid component of Camera"); 147 | } 148 | else 149 | { 150 | if(uniformType.equals("vec3")) 151 | SetUniform(uniformName, material.GetVector3f(uniformName)); 152 | else if(uniformType.equals("float")) 153 | SetUniformf(uniformName, material.GetFloat(uniformName)); 154 | // else 155 | // throw new IllegalArgumentException(uniformType + " is not a supported type in Material"); 156 | } 157 | } 158 | } 159 | 160 | private void AddAllAttributes(String shaderText) 161 | { 162 | final String ATTRIBUTE_KEYWORD = "attribute"; 163 | int attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD); 164 | int attribNumber = 0; 165 | while(attributeStartLocation != -1) 166 | { 167 | if(!(attributeStartLocation != 0 168 | && (Character.isWhitespace(shaderText.charAt(attributeStartLocation - 1)) || shaderText.charAt(attributeStartLocation - 1) == ';') 169 | && Character.isWhitespace(shaderText.charAt(attributeStartLocation + ATTRIBUTE_KEYWORD.length())))) { 170 | attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD, attributeStartLocation + ATTRIBUTE_KEYWORD.length()); 171 | continue; 172 | 173 | } 174 | 175 | int begin = attributeStartLocation + ATTRIBUTE_KEYWORD.length() + 1; 176 | int end = shaderText.indexOf(";", begin); 177 | 178 | String attributeLine = shaderText.substring(begin, end).trim(); 179 | String attributeName = attributeLine.substring(attributeLine.indexOf(' ') + 1, attributeLine.length()).trim(); 180 | 181 | SetAttribLocation(attributeName, attribNumber); 182 | attribNumber++; 183 | 184 | attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD, attributeStartLocation + ATTRIBUTE_KEYWORD.length()); 185 | } 186 | } 187 | 188 | private class GLSLStruct 189 | { 190 | public String name; 191 | public String type; 192 | } 193 | 194 | private HashMap> FindUniformStructs(String shaderText) 195 | { 196 | HashMap> result = new HashMap>(); 197 | 198 | final String STRUCT_KEYWORD = "struct"; 199 | int structStartLocation = shaderText.indexOf(STRUCT_KEYWORD); 200 | while(structStartLocation != -1) 201 | { 202 | if(!(structStartLocation != 0 203 | && (Character.isWhitespace(shaderText.charAt(structStartLocation - 1)) || shaderText.charAt(structStartLocation - 1) == ';') 204 | && Character.isWhitespace(shaderText.charAt(structStartLocation + STRUCT_KEYWORD.length())))) { 205 | structStartLocation = shaderText.indexOf(STRUCT_KEYWORD, structStartLocation + STRUCT_KEYWORD.length()); 206 | continue; 207 | } 208 | 209 | int nameBegin = structStartLocation + STRUCT_KEYWORD.length() + 1; 210 | int braceBegin = shaderText.indexOf("{", nameBegin); 211 | int braceEnd = shaderText.indexOf("}", braceBegin); 212 | 213 | String structName = shaderText.substring(nameBegin, braceBegin).trim(); 214 | ArrayList glslStructs = new ArrayList(); 215 | 216 | int componentSemicolonPos = shaderText.indexOf(";", braceBegin); 217 | while(componentSemicolonPos != -1 && componentSemicolonPos < braceEnd) 218 | { 219 | int componentNameEnd = componentSemicolonPos + 1; 220 | 221 | while(Character.isWhitespace(shaderText.charAt(componentNameEnd - 1)) || shaderText.charAt(componentNameEnd - 1) == ';') 222 | componentNameEnd--; 223 | 224 | int componentNameStart = componentSemicolonPos; 225 | 226 | while(!Character.isWhitespace(shaderText.charAt(componentNameStart - 1))) 227 | componentNameStart--; 228 | 229 | int componentTypeEnd = componentNameStart; 230 | 231 | while(Character.isWhitespace(shaderText.charAt(componentTypeEnd - 1))) 232 | componentTypeEnd--; 233 | 234 | int componentTypeStart = componentTypeEnd; 235 | 236 | while(!Character.isWhitespace(shaderText.charAt(componentTypeStart - 1))) 237 | componentTypeStart--; 238 | 239 | String componentName = shaderText.substring(componentNameStart, componentNameEnd); 240 | String componentType = shaderText.substring(componentTypeStart, componentTypeEnd); 241 | 242 | GLSLStruct glslStruct = new GLSLStruct(); 243 | glslStruct.name = componentName; 244 | glslStruct.type = componentType; 245 | 246 | glslStructs.add(glslStruct); 247 | 248 | componentSemicolonPos = shaderText.indexOf(";", componentSemicolonPos + 1); 249 | } 250 | 251 | result.put(structName, glslStructs); 252 | 253 | structStartLocation = shaderText.indexOf(STRUCT_KEYWORD, structStartLocation + STRUCT_KEYWORD.length()); 254 | } 255 | 256 | return result; 257 | } 258 | 259 | private void AddAllUniforms(String shaderText) 260 | { 261 | HashMap> structs = FindUniformStructs(shaderText); 262 | 263 | final String UNIFORM_KEYWORD = "uniform"; 264 | int uniformStartLocation = shaderText.indexOf(UNIFORM_KEYWORD); 265 | while(uniformStartLocation != -1) 266 | { 267 | if(!(uniformStartLocation != 0 268 | && (Character.isWhitespace(shaderText.charAt(uniformStartLocation - 1)) || shaderText.charAt(uniformStartLocation - 1) == ';') 269 | && Character.isWhitespace(shaderText.charAt(uniformStartLocation + UNIFORM_KEYWORD.length())))) { 270 | uniformStartLocation = shaderText.indexOf(UNIFORM_KEYWORD, uniformStartLocation + UNIFORM_KEYWORD.length()); 271 | continue; 272 | } 273 | 274 | int begin = uniformStartLocation + UNIFORM_KEYWORD.length() + 1; 275 | int end = shaderText.indexOf(";", begin); 276 | 277 | String uniformLine = shaderText.substring(begin, end).trim(); 278 | 279 | int whiteSpacePos = uniformLine.indexOf(' '); 280 | String uniformName = uniformLine.substring(whiteSpacePos + 1, uniformLine.length()).trim(); 281 | String uniformType = uniformLine.substring(0, whiteSpacePos).trim(); 282 | 283 | m_resource.GetUniformNames().add(uniformName); 284 | m_resource.GetUniformTypes().add(uniformType); 285 | Matcher arrayMatcher = Pattern.compile("\\[\\d+\\]").matcher(uniformName); 286 | if(arrayMatcher.find()) 287 | { 288 | int size = Integer.valueOf(arrayMatcher.group().substring(1, arrayMatcher.group().length() - 1)); 289 | for(int i = 0; i < size; i++) 290 | AddUniform(uniformName.replaceAll("\\[\\d+\\]", "[" + i + "]"), uniformType, structs); 291 | } else 292 | AddUniform(uniformName.replaceAll("\\[\\d+\\]", ""), uniformType, structs); 293 | 294 | uniformStartLocation = shaderText.indexOf(UNIFORM_KEYWORD, uniformStartLocation + UNIFORM_KEYWORD.length()); 295 | } 296 | } 297 | 298 | private void AddUniform(String uniformName, String uniformType, HashMap> structs) 299 | { 300 | boolean addThis = true; 301 | ArrayList structComponents = structs.get(uniformType); 302 | 303 | if(structComponents != null) 304 | { 305 | addThis = false; 306 | for(GLSLStruct struct : structComponents) 307 | { 308 | AddUniform(uniformName + "." + struct.name, struct.type, structs); 309 | } 310 | } 311 | 312 | if(!addThis) 313 | return; 314 | 315 | int uniformLocation = glGetUniformLocation(m_resource.GetProgram(), uniformName); 316 | 317 | if(uniformLocation == 0xFFFFFFFF) 318 | { 319 | System.err.println("Error: Could not find uniform: " + uniformName); 320 | new Exception().printStackTrace(); 321 | System.exit(1); 322 | } 323 | 324 | m_resource.GetUniforms().put(uniformName, uniformLocation); 325 | } 326 | 327 | private void AddVertexShader(String text) 328 | { 329 | AddProgram(text, GL_VERTEX_SHADER); 330 | } 331 | 332 | private void AddGeometryShader(String text) 333 | { 334 | AddProgram(text, GL_GEOMETRY_SHADER); 335 | } 336 | 337 | private void AddFragmentShader(String text) 338 | { 339 | AddProgram(text, GL_FRAGMENT_SHADER); 340 | } 341 | 342 | private void SetAttribLocation(String attributeName, int location) 343 | { 344 | glBindAttribLocation(m_resource.GetProgram(), location, attributeName); 345 | } 346 | 347 | private void CompileShader() 348 | { 349 | glLinkProgram(m_resource.GetProgram()); 350 | 351 | if(glGetProgrami(m_resource.GetProgram(), GL_LINK_STATUS) == 0) 352 | { 353 | System.err.println(glGetProgramInfoLog(m_resource.GetProgram(), 1024)); 354 | System.exit(1); 355 | } 356 | 357 | glValidateProgram(m_resource.GetProgram()); 358 | 359 | if(glGetProgrami(m_resource.GetProgram(), GL_VALIDATE_STATUS) == 0) 360 | { 361 | System.err.println(glGetProgramInfoLog(m_resource.GetProgram(), 1024)); 362 | System.exit(1); 363 | } 364 | } 365 | 366 | private void AddProgram(String text, int type) 367 | { 368 | int shader = glCreateShader(type); 369 | 370 | if(shader == 0) 371 | { 372 | System.err.println("Shader creation failed: Could not find valid memory location when adding shader"); 373 | System.exit(1); 374 | } 375 | 376 | glShaderSource(shader, text); 377 | glCompileShader(shader); 378 | 379 | if(glGetShaderi(shader, GL_COMPILE_STATUS) == 0) 380 | { 381 | System.err.println(glGetShaderInfoLog(shader, 1024)); 382 | System.exit(1); 383 | } 384 | 385 | glAttachShader(m_resource.GetProgram(), shader); 386 | } 387 | 388 | private static String LoadShader(String fileName) 389 | { 390 | StringBuilder shaderSource = new StringBuilder(); 391 | BufferedReader shaderReader = null; 392 | final String INCLUDE_DIRECTIVE = "#include"; 393 | 394 | try 395 | { 396 | shaderReader = new BufferedReader(new FileReader("./res/shaders/" + fileName)); 397 | String line; 398 | 399 | while((line = shaderReader.readLine()) != null) 400 | { 401 | if(line.startsWith(INCLUDE_DIRECTIVE)) 402 | { 403 | shaderSource.append(LoadShader(line.substring(INCLUDE_DIRECTIVE.length() + 2, line.length() - 1))); 404 | } 405 | else 406 | shaderSource.append(line).append("\n"); 407 | } 408 | 409 | shaderReader.close(); 410 | } 411 | catch(Exception e) 412 | { 413 | e.printStackTrace(); 414 | System.exit(1); 415 | } 416 | 417 | 418 | return shaderSource.toString(); 419 | } 420 | 421 | public void SetUniformi(String uniformName, int value) 422 | { 423 | glUniform1i(m_resource.GetUniforms().get(uniformName), value); 424 | } 425 | 426 | public void SetUniformf(String uniformName, float value) 427 | { 428 | glUniform1f(m_resource.GetUniforms().get(uniformName), value); 429 | } 430 | 431 | public void SetUniform(String uniformName, Vector3f value) 432 | { 433 | glUniform3f(m_resource.GetUniforms().get(uniformName), value.GetX(), value.GetY(), value.GetZ()); 434 | } 435 | 436 | public void SetUniform(String uniformName, Matrix4f value) 437 | { 438 | glUniformMatrix4fv(m_resource.GetUniforms().get(uniformName), true, Util.CreateFlippedBuffer(value)); 439 | } 440 | 441 | public void SetUniformBaseLight(String uniformName, BaseLight baseLight) 442 | { 443 | SetUniform(uniformName + ".color", baseLight.GetColor()); 444 | SetUniformf(uniformName + ".intensity", baseLight.GetIntensity()); 445 | } 446 | 447 | public void SetUniformDirectionalLight(String uniformName, DirectionalLight directionalLight) 448 | { 449 | SetUniformBaseLight(uniformName + ".base", directionalLight); 450 | SetUniform(uniformName + ".direction", directionalLight.GetDirection()); 451 | } 452 | 453 | public void SetUniformPointLight(String uniformName, PointLight pointLight) 454 | { 455 | SetUniformBaseLight(uniformName + ".base", pointLight); 456 | SetUniformf(uniformName + ".atten.constant", pointLight.GetAttenuation().GetConstant()); 457 | SetUniformf(uniformName + ".atten.linear", pointLight.GetAttenuation().GetLinear()); 458 | SetUniformf(uniformName + ".atten.exponent", pointLight.GetAttenuation().GetExponent()); 459 | SetUniform(uniformName + ".position", pointLight.GetTransform().GetTransformedPos()); 460 | SetUniformf(uniformName + ".range", pointLight.GetRange()); 461 | } 462 | 463 | public void SetUniformSpotLight(String uniformName, SpotLight spotLight) 464 | { 465 | SetUniformPointLight(uniformName + ".pointLight", spotLight); 466 | SetUniform(uniformName + ".direction", spotLight.GetDirection()); 467 | SetUniformf(uniformName + ".cutoff", spotLight.GetCutoff()); 468 | } 469 | } 470 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/Shader_old.java: -------------------------------------------------------------------------------- 1 | ///* 2 | // * Copyright (C) 2014 Benny Bobaganoosh 3 | // * 4 | // * Licensed under the Apache License, Version 2.0 (the "License"); 5 | // * you may not use this file except in compliance with the License. 6 | // * You may obtain a copy of the License at 7 | // * 8 | // * http://www.apache.org/licenses/LICENSE-2.0 9 | // * 10 | // * Unless required by applicable law or agreed to in writing, software 11 | // * distributed under the License is distributed on an "AS IS" BASIS, 12 | // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // * See the License for the specific language governing permissions and 14 | // * limitations under the License. 15 | // */ 16 | // 17 | //package com.base.engine.rendering; 18 | // 19 | //import com.base.engine.components.BaseLight; 20 | //import com.base.engine.components.DirectionalLight; 21 | //import com.base.engine.components.PointLight; 22 | //import com.base.engine.components.SpotLight; 23 | //import com.base.engine.core.*; 24 | //import com.base.engine.rendering.resourceManagement.ShaderResource; 25 | // 26 | //import static org.lwjgl.opengl.GL20.*; 27 | //import static org.lwjgl.opengl.GL20.glGetUniformLocation; 28 | //import static org.lwjgl.opengl.GL32.*; 29 | // 30 | //import java.io.BufferedReader; 31 | //import java.io.FileReader; 32 | //import java.util.ArrayList; 33 | //import java.util.HashMap; 34 | // 35 | //public class Shader_old 36 | //{ 37 | // private static HashMap s_loadedShaders = new HashMap(); 38 | // 39 | // private ShaderResource m_resource; 40 | // private String m_fileName; 41 | // 42 | // public Shader_old(String fileName) 43 | // { 44 | // this.m_fileName = fileName; 45 | // 46 | // ShaderResource oldResource = s_loadedShaders.get(fileName); 47 | // 48 | // if(oldResource != null) 49 | // { 50 | // m_resource = oldResource; 51 | // m_resource.AddReference(); 52 | // } 53 | // else 54 | // { 55 | // m_resource = new ShaderResource(); 56 | // 57 | // String vertexShaderText = LoadShader(fileName + ".vs"); 58 | // String fragmentShaderText = LoadShader(fileName + ".fs"); 59 | // 60 | // AddVertexShader(vertexShaderText); 61 | // AddFragmentShader(fragmentShaderText); 62 | // 63 | // AddAllAttributes(vertexShaderText); 64 | // 65 | // CompileShader(); 66 | // 67 | // AddAllUniforms(vertexShaderText); 68 | // AddAllUniforms(fragmentShaderText); 69 | // 70 | // s_loadedShaders.put(fileName, m_resource); 71 | // } 72 | // } 73 | // 74 | // @Override 75 | // protected void finalize() 76 | // { 77 | // if(m_resource.RemoveReference() && !m_fileName.isEmpty()) 78 | // { 79 | // s_loadedShaders.remove(m_fileName); 80 | // } 81 | // } 82 | // 83 | // public void Bind() 84 | // { 85 | // glUseProgram(m_resource.GetProgram()); 86 | // } 87 | // 88 | // public void UpdateUniforms(Transform transform, Material material, RenderingEngine renderingEngine) 89 | // { 90 | // Matrix4f worldMatrix = transform.GetTransformation(); 91 | // Matrix4f MVPMatrix = renderingEngine.GetMainCamera().GetViewProjection().Mul(worldMatrix); 92 | // 93 | // for(int i = 0; i < m_resource.GetUniformNames().size(); i++) 94 | // { 95 | // String uniformName = m_resource.GetUniformNames().get(i); 96 | // String uniformType = m_resource.GetUniformTypes().get(i); 97 | // 98 | // if(uniformType.equals("sampler2D")) 99 | // { 100 | // int samplerSlot = renderingEngine.GetSamplerSlot(uniformName); 101 | // material.GetTexture(uniformName).Bind(samplerSlot); 102 | // SetUniformi(uniformName, samplerSlot); 103 | // } 104 | // else if(uniformName.startsWith("T_")) 105 | // { 106 | // if(uniformName.equals("T_MVP")) 107 | // SetUniform(uniformName, MVPMatrix); 108 | // else if(uniformName.equals("T_model")) 109 | // SetUniform(uniformName, worldMatrix); 110 | // else 111 | // throw new IllegalArgumentException(uniformName + " is not a valid component of Transform"); 112 | // } 113 | // else if(uniformName.startsWith("R_")) 114 | // { 115 | // String unprefixedUniformName = uniformName.substring(2); 116 | // if(uniformType.equals("vec3")) 117 | // SetUniform(uniformName, renderingEngine.GetVector3f(unprefixedUniformName)); 118 | // else if(uniformType.equals("float")) 119 | // SetUniformf(uniformName, renderingEngine.GetFloat(unprefixedUniformName)); 120 | // else if(uniformType.equals("DirectionalLight")) 121 | // SetUniformDirectionalLight(uniformName, (DirectionalLight) renderingEngine.GetActiveLight()); 122 | // else if(uniformType.equals("PointLight")) 123 | // SetUniformPointLight(uniformName, (PointLight) renderingEngine.GetActiveLight()); 124 | // else if(uniformType.equals("SpotLight")) 125 | // SetUniformSpotLight(uniformName, (SpotLight) renderingEngine.GetActiveLight()); 126 | // else 127 | // renderingEngine.UpdateUniformStruct(transform, material, this, uniformName, uniformType); 128 | // } 129 | // else if(uniformName.startsWith("C_")) 130 | // { 131 | // if(uniformName.equals("C_eyePos")) 132 | // SetUniform(uniformName, renderingEngine.GetMainCamera().GetTransform().GetTransformedPos()); 133 | // else 134 | // throw new IllegalArgumentException(uniformName + " is not a valid component of Camera"); 135 | // } 136 | // else 137 | // { 138 | // if(uniformType.equals("vec3")) 139 | // SetUniform(uniformName, material.GetVector3f(uniformName)); 140 | // else if(uniformType.equals("float")) 141 | // SetUniformf(uniformName, material.GetFloat(uniformName)); 142 | // else 143 | // throw new IllegalArgumentException(uniformType + " is not a supported type in Material"); 144 | // } 145 | // } 146 | // } 147 | // 148 | // private void AddAllAttributes(String shaderText) 149 | // { 150 | // final String ATTRIBUTE_KEYWORD = "attribute"; 151 | // int attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD); 152 | // int attribNumber = 0; 153 | // while(attributeStartLocation != -1) 154 | // { 155 | // if(!(attributeStartLocation != 0 156 | // && (Character.isWhitespace(shaderText.charAt(attributeStartLocation - 1)) || shaderText.charAt(attributeStartLocation - 1) == ';') 157 | // && Character.isWhitespace(shaderText.charAt(attributeStartLocation + ATTRIBUTE_KEYWORD.length())))) { 158 | // attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD, attributeStartLocation + ATTRIBUTE_KEYWORD.length()); 159 | // continue; 160 | // 161 | // } 162 | // 163 | // int begin = attributeStartLocation + ATTRIBUTE_KEYWORD.length() + 1; 164 | // int end = shaderText.indexOf(";", begin); 165 | // 166 | // String attributeLine = shaderText.substring(begin, end).trim(); 167 | // String attributeName = attributeLine.substring(attributeLine.indexOf(' ') + 1, attributeLine.length()).trim(); 168 | // 169 | // SetAttribLocation(attributeName, attribNumber); 170 | // attribNumber++; 171 | // 172 | // attributeStartLocation = shaderText.indexOf(ATTRIBUTE_KEYWORD, attributeStartLocation + ATTRIBUTE_KEYWORD.length()); 173 | // } 174 | // } 175 | // 176 | // private class GLSLStruct 177 | // { 178 | // public String name; 179 | // public String type; 180 | // } 181 | // 182 | // private HashMap> FindUniformStructs(String shaderText) 183 | // { 184 | // HashMap> result = new HashMap>(); 185 | // 186 | // final String STRUCT_KEYWORD = "struct"; 187 | // int structStartLocation = shaderText.indexOf(STRUCT_KEYWORD); 188 | // while(structStartLocation != -1) 189 | // { 190 | // if(!(structStartLocation != 0 191 | // && (Character.isWhitespace(shaderText.charAt(structStartLocation - 1)) || shaderText.charAt(structStartLocation - 1) == ';') 192 | // && Character.isWhitespace(shaderText.charAt(structStartLocation + STRUCT_KEYWORD.length())))) { 193 | // structStartLocation = shaderText.indexOf(STRUCT_KEYWORD, structStartLocation + STRUCT_KEYWORD.length()); 194 | // continue; 195 | // } 196 | // 197 | // int nameBegin = structStartLocation + STRUCT_KEYWORD.length() + 1; 198 | // int braceBegin = shaderText.indexOf("{", nameBegin); 199 | // int braceEnd = shaderText.indexOf("}", braceBegin); 200 | // 201 | // String structName = shaderText.substring(nameBegin, braceBegin).trim(); 202 | // ArrayList glslStructs = new ArrayList(); 203 | // 204 | // int componentSemicolonPos = shaderText.indexOf(";", braceBegin); 205 | // while(componentSemicolonPos != -1 && componentSemicolonPos < braceEnd) 206 | // { 207 | // int componentNameEnd = componentSemicolonPos + 1; 208 | // 209 | // while(Character.isWhitespace(shaderText.charAt(componentNameEnd - 1)) || shaderText.charAt(componentNameEnd - 1) == ';') 210 | // componentNameEnd--; 211 | // 212 | // int componentNameStart = componentSemicolonPos; 213 | // 214 | // while(!Character.isWhitespace(shaderText.charAt(componentNameStart - 1))) 215 | // componentNameStart--; 216 | // 217 | // int componentTypeEnd = componentNameStart; 218 | // 219 | // while(Character.isWhitespace(shaderText.charAt(componentTypeEnd - 1))) 220 | // componentTypeEnd--; 221 | // 222 | // int componentTypeStart = componentTypeEnd; 223 | // 224 | // while(!Character.isWhitespace(shaderText.charAt(componentTypeStart - 1))) 225 | // componentTypeStart--; 226 | // 227 | // String componentName = shaderText.substring(componentNameStart, componentNameEnd); 228 | // String componentType = shaderText.substring(componentTypeStart, componentTypeEnd); 229 | // 230 | // GLSLStruct glslStruct = new GLSLStruct(); 231 | // glslStruct.name = componentName; 232 | // glslStruct.type = componentType; 233 | // 234 | // glslStructs.add(glslStruct); 235 | // 236 | // componentSemicolonPos = shaderText.indexOf(";", componentSemicolonPos + 1); 237 | // } 238 | // 239 | // result.put(structName, glslStructs); 240 | // 241 | // structStartLocation = shaderText.indexOf(STRUCT_KEYWORD, structStartLocation + STRUCT_KEYWORD.length()); 242 | // } 243 | // 244 | // return result; 245 | // } 246 | // 247 | // private void AddAllUniforms(String shaderText) 248 | // { 249 | // HashMap> structs = FindUniformStructs(shaderText); 250 | // 251 | // final String UNIFORM_KEYWORD = "uniform"; 252 | // int uniformStartLocation = shaderText.indexOf(UNIFORM_KEYWORD); 253 | // while(uniformStartLocation != -1) 254 | // { 255 | // if(!(uniformStartLocation != 0 256 | // && (Character.isWhitespace(shaderText.charAt(uniformStartLocation - 1)) || shaderText.charAt(uniformStartLocation - 1) == ';') 257 | // && Character.isWhitespace(shaderText.charAt(uniformStartLocation + UNIFORM_KEYWORD.length())))) { 258 | // uniformStartLocation = shaderText.indexOf(UNIFORM_KEYWORD, uniformStartLocation + UNIFORM_KEYWORD.length()); 259 | // continue; 260 | // } 261 | // 262 | // int begin = uniformStartLocation + UNIFORM_KEYWORD.length() + 1; 263 | // int end = shaderText.indexOf(";", begin); 264 | // 265 | // String uniformLine = shaderText.substring(begin, end).trim(); 266 | // 267 | // int whiteSpacePos = uniformLine.indexOf(' '); 268 | // String uniformName = uniformLine.substring(whiteSpacePos + 1, uniformLine.length()).trim(); 269 | // String uniformType = uniformLine.substring(0, whiteSpacePos).trim(); 270 | // 271 | // m_resource.GetUniformNames().add(uniformName); 272 | // m_resource.GetUniformTypes().add(uniformType); 273 | // AddUniform(uniformName, uniformType, structs); 274 | // 275 | // uniformStartLocation = shaderText.indexOf(UNIFORM_KEYWORD, uniformStartLocation + UNIFORM_KEYWORD.length()); 276 | // } 277 | // } 278 | // 279 | // private void AddUniform(String uniformName, String uniformType, HashMap> structs) 280 | // { 281 | // boolean addThis = true; 282 | // ArrayList structComponents = structs.get(uniformType); 283 | // 284 | // if(structComponents != null) 285 | // { 286 | // addThis = false; 287 | // for(GLSLStruct struct : structComponents) 288 | // { 289 | // AddUniform(uniformName + "." + struct.name, struct.type, structs); 290 | // } 291 | // } 292 | // 293 | // if(!addThis) 294 | // return; 295 | // 296 | // int uniformLocation = glGetUniformLocation(m_resource.GetProgram(), uniformName); 297 | // 298 | // if(uniformLocation == 0xFFFFFFFF) 299 | // { 300 | // System.err.println("Error: Could not find uniform: " + uniformName); 301 | // new Exception().printStackTrace(); 302 | // System.exit(1); 303 | // } 304 | // 305 | // m_resource.GetUniforms().put(uniformName, uniformLocation); 306 | // } 307 | // 308 | // private void AddVertexShader(String text) 309 | // { 310 | // AddProgram(text, GL_VERTEX_SHADER); 311 | // } 312 | // 313 | // private void AddGeometryShader(String text) 314 | // { 315 | // AddProgram(text, GL_GEOMETRY_SHADER); 316 | // } 317 | // 318 | // private void AddFragmentShader(String text) 319 | // { 320 | // AddProgram(text, GL_FRAGMENT_SHADER); 321 | // } 322 | // 323 | // private void SetAttribLocation(String attributeName, int location) 324 | // { 325 | // glBindAttribLocation(m_resource.GetProgram(), location, attributeName); 326 | // } 327 | // 328 | // private void CompileShader() 329 | // { 330 | // glLinkProgram(m_resource.GetProgram()); 331 | // 332 | // if(glGetProgrami(m_resource.GetProgram(), GL_LINK_STATUS) == 0) 333 | // { 334 | // System.err.println(glGetProgramInfoLog(m_resource.GetProgram(), 1024)); 335 | // System.exit(1); 336 | // } 337 | // 338 | // glValidateProgram(m_resource.GetProgram()); 339 | // 340 | // if(glGetProgrami(m_resource.GetProgram(), GL_VALIDATE_STATUS) == 0) 341 | // { 342 | // System.err.println(glGetProgramInfoLog(m_resource.GetProgram(), 1024)); 343 | // System.exit(1); 344 | // } 345 | // } 346 | // 347 | // private void AddProgram(String text, int type) 348 | // { 349 | // int shader = glCreateShader(type); 350 | // 351 | // if(shader == 0) 352 | // { 353 | // System.err.println("Shader creation failed: Could not find valid memory location when adding shader"); 354 | // System.exit(1); 355 | // } 356 | // 357 | // glShaderSource(shader, text); 358 | // glCompileShader(shader); 359 | // 360 | // if(glGetShaderi(shader, GL_COMPILE_STATUS) == 0) 361 | // { 362 | // System.err.println(glGetShaderInfoLog(shader, 1024)); 363 | // System.exit(1); 364 | // } 365 | // 366 | // glAttachShader(m_resource.GetProgram(), shader); 367 | // } 368 | // 369 | // private static String LoadShader(String fileName) 370 | // { 371 | // StringBuilder shaderSource = new StringBuilder(); 372 | // BufferedReader shaderReader = null; 373 | // final String INCLUDE_DIRECTIVE = "#include"; 374 | // 375 | // try 376 | // { 377 | // shaderReader = new BufferedReader(new FileReader("./res/shaders/" + fileName)); 378 | // String line; 379 | // 380 | // while((line = shaderReader.readLine()) != null) 381 | // { 382 | // if(line.startsWith(INCLUDE_DIRECTIVE)) 383 | // { 384 | // shaderSource.append(LoadShader(line.substring(INCLUDE_DIRECTIVE.length() + 2, line.length() - 1))); 385 | // } 386 | // else 387 | // shaderSource.append(line).append("\n"); 388 | // } 389 | // 390 | // shaderReader.close(); 391 | // } 392 | // catch(Exception e) 393 | // { 394 | // e.printStackTrace(); 395 | // System.exit(1); 396 | // } 397 | // 398 | // 399 | // return shaderSource.toString(); 400 | // } 401 | // 402 | // public void SetUniformi(String uniformName, int value) 403 | // { 404 | // glUniform1i(m_resource.GetUniforms().get(uniformName), value); 405 | // } 406 | // 407 | // public void SetUniformf(String uniformName, float value) 408 | // { 409 | // glUniform1f(m_resource.GetUniforms().get(uniformName), value); 410 | // } 411 | // 412 | // public void SetUniform(String uniformName, Vector3f value) 413 | // { 414 | // glUniform3f(m_resource.GetUniforms().get(uniformName), value.GetX(), value.GetY(), value.GetZ()); 415 | // } 416 | // 417 | // public void SetUniform(String uniformName, Matrix4f value) 418 | // { 419 | // glUniformMatrix4fv(m_resource.GetUniforms().get(uniformName), true, Util.CreateFlippedBuffer(value)); 420 | // } 421 | // 422 | // public void SetUniformBaseLight(String uniformName, BaseLight baseLight) 423 | // { 424 | // SetUniform(uniformName + ".color", baseLight.GetColor()); 425 | // SetUniformf(uniformName + ".intensity", baseLight.GetIntensity()); 426 | // } 427 | // 428 | // public void SetUniformDirectionalLight(String uniformName, DirectionalLight directionalLight) 429 | // { 430 | // SetUniformBaseLight(uniformName + ".base", directionalLight); 431 | // SetUniform(uniformName + ".direction", directionalLight.GetDirection()); 432 | // } 433 | // 434 | // public void SetUniformPointLight(String uniformName, PointLight pointLight) 435 | // { 436 | // SetUniformBaseLight(uniformName + ".base", pointLight); 437 | // SetUniformf(uniformName + ".atten.constant", pointLight.GetAttenuation().GetConstant()); 438 | // SetUniformf(uniformName + ".atten.linear", pointLight.GetAttenuation().GetLinear()); 439 | // SetUniformf(uniformName + ".atten.exponent", pointLight.GetAttenuation().GetExponent()); 440 | // SetUniform(uniformName + ".position", pointLight.GetTransform().GetTransformedPos()); 441 | // SetUniformf(uniformName + ".range", pointLight.GetRange()); 442 | // } 443 | // 444 | // public void SetUniformSpotLight(String uniformName, SpotLight spotLight) 445 | // { 446 | // SetUniformPointLight(uniformName + ".pointLight", spotLight); 447 | // SetUniform(uniformName + ".direction", spotLight.GetDirection()); 448 | // SetUniformf(uniformName + ".cutoff", spotLight.GetCutoff()); 449 | // } 450 | //} 451 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/Texture.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering; 18 | 19 | import static org.lwjgl.opengl.GL11.*; 20 | import static org.lwjgl.opengl.GL13.*; 21 | 22 | import java.awt.image.BufferedImage; 23 | import java.io.File; 24 | import java.nio.ByteBuffer; 25 | import java.util.HashMap; 26 | 27 | import com.base.engine.core.*; 28 | import com.base.engine.rendering.resourceManagement.TextureResource; 29 | 30 | import javax.imageio.ImageIO; 31 | 32 | public class Texture 33 | { 34 | private static HashMap s_loadedTextures = new HashMap(); 35 | private TextureResource m_resource; 36 | private String m_fileName; 37 | 38 | public Texture(String fileName) 39 | { 40 | this.m_fileName = fileName; 41 | TextureResource oldResource = s_loadedTextures.get(fileName); 42 | 43 | if(oldResource != null) 44 | { 45 | m_resource = oldResource; 46 | m_resource.AddReference(); 47 | } 48 | else 49 | { 50 | m_resource = LoadTexture(fileName); 51 | s_loadedTextures.put(fileName, m_resource); 52 | } 53 | } 54 | 55 | @Override 56 | protected void finalize() 57 | { 58 | if(m_resource.RemoveReference() && !m_fileName.isEmpty()) 59 | { 60 | s_loadedTextures.remove(m_fileName); 61 | } 62 | } 63 | 64 | public void Bind() 65 | { 66 | Bind(0); 67 | } 68 | 69 | public void Bind(int samplerSlot) 70 | { 71 | assert(samplerSlot >= 0 && samplerSlot <= 31); 72 | glActiveTexture(GL_TEXTURE0 + samplerSlot); 73 | glBindTexture(GL_TEXTURE_2D, m_resource.GetId()); 74 | } 75 | 76 | public int GetID() 77 | { 78 | return m_resource.GetId(); 79 | } 80 | 81 | private static TextureResource LoadTexture(String fileName) 82 | { 83 | try 84 | { 85 | BufferedImage image = ImageIO.read(new File("./res/textures/" + fileName)); 86 | int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth()); 87 | 88 | ByteBuffer buffer = Util.CreateByteBuffer(image.getHeight() * image.getWidth() * 4); 89 | boolean hasAlpha = image.getColorModel().hasAlpha(); 90 | 91 | for(int y = 0; y < image.getHeight(); y++) 92 | { 93 | for(int x = 0; x < image.getWidth(); x++) 94 | { 95 | int pixel = pixels[y * image.getWidth() + x]; 96 | 97 | buffer.put((byte)((pixel >> 16) & 0xFF)); 98 | buffer.put((byte)((pixel >> 8) & 0xFF)); 99 | buffer.put((byte)((pixel) & 0xFF)); 100 | if(hasAlpha) 101 | buffer.put((byte)((pixel >> 24) & 0xFF)); 102 | else 103 | buffer.put((byte)(0xFF)); 104 | } 105 | } 106 | 107 | buffer.flip(); 108 | 109 | TextureResource resource = new TextureResource(); 110 | glBindTexture(GL_TEXTURE_2D, resource.GetId()); 111 | 112 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 113 | glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 114 | 115 | glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 116 | glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 117 | 118 | glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer); 119 | 120 | return resource; 121 | } 122 | catch(Exception e) 123 | { 124 | e.printStackTrace(); 125 | System.exit(1); 126 | } 127 | 128 | return null; 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/Vertex.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering; 18 | 19 | import com.base.engine.core.Vector2f; 20 | import com.base.engine.core.Vector3f; 21 | 22 | public class Vertex 23 | { 24 | public static final int SIZE = 11; 25 | 26 | private Vector3f m_pos; 27 | private Vector2f m_texCoord; 28 | private Vector3f m_normal; 29 | private Vector3f m_tangent; 30 | 31 | public Vertex(Vector3f pos) 32 | { 33 | this(pos, new Vector2f(0,0)); 34 | } 35 | 36 | public Vertex(Vector3f pos, Vector2f texCoord) 37 | { 38 | this(pos, texCoord, new Vector3f(0,0,0)); 39 | } 40 | 41 | public Vertex(Vector3f pos, Vector2f texCoord, Vector3f normal) 42 | { 43 | this(pos, texCoord, normal, new Vector3f(0,0,0)); 44 | } 45 | 46 | public Vertex(Vector3f pos, Vector2f texCoord, Vector3f normal, Vector3f tangent) 47 | { 48 | this.m_pos = pos; 49 | this.m_texCoord = texCoord; 50 | this.m_normal = normal; 51 | this.m_tangent = tangent; 52 | } 53 | 54 | public Vector3f GetTangent() { 55 | return m_tangent; 56 | } 57 | 58 | public void SetTangent(Vector3f tangent) { 59 | this.m_tangent = tangent; 60 | } 61 | 62 | public Vector3f GetPos() 63 | { 64 | return m_pos; 65 | } 66 | 67 | public void SetPos(Vector3f pos) 68 | { 69 | this.m_pos = pos; 70 | } 71 | 72 | public Vector2f GetTexCoord() 73 | { 74 | return m_texCoord; 75 | } 76 | 77 | public void SetTexCoord(Vector2f texCoord) 78 | { 79 | this.m_texCoord = texCoord; 80 | } 81 | 82 | public Vector3f GetNormal() 83 | { 84 | return m_normal; 85 | } 86 | 87 | public void SetNormal(Vector3f normal) 88 | { 89 | this.m_normal = normal; 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/Window.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering; 18 | 19 | import static org.lwjgl.glfw.GLFW.*; 20 | import static org.lwjgl.opengl.GL11.*; 21 | import static org.lwjgl.opengl.GL30.*; 22 | import static org.lwjgl.system.MemoryUtil.*; 23 | 24 | import java.nio.IntBuffer; 25 | import java.util.ArrayList; 26 | 27 | import org.lwjgl.BufferUtils; 28 | import org.lwjgl.glfw.GLFWCursorPosCallback; 29 | import org.lwjgl.glfw.GLFWDropCallback; 30 | import org.lwjgl.glfw.GLFWDropCallbackI; 31 | import org.lwjgl.glfw.GLFWErrorCallback; 32 | import org.lwjgl.glfw.GLFWScrollCallback; 33 | import org.lwjgl.glfw.GLFWVidMode; 34 | import org.lwjgl.glfw.GLFWWindowSizeCallback; 35 | import org.lwjgl.opengl.GL; 36 | import org.lwjgl.opengl.GL30; 37 | 38 | import com.base.engine.core.Vector2f; 39 | 40 | public class Window 41 | { 42 | private static final ArrayList s_behaviours = new ArrayList<>(); 43 | private static final Window window = new Window(); 44 | public static int BOUND_FBO_ID = 0; 45 | public static int BOUND_FBO_TYPE = 0; 46 | public static int BOUND_TEX_ID = 0; 47 | public static int BOUND_TEX_TYPE = 0; 48 | public static int BOUND_TEX_VX = 0; 49 | public static int BOUND_TEX_VY = 0; 50 | public static int BOUND_TEX_VW = 0; 51 | public static int BOUND_TEX_VH = 0; 52 | public static int WIDTH = 0; 53 | public static int HEIGHT = 0; 54 | protected static long m_window; 55 | protected static GLFWErrorCallback m_errorCallback; 56 | protected static GLFWDropCallbackI m_dropCallBackI; 57 | protected static GLFWDropCallback m_dropCallBack; 58 | protected static GLFWWindowSizeCallback m_resizeCallBack; 59 | public static Mouse Mouse; 60 | 61 | public static void CreateWindow(int width, int height, String title) 62 | { 63 | try 64 | { 65 | if(!glfwInit()) throw new Exception("GLFW Initialization failed."); 66 | glfwSetErrorCallback(m_errorCallback = GLFWErrorCallback.createPrint(System.err)); 67 | glfwDefaultWindowHints(); 68 | glfwWindowHint(GLFW_VISIBLE, GL_FALSE); 69 | glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); 70 | glfwWindowHint(GLFW_REFRESH_RATE , GLFW_DONT_CARE); 71 | glfwWindowHint(GLFW_DOUBLEBUFFER , GL_TRUE); 72 | Window.WIDTH = width; 73 | Window.HEIGHT = height; 74 | m_window = glfwCreateWindow(width, height, title, NULL, NULL); 75 | if(m_window == 0) throw new Exception("GLFW Window creation failed."); 76 | GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); 77 | // Center our window 78 | glfwSetWindowPos( 79 | m_window, 80 | (vidmode.width() - WIDTH) / 2, 81 | (vidmode.height() - HEIGHT) / 2 82 | ); 83 | 84 | Mouse = window.new Mouse(); 85 | Mouse.Create(m_window); 86 | 87 | glfwSetWindowSizeCallback(m_window, m_resizeCallBack = new GLFWWindowSizeCallback() 88 | { 89 | @Override 90 | public void invoke(long arg0, int arg1, int arg2) 91 | { 92 | Window.WIDTH = arg1; 93 | Window.HEIGHT = arg2; 94 | } 95 | }); 96 | glfwMakeContextCurrent(m_window); 97 | glfwSwapInterval(0); 98 | glfwShowWindow(m_window); 99 | GL.createCapabilities(); 100 | int vao = GL30.glGenVertexArrays (); 101 | GL30.glBindVertexArray (vao); 102 | } 103 | catch (Exception e) 104 | { 105 | e.printStackTrace(); 106 | System.exit(0); 107 | } 108 | } 109 | 110 | public static void BindAsRenderTarget() 111 | { 112 | BindAsRenderTarget(GL_TEXTURE_2D, 0, GL_FRAMEBUFFER, 0, 0, 0, GetWidth(), GetHeight()); 113 | } 114 | 115 | public static void BindAsRenderTarget(int viewPortX, 116 | int viewPortY, int width, int height) 117 | { 118 | BindAsRenderTarget(GL_TEXTURE_2D, 0, GL_FRAMEBUFFER, 0, viewPortX, viewPortY, width, height); 119 | } 120 | 121 | public static void BindAsRenderTarget(int frameBufferType, int fboId, int viewPortX, int viewPortY, int width, 122 | int height) 123 | { 124 | glViewport(viewPortX, viewPortY, width, height); 125 | glBindFramebuffer(frameBufferType, fboId); 126 | BOUND_FBO_ID = fboId; 127 | BOUND_FBO_TYPE = frameBufferType; 128 | 129 | BOUND_TEX_VX = viewPortX; 130 | BOUND_TEX_VY = viewPortY; 131 | BOUND_TEX_VW = width; 132 | BOUND_TEX_VH = height; 133 | } 134 | 135 | public static void BindAsRenderTarget(int texTureType, int id, int frameBufferType, int fboId, int viewPortX, 136 | int viewPortY, int width, int height) 137 | { 138 | glBindTexture(texTureType, id); 139 | BindAsRenderTarget(frameBufferType, fboId, viewPortX, viewPortY, width, height); 140 | BOUND_TEX_ID = id; 141 | BOUND_TEX_TYPE = texTureType; 142 | } 143 | 144 | public static void BindLastAsRenderTarget(WindowRenderTargetInfo info) 145 | { 146 | BindAsRenderTarget(info.BOUND_FBO_TYPE, info.BOUND_FBO_ID, info.BOUND_TEX_VX, info.BOUND_TEX_VY, info.BOUND_TEX_VW, info.BOUND_TEX_VH); 147 | } 148 | 149 | public static WindowRenderTargetInfo SaveLastRenderTarget() 150 | { 151 | WindowRenderTargetInfo info = new WindowRenderTargetInfo(); 152 | info.BOUND_FBO_ID = BOUND_FBO_ID; 153 | info.BOUND_FBO_TYPE = BOUND_FBO_TYPE; 154 | info.BOUND_TEX_ID = BOUND_TEX_ID; 155 | info.BOUND_TEX_TYPE = BOUND_TEX_TYPE; 156 | info.BOUND_TEX_VX = BOUND_TEX_VX; 157 | info.BOUND_TEX_VY = BOUND_TEX_VY; 158 | info.BOUND_TEX_VW = BOUND_TEX_VW; 159 | info.BOUND_TEX_VH = BOUND_TEX_VH; 160 | return info; 161 | } 162 | 163 | public static class WindowRenderTargetInfo 164 | { 165 | public int BOUND_FBO_ID = 0; 166 | public int BOUND_FBO_TYPE = 0; 167 | public int BOUND_TEX_ID = 0; 168 | public int BOUND_TEX_TYPE = 0; 169 | public int BOUND_TEX_VX = 0; 170 | public int BOUND_TEX_VY = 0; 171 | public int BOUND_TEX_VW = 0; 172 | public int BOUND_TEX_VH = 0; 173 | } 174 | 175 | public static void Update() 176 | { 177 | glfwPollEvents(); 178 | } 179 | 180 | public static void Render() 181 | { 182 | // Display.update(); 183 | glfwSwapBuffers(m_window); 184 | // glfwPollEvents(); 185 | } 186 | 187 | public static void Dispose() 188 | { 189 | glfwDestroyWindow(m_window); 190 | // Display.destroy(); 191 | // Keyboard.destroy(); 192 | // Mouse.destroy(); 193 | } 194 | 195 | public static boolean IsCloseRequested() 196 | { 197 | return glfwWindowShouldClose(m_window);//Display.isCloseRequested(); 198 | } 199 | 200 | public static void SetCloseRequested(boolean value) 201 | { 202 | glfwSetWindowShouldClose(m_window, value); 203 | } 204 | 205 | public static void SetTitle(String title) 206 | { 207 | glfwSetWindowTitle(m_window, title); 208 | } 209 | 210 | static final IntBuffer w = BufferUtils.createIntBuffer(1); 211 | static final IntBuffer h = BufferUtils.createIntBuffer(1); 212 | 213 | public static int GetWidth() 214 | { 215 | glfwGetWindowSize(m_window, w, h); 216 | WIDTH = w.get(0); 217 | HEIGHT = h.get(0); 218 | return w.get(0);//Display.getDisplayMode().getWidth(); 219 | } 220 | 221 | public static int GetHeight() 222 | { 223 | glfwGetWindowSize(m_window, w, h); 224 | WIDTH = w.get(0); 225 | HEIGHT = h.get(0); 226 | return h.get(0);//Display.getDisplayMode().getHeight(); 227 | } 228 | 229 | public static float Aspect() 230 | { 231 | return (float)GetWidth() / (float)GetHeight(); 232 | } 233 | 234 | // public static String GetTitle() 235 | // { 236 | // return glfwgetwindow//Display.getTitle(); 237 | // } 238 | 239 | public Vector2f GetCenter() 240 | { 241 | return new Vector2f(GetWidth()/2, GetHeight()/2); 242 | } 243 | 244 | public static long CurrentWindow() 245 | { 246 | return m_window; 247 | } 248 | 249 | public class Mouse 250 | { 251 | public GLFWCursorPosCallback callback; 252 | public GLFWScrollCallback scallback; 253 | public double x; 254 | public double y; 255 | // 256 | public double dx; 257 | public double dy; 258 | 259 | public double wheel; 260 | 261 | // double[] x; 262 | // double[] y; 263 | // Vector2f MousePos; 264 | 265 | public void Create(long window) 266 | { 267 | // MousePos = new Vector2f(0, 0); 268 | // x = new double[1]; 269 | // y = new double[1]; 270 | // glfwGetCursorPos(CurrentWindow(), x, y); 271 | // MousePos.Set((float)x[0], (float)y[0]); 272 | glfwSetCursorPosCallback(window, callback = new GLFWCursorPosCallback(){ 273 | 274 | @Override 275 | public void invoke(long window, double xpos, double ypos) { 276 | // Add delta of x and y mouse coordinates 277 | dx += (int)xpos - x; 278 | dy += (int)xpos - y; 279 | // Set new positions of x and y 280 | x = (int) xpos; 281 | y = (int) ypos; 282 | } 283 | }); 284 | glfwSetScrollCallback(m_window, scallback = new GLFWScrollCallback() { 285 | 286 | @Override 287 | public void invoke(long arg0, double arg1, double arg2) 288 | { 289 | wheel += arg2; 290 | } 291 | }); 292 | } 293 | 294 | public void Update() 295 | { 296 | double xx[] = new double[1]; 297 | double yy[] = new double[1]; 298 | glfwGetCursorPos(CurrentWindow(), xx, yy); 299 | x = xx[0]; 300 | y = yy[0]; 301 | } 302 | 303 | public void setCursorPosition(float x, float y) 304 | { 305 | glfwSetCursorPos(m_window, x, y); 306 | Update(); 307 | } 308 | 309 | public void setGrabbed(boolean grabbed) 310 | { 311 | if(grabbed) 312 | { 313 | glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); 314 | } 315 | else 316 | { 317 | glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); 318 | } 319 | } 320 | 321 | public double getWheel() 322 | { 323 | return wheel; 324 | } 325 | 326 | public double getX() 327 | { 328 | return x; 329 | } 330 | 331 | public double getY() 332 | { 333 | //TODO: This is a fucking bug, remove this temp fix and fix it permanently. 334 | int height = (int) Math.ceil((HEIGHT/1080.0)-1.0); 335 | return (HEIGHT - height) - y; 336 | } 337 | 338 | public double getOGLX() 339 | { 340 | return x; 341 | } 342 | 343 | public double getOGLY() 344 | { 345 | return y; 346 | } 347 | } 348 | 349 | public static void SetResizeable(boolean b) 350 | { 351 | int bool = GL_FALSE; 352 | if(b) bool = GL_TRUE; 353 | glfwWindowHint(GLFW_RESIZABLE, bool); 354 | } 355 | 356 | public static void SetSize(int i, int j) 357 | { 358 | glfwSetWindowSize(m_window, i, j); 359 | } 360 | 361 | public static void AddDragAndDropBehaviour(ScreenDraggable draggable) 362 | { 363 | s_behaviours.add(draggable); 364 | } 365 | 366 | public static interface ScreenDraggable 367 | { 368 | public void CheckDropped(String string); 369 | } 370 | } 371 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/meshLoading/IndexedModel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering.meshLoading; 18 | 19 | import com.base.engine.core.Vector2f; 20 | import com.base.engine.core.Vector3f; 21 | 22 | import java.util.ArrayList; 23 | 24 | public class IndexedModel 25 | { 26 | private ArrayList m_positions; 27 | private ArrayList m_texCoords; 28 | private ArrayList m_normals; 29 | private ArrayList m_tangents; 30 | private ArrayList m_indices; 31 | 32 | public IndexedModel() 33 | { 34 | m_positions = new ArrayList(); 35 | m_texCoords = new ArrayList(); 36 | m_normals = new ArrayList(); 37 | m_tangents = new ArrayList(); 38 | m_indices = new ArrayList(); 39 | } 40 | 41 | public void CalcNormals() 42 | { 43 | for(int i = 0; i < m_indices.size(); i += 3) 44 | { 45 | int i0 = m_indices.get(i); 46 | int i1 = m_indices.get(i + 1); 47 | int i2 = m_indices.get(i + 2); 48 | 49 | Vector3f v1 = m_positions.get(i1).Sub(m_positions.get(i0)); 50 | Vector3f v2 = m_positions.get(i2).Sub(m_positions.get(i0)); 51 | 52 | Vector3f normal = v1.Cross(v2).Normalized(); 53 | 54 | m_normals.get(i0).Set(m_normals.get(i0).Add(normal)); 55 | m_normals.get(i1).Set(m_normals.get(i1).Add(normal)); 56 | m_normals.get(i2).Set(m_normals.get(i2).Add(normal)); 57 | } 58 | 59 | for(int i = 0; i < m_normals.size(); i++) 60 | m_normals.get(i).Set(m_normals.get(i).Normalized()); 61 | } 62 | 63 | public void CalcTangents() 64 | { 65 | for(int i = 0; i < m_indices.size(); i += 3) 66 | { 67 | int i0 = m_indices.get(i); 68 | int i1 = m_indices.get(i + 1); 69 | int i2 = m_indices.get(i + 2); 70 | 71 | Vector3f edge1 = m_positions.get(i1).Sub(m_positions.get(i0)); 72 | Vector3f edge2 = m_positions.get(i2).Sub(m_positions.get(i0)); 73 | 74 | float deltaU1 = m_texCoords.get(i1).GetX() - m_texCoords.get(i0).GetX(); 75 | float deltaV1 = m_texCoords.get(i1).GetY() - m_texCoords.get(i0).GetY(); 76 | float deltaU2 = m_texCoords.get(i2).GetX() - m_texCoords.get(i0).GetX(); 77 | float deltaV2 = m_texCoords.get(i2).GetY() - m_texCoords.get(i0).GetY(); 78 | 79 | float dividend = (deltaU1*deltaV2 - deltaU2*deltaV1); 80 | //TODO: The first 0.0f may need to be changed to 1.0f here. 81 | float f = dividend == 0 ? 0.0f : 1.0f/dividend; 82 | 83 | Vector3f tangent = new Vector3f(0,0,0); 84 | tangent.SetX(f * (deltaV2 * edge1.GetX() - deltaV1 * edge2.GetX())); 85 | tangent.SetY(f * (deltaV2 * edge1.GetY() - deltaV1 * edge2.GetY())); 86 | tangent.SetZ(f * (deltaV2 * edge1.GetZ() - deltaV1 * edge2.GetZ())); 87 | 88 | m_tangents.get(i0).Set(m_tangents.get(i0).Add(tangent)); 89 | m_tangents.get(i1).Set(m_tangents.get(i1).Add(tangent)); 90 | m_tangents.get(i2).Set(m_tangents.get(i2).Add(tangent)); 91 | } 92 | 93 | for(int i = 0; i < m_tangents.size(); i++) 94 | m_tangents.get(i).Set(m_tangents.get(i).Normalized()); 95 | } 96 | 97 | public ArrayList GetPositions() { return m_positions; } 98 | public ArrayList GetTexCoords() { return m_texCoords; } 99 | public ArrayList GetNormals() { return m_normals; } 100 | public ArrayList GetTangents() { return m_tangents; } 101 | public ArrayList GetIndices() { return m_indices; } 102 | } 103 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/meshLoading/OBJIndex.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering.meshLoading; 18 | 19 | public class OBJIndex 20 | { 21 | private int m_vertexIndex; 22 | private int m_texCoordIndex; 23 | private int m_normalIndex; 24 | 25 | public int GetVertexIndex() { return m_vertexIndex; } 26 | public int GetTexCoordIndex() { return m_texCoordIndex; } 27 | public int GetNormalIndex() { return m_normalIndex; } 28 | 29 | public void SetVertexIndex(int val) { m_vertexIndex = val; } 30 | public void SetTexCoordIndex(int val) { m_texCoordIndex = val; } 31 | public void SetNormalIndex(int val) { m_normalIndex = val; } 32 | 33 | @Override 34 | public boolean equals(Object obj) 35 | { 36 | OBJIndex index = (OBJIndex)obj; 37 | 38 | return m_vertexIndex == index.m_vertexIndex 39 | && m_texCoordIndex == index.m_texCoordIndex 40 | && m_normalIndex == index.m_normalIndex; 41 | } 42 | 43 | @Override 44 | public int hashCode() 45 | { 46 | final int BASE = 17; 47 | final int MULTIPLIER = 31; 48 | 49 | int result = BASE; 50 | 51 | result = MULTIPLIER * result + m_vertexIndex; 52 | result = MULTIPLIER * result + m_texCoordIndex; 53 | result = MULTIPLIER * result + m_normalIndex; 54 | 55 | return result; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/meshLoading/OBJModel.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering.meshLoading; 18 | 19 | import com.base.engine.core.Util; 20 | import com.base.engine.core.Vector2f; 21 | import com.base.engine.core.Vector3f; 22 | 23 | import java.io.BufferedReader; 24 | import java.io.FileReader; 25 | import java.util.ArrayList; 26 | import java.util.HashMap; 27 | 28 | public class OBJModel 29 | { 30 | private ArrayList m_positions; 31 | private ArrayList m_texCoords; 32 | private ArrayList m_normals; 33 | private ArrayList m_indices; 34 | private boolean m_hasTexCoords; 35 | private boolean m_hasNormals; 36 | 37 | public OBJModel(String fileName) 38 | { 39 | m_positions = new ArrayList(); 40 | m_texCoords = new ArrayList(); 41 | m_normals = new ArrayList(); 42 | m_indices = new ArrayList(); 43 | m_hasTexCoords = false; 44 | m_hasNormals = false; 45 | 46 | BufferedReader meshReader = null; 47 | 48 | try 49 | { 50 | meshReader = new BufferedReader(new FileReader(fileName)); 51 | String line; 52 | 53 | while((line = meshReader.readLine()) != null) 54 | { 55 | String[] tokens = line.split(" "); 56 | tokens = Util.RemoveEmptyStrings(tokens); 57 | 58 | if(tokens.length == 0 || tokens[0].equals("#")) 59 | continue; 60 | else if(tokens[0].equals("v")) 61 | { 62 | m_positions.add(new Vector3f(Float.valueOf(tokens[1]), 63 | Float.valueOf(tokens[2]), 64 | Float.valueOf(tokens[3]))); 65 | } 66 | else if(tokens[0].equals("vt")) 67 | { 68 | m_texCoords.add(new Vector2f(Float.valueOf(tokens[1]), 69 | 1.0f - Float.valueOf(tokens[2]))); 70 | } 71 | else if(tokens[0].equals("vn")) 72 | { 73 | m_normals.add(new Vector3f(Float.valueOf(tokens[1]), 74 | Float.valueOf(tokens[2]), 75 | Float.valueOf(tokens[3]))); 76 | } 77 | else if(tokens[0].equals("f")) 78 | { 79 | for(int i = 0; i < tokens.length - 3; i++) 80 | { 81 | m_indices.add(ParseOBJIndex(tokens[1])); 82 | m_indices.add(ParseOBJIndex(tokens[2 + i])); 83 | m_indices.add(ParseOBJIndex(tokens[3 + i])); 84 | } 85 | } 86 | } 87 | 88 | meshReader.close(); 89 | } 90 | catch(Exception e) 91 | { 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | public IndexedModel ToIndexedModel() 98 | { 99 | IndexedModel result = new IndexedModel(); 100 | IndexedModel normalModel = new IndexedModel(); 101 | HashMap resultIndexMap = new HashMap(); 102 | HashMap normalIndexMap = new HashMap(); 103 | HashMap indexMap = new HashMap(); 104 | 105 | for(int i = 0; i < m_indices.size(); i++) 106 | { 107 | OBJIndex currentIndex = m_indices.get(i); 108 | 109 | Vector3f currentPosition = m_positions.get(currentIndex.GetVertexIndex()); 110 | Vector2f currentTexCoord; 111 | Vector3f currentNormal; 112 | 113 | if(m_hasTexCoords) 114 | currentTexCoord = m_texCoords.get(currentIndex.GetTexCoordIndex()); 115 | else 116 | currentTexCoord = new Vector2f(0,0); 117 | 118 | if(m_hasNormals) 119 | currentNormal = m_normals.get(currentIndex.GetNormalIndex()); 120 | else 121 | currentNormal = new Vector3f(0,0,0); 122 | 123 | Integer modelVertexIndex = resultIndexMap.get(currentIndex); 124 | 125 | if(modelVertexIndex == null) 126 | { 127 | modelVertexIndex = result.GetPositions().size(); 128 | resultIndexMap.put(currentIndex, modelVertexIndex); 129 | 130 | result.GetPositions().add(currentPosition); 131 | result.GetTexCoords().add(currentTexCoord); 132 | if(m_hasNormals) 133 | result.GetNormals().add(currentNormal); 134 | } 135 | 136 | Integer normalModelIndex = normalIndexMap.get(currentIndex.GetVertexIndex()); 137 | 138 | if(normalModelIndex == null) 139 | { 140 | normalModelIndex = normalModel.GetPositions().size(); 141 | normalIndexMap.put(currentIndex.GetVertexIndex(), normalModelIndex); 142 | 143 | normalModel.GetPositions().add(currentPosition); 144 | normalModel.GetTexCoords().add(currentTexCoord); 145 | normalModel.GetNormals().add(currentNormal); 146 | normalModel.GetTangents().add(new Vector3f(0,0,0)); 147 | } 148 | 149 | result.GetIndices().add(modelVertexIndex); 150 | normalModel.GetIndices().add(normalModelIndex); 151 | indexMap.put(modelVertexIndex, normalModelIndex); 152 | } 153 | 154 | if(!m_hasNormals) 155 | { 156 | normalModel.CalcNormals(); 157 | 158 | for(int i = 0; i < result.GetPositions().size(); i++) 159 | result.GetNormals().add(normalModel.GetNormals().get(indexMap.get(i))); 160 | } 161 | 162 | normalModel.CalcTangents(); 163 | 164 | for(int i = 0; i < result.GetPositions().size(); i++) 165 | result.GetTangents().add(normalModel.GetTangents().get(indexMap.get(i))); 166 | 167 | // for(int i = 0; i < result.GetTexCoords().size(); i++) 168 | // result.GetTexCoords().Get(i).SetY(1.0f - result.GetTexCoords().Get(i).GetY()); 169 | 170 | return result; 171 | } 172 | 173 | private OBJIndex ParseOBJIndex(String token) 174 | { 175 | String[] values = token.split("/"); 176 | 177 | OBJIndex result = new OBJIndex(); 178 | result.SetVertexIndex(Integer.parseInt(values[0]) - 1); 179 | 180 | if(values.length > 1) 181 | { 182 | if(!values[1].isEmpty()) 183 | { 184 | m_hasTexCoords = true; 185 | result.SetTexCoordIndex(Integer.parseInt(values[1]) - 1); 186 | } 187 | 188 | if(values.length > 2) 189 | { 190 | m_hasNormals = true; 191 | result.SetNormalIndex(Integer.parseInt(values[2]) - 1); 192 | } 193 | } 194 | 195 | return result; 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/resourceManagement/MappedValues.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering.resourceManagement; 18 | 19 | import com.base.engine.core.Vector3f; 20 | 21 | import java.util.HashMap; 22 | 23 | public abstract class MappedValues 24 | { 25 | private HashMap m_vector3fHashMap; 26 | private HashMap m_floatHashMap; 27 | 28 | public MappedValues() 29 | { 30 | m_vector3fHashMap = new HashMap(); 31 | m_floatHashMap = new HashMap(); 32 | } 33 | 34 | public void AddVector3f(String name, Vector3f vector3f) { m_vector3fHashMap.put(name, vector3f); } 35 | public void AddFloat(String name, float floatValue) { m_floatHashMap.put(name, floatValue); } 36 | 37 | public Vector3f GetVector3f(String name) 38 | { 39 | Vector3f result = m_vector3fHashMap.get(name); 40 | if(result != null) 41 | return result; 42 | 43 | return new Vector3f(0,0,0); 44 | } 45 | 46 | public float GetFloat(String name) 47 | { 48 | Float result = m_floatHashMap.get(name); 49 | if(result != null) 50 | return result; 51 | 52 | return 0; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/resourceManagement/MeshResource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering.resourceManagement; 18 | 19 | import static org.lwjgl.opengl.GL15.*; 20 | 21 | public class MeshResource 22 | { 23 | private int m_vbo; 24 | private int m_ibo; 25 | private int m_size; 26 | private int m_refCount; 27 | 28 | public MeshResource(int size) 29 | { 30 | m_vbo = glGenBuffers(); 31 | m_ibo = glGenBuffers(); 32 | this.m_size = size; 33 | this.m_refCount = 1; 34 | } 35 | 36 | @Override 37 | protected void finalize() 38 | { 39 | // glDeleteBuffers(m_vbo); 40 | // glDeleteBuffers(m_ibo); 41 | } 42 | 43 | public void AddReference() 44 | { 45 | m_refCount++; 46 | } 47 | 48 | public boolean RemoveReference() 49 | { 50 | m_refCount--; 51 | return m_refCount == 0; 52 | } 53 | 54 | public int GetVbo() { return m_vbo; } 55 | public int GetIbo() { return m_ibo; } 56 | public int GetSize() { return m_size; } 57 | } 58 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/resourceManagement/ShaderResource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering.resourceManagement; 18 | 19 | import java.util.ArrayList; 20 | import java.util.HashMap; 21 | 22 | import static org.lwjgl.opengl.GL15.glDeleteBuffers; 23 | import static org.lwjgl.opengl.GL20.glCreateProgram; 24 | 25 | public class ShaderResource 26 | { 27 | private int m_program; 28 | private HashMap m_uniforms; 29 | private ArrayList m_uniformNames; 30 | private ArrayList m_uniformTypes; 31 | private int m_refCount; 32 | 33 | public ShaderResource() 34 | { 35 | this.m_program = glCreateProgram(); 36 | this.m_refCount = 1; 37 | 38 | if(m_program == 0) 39 | { 40 | System.err.println("Shader creation failed: Could not find valid memory location in constructor"); 41 | System.exit(1); 42 | } 43 | 44 | m_uniforms = new HashMap(); 45 | m_uniformNames = new ArrayList(); 46 | m_uniformTypes = new ArrayList(); 47 | } 48 | 49 | @Override 50 | protected void finalize() 51 | { 52 | glDeleteBuffers(m_program); 53 | } 54 | 55 | public void AddReference() 56 | { 57 | m_refCount++; 58 | } 59 | 60 | public boolean RemoveReference() 61 | { 62 | m_refCount--; 63 | return m_refCount == 0; 64 | } 65 | 66 | public int GetProgram() { return m_program; } 67 | public HashMap GetUniforms() { return m_uniforms; } 68 | public ArrayList GetUniformNames() { return m_uniformNames; } 69 | public ArrayList GetUniformTypes() { return m_uniformTypes; } 70 | } 71 | -------------------------------------------------------------------------------- /src/com/base/engine/rendering/resourceManagement/TextureResource.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.engine.rendering.resourceManagement; 18 | 19 | import static org.lwjgl.opengl.GL11.glGenTextures; 20 | import static org.lwjgl.opengl.GL15.glDeleteBuffers; 21 | 22 | public class TextureResource 23 | { 24 | private int m_id; 25 | private int m_refCount; 26 | 27 | public TextureResource() 28 | { 29 | this.m_id = glGenTextures(); 30 | this.m_refCount = 1; 31 | } 32 | 33 | @Override 34 | protected void finalize() 35 | { 36 | glDeleteBuffers(m_id); 37 | } 38 | 39 | public void AddReference() 40 | { 41 | m_refCount++; 42 | } 43 | 44 | public boolean RemoveReference() 45 | { 46 | m_refCount--; 47 | return m_refCount == 0; 48 | } 49 | 50 | public int GetId() { return m_id; } 51 | } 52 | -------------------------------------------------------------------------------- /src/com/base/game/AnimatedComponent.java: -------------------------------------------------------------------------------- 1 | package com.base.game; 2 | 3 | import static org.lwjgl.opengl.GL11.*; 4 | import static org.lwjgl.opengl.GL15.*; 5 | import static org.lwjgl.opengl.GL20.*; 6 | 7 | import java.nio.FloatBuffer; 8 | import java.nio.IntBuffer; 9 | 10 | import org.lwjgl.assimp.AIAnimation; 11 | import org.lwjgl.assimp.AINode; 12 | import org.lwjgl.assimp.AINodeAnim; 13 | 14 | import com.base.engine.components.GameComponent; 15 | import com.base.engine.core.Matrix4f; 16 | import com.base.engine.core.Quaternion; 17 | import com.base.engine.core.Vector3f; 18 | import com.base.engine.rendering.Material; 19 | import com.base.engine.rendering.RenderingEngine; 20 | import com.base.engine.rendering.Shader; 21 | import com.base.engine.rendering.Texture; 22 | import com.base.engine.rendering.resourceManagement.MeshResource; 23 | 24 | public class AnimatedComponent extends GameComponent 25 | { 26 | public Matrix4f globalInverseTransform; 27 | public Bone bones[]; 28 | public Matrix4f boneTransforms[]; 29 | public AINode root; 30 | public AIAnimation animation; 31 | public MeshResource resource; 32 | public Shader shader; 33 | public Material material; 34 | 35 | long timer = System.currentTimeMillis(); 36 | 37 | public void AddVertices(FloatBuffer vertices, IntBuffer indices) 38 | { 39 | shader = new Shader("forward-ambient2"); 40 | material = new Material(new Texture("bricks.jpg"), 1, 8, 41 | new Texture("bricks_normal.jpg"), new Texture("bricks_disp.png"), 0.03f, -0.5f); 42 | 43 | resource = new MeshResource(indices.capacity()); 44 | 45 | glBindBuffer(GL_ARRAY_BUFFER, resource.GetVbo()); 46 | glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW); 47 | 48 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, resource.GetIbo()); 49 | glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW); 50 | } 51 | 52 | @Override 53 | public void Update(float delta) { 54 | super.Update(delta); 55 | 56 | boneTransforms((float)(((double)System.currentTimeMillis() - (double)timer) / 1000.0)); 57 | } 58 | 59 | AINodeAnim FindNodeAnim(AIAnimation pAnimation, String NodeName) 60 | { 61 | for (int i = 0 ; i < pAnimation.mNumChannels(); i++) { 62 | AINodeAnim pNodeAnim = AINodeAnim.create(pAnimation.mChannels().get(i)); 63 | 64 | if (pNodeAnim.mNodeName().dataString().equals(NodeName)) return pNodeAnim; 65 | } 66 | 67 | return null; 68 | } 69 | 70 | void CalcInterpolatedPosition(Vector3f Out, float AnimationTime, AINodeAnim pNodeAnim) 71 | { 72 | if (pNodeAnim.mNumPositionKeys() == 1) { 73 | Out.Set(Vector3f.fromAssimp(pNodeAnim.mPositionKeys().get(0).mValue())); 74 | return; 75 | } 76 | 77 | int PositionIndex = FindPosition(AnimationTime, pNodeAnim); 78 | int NextPositionIndex = (PositionIndex + 1); 79 | assert(NextPositionIndex < pNodeAnim.mNumPositionKeys()); 80 | float DeltaTime = (float)(pNodeAnim.mPositionKeys().get(NextPositionIndex).mTime() - pNodeAnim.mPositionKeys().get(PositionIndex).mTime()); 81 | float Factor = (AnimationTime - (float)pNodeAnim.mPositionKeys().get(PositionIndex).mTime()) / DeltaTime; 82 | assert(Factor >= 0.0f && Factor <= 1.0f); 83 | Vector3f Start = Vector3f.fromAssimp(pNodeAnim.mPositionKeys().get(PositionIndex).mValue()); 84 | Vector3f End = Vector3f.fromAssimp(pNodeAnim.mPositionKeys().get(NextPositionIndex).mValue()); 85 | Vector3f Delta = End.Sub(Start); 86 | Out.Set(Start.Add(Delta.Mul(Factor)));// + Factor * Delta; 87 | } 88 | 89 | 90 | void CalcInterpolatedRotation(Quaternion Out, float AnimationTime, AINodeAnim pNodeAnim) 91 | { 92 | // we need at least two values to interpolate... 93 | if (pNodeAnim.mNumRotationKeys() == 1) { 94 | Out.Set(Quaternion.fromAssimp(pNodeAnim.mRotationKeys().get(0).mValue())); 95 | return; 96 | } 97 | 98 | int RotationIndex = FindRotation(AnimationTime, pNodeAnim); 99 | int NextRotationIndex = (RotationIndex + 1); 100 | assert(NextRotationIndex < pNodeAnim.mNumRotationKeys()); 101 | float DeltaTime = (float)(pNodeAnim.mRotationKeys().get(NextRotationIndex).mTime() - pNodeAnim.mRotationKeys().get(RotationIndex).mTime()); 102 | float Factor = (AnimationTime - (float)pNodeAnim.mRotationKeys().get(RotationIndex).mTime()) / DeltaTime; 103 | assert(Factor >= 0.0f && Factor <= 1.0f); 104 | Quaternion StartRotationQ = Quaternion.fromAssimp(pNodeAnim.mRotationKeys().get(RotationIndex).mValue()); 105 | Quaternion EndRotationQ = Quaternion.fromAssimp(pNodeAnim.mRotationKeys().get(NextRotationIndex).mValue()); 106 | Out.Set(StartRotationQ.SLerp(EndRotationQ, Factor, false));// = AIQuaternion.Interpolate(Out, StartRotationQ, EndRotationQ, Factor); 107 | // Out = Out.Normalize(); 108 | } 109 | 110 | 111 | void CalcInterpolatedScaling(Vector3f Out, float AnimationTime, AINodeAnim pNodeAnim) 112 | { 113 | if (pNodeAnim.mNumScalingKeys() == 1) { 114 | Out = Vector3f.fromAssimp(pNodeAnim.mScalingKeys().get(0).mValue()); 115 | return; 116 | } 117 | 118 | int ScalingIndex = FindScaling(AnimationTime, pNodeAnim); 119 | int NextScalingIndex = (ScalingIndex + 1); 120 | assert(NextScalingIndex < pNodeAnim.mNumScalingKeys()); 121 | float DeltaTime = (float)(pNodeAnim.mScalingKeys().get(NextScalingIndex).mTime() - pNodeAnim.mScalingKeys().get(ScalingIndex).mTime()); 122 | float Factor = (AnimationTime - (float)pNodeAnim.mScalingKeys().get(ScalingIndex).mTime()) / DeltaTime; 123 | assert(Factor >= 0.0f && Factor <= 1.0f); 124 | Vector3f Start = Vector3f.fromAssimp(pNodeAnim.mScalingKeys().get(ScalingIndex).mValue()); 125 | Vector3f End = Vector3f.fromAssimp(pNodeAnim.mScalingKeys().get(NextScalingIndex).mValue()); 126 | Vector3f Delta = End.Sub(Start); 127 | Out.Set(Start.Add(Delta.Mul(Factor))); 128 | } 129 | 130 | int FindPosition(float AnimationTime, AINodeAnim pNodeAnim) 131 | { 132 | for (int i = 0 ; i < pNodeAnim.mNumPositionKeys() - 1 ; i++) { 133 | if (AnimationTime < (float)pNodeAnim.mPositionKeys().get(i + 1).mTime()) { 134 | return i; 135 | } 136 | } 137 | 138 | return 0; 139 | } 140 | 141 | 142 | int FindRotation(float AnimationTime, AINodeAnim pNodeAnim) 143 | { 144 | assert(pNodeAnim.mNumRotationKeys() > 0); 145 | 146 | for (int i = 0 ; i < pNodeAnim.mNumRotationKeys() - 1 ; i++) { 147 | if (AnimationTime < (float)pNodeAnim.mRotationKeys().get(i + 1).mTime()) { 148 | return i; 149 | } 150 | } 151 | 152 | return 0; 153 | } 154 | 155 | 156 | int FindScaling(float AnimationTime, AINodeAnim pNodeAnim) 157 | { 158 | assert(pNodeAnim.mNumScalingKeys() > 0); 159 | 160 | for (int i = 0 ; i < pNodeAnim.mNumScalingKeys() - 1 ; i++) { 161 | if (AnimationTime < (float)pNodeAnim.mScalingKeys().get(i + 1).mTime()) { 162 | return i; 163 | } 164 | } 165 | 166 | return 0; 167 | } 168 | 169 | protected void ReadNodeHeirarchy(float AnimationTime, AINode pNode, Matrix4f ParentTransform) 170 | { 171 | String NodeName = pNode.mName().dataString(); 172 | 173 | // engine.animation pAnimation = null;//m_pScene.mAnimations[0]; 174 | 175 | Matrix4f NodeTransformation = new Matrix4f().fromAssimp(pNode.mTransformation());//(pNode.mTransformation); 176 | 177 | AINodeAnim pNodeAnim = FindNodeAnim(animation, NodeName); 178 | 179 | if (pNodeAnim != null) 180 | { 181 | // Interpolate scaling and generate scaling transformation matrix 182 | Vector3f Scaling = new Vector3f(0, 0, 0); 183 | CalcInterpolatedScaling(Scaling, AnimationTime, pNodeAnim); 184 | Matrix4f ScalingM = new Matrix4f().InitScale(Scaling.x(), Scaling.y(), Scaling.z()); 185 | 186 | // Interpolate rotation and generate rotation transformation matrix 187 | Quaternion RotationQ = new Quaternion(0, 0, 0, 0); 188 | CalcInterpolatedRotation(RotationQ, AnimationTime, pNodeAnim); 189 | Matrix4f RotationM = RotationQ.ToRotationMatrix(); 190 | 191 | // Interpolate translation and generate translation transformation matrix 192 | Vector3f Translation = new Vector3f(0, 0, 0); 193 | CalcInterpolatedPosition(Translation, AnimationTime, pNodeAnim); 194 | Matrix4f TranslationM = new Matrix4f().InitTranslation(Translation.x(), Translation.y(), Translation.z()); 195 | 196 | // Combine the above transformations 197 | NodeTransformation = TranslationM.Mul(RotationM).Mul(ScalingM); 198 | } 199 | 200 | Matrix4f GlobalTransformation = ParentTransform.Mul(NodeTransformation); 201 | 202 | Bone bone = null; 203 | 204 | if ((bone = findBone(NodeName)) != null) 205 | { 206 | bone.finalTransformation = globalInverseTransform.Mul(GlobalTransformation).Mul(bone.offsetMatrix); 207 | } 208 | 209 | for (int i = 0 ; i < pNode.mNumChildren(); i++) { 210 | ReadNodeHeirarchy(AnimationTime, AINode.create(pNode.mChildren().get(i)), GlobalTransformation); 211 | } 212 | } 213 | 214 | private final Bone findBone(String name) 215 | { 216 | for(Bone bone : bones) if(bone.name.equals(name)) return bone; 217 | 218 | return null; 219 | } 220 | 221 | public void boneTransforms(float timeInSeconds) 222 | { 223 | Matrix4f Identity = new Matrix4f().InitIdentity(); 224 | 225 | float TicksPerSecond = (float)(animation.mTicksPerSecond() != 0 ? animation.mTicksPerSecond() : 25.0f); 226 | float TimeInTicks = timeInSeconds * TicksPerSecond; 227 | float AnimationTime = (TimeInTicks % (float)animation.mDuration()); 228 | 229 | ReadNodeHeirarchy(AnimationTime, root, Identity); 230 | 231 | // boneTransforms.resize(m_NumBones); 232 | 233 | for (short i = 0 ; i < bones.length ; i++) { 234 | boneTransforms[i] = bones[i].finalTransformation; 235 | } 236 | } 237 | 238 | @Override 239 | public void Render(Shader notshader, RenderingEngine renderingEngine) { 240 | shader.Bind(); 241 | GetTransform().SetRot(new Quaternion(new Matrix4f().InitRotation(-90, 0, 0))); 242 | 243 | for(int i = 0; i < boneTransforms.length; i++) shader.SetUniform("gBones[" + i + "]", boneTransforms[i]); 244 | shader.UpdateUniforms(GetTransform(), material, renderingEngine); 245 | 246 | glEnableVertexAttribArray(0); 247 | glEnableVertexAttribArray(1); 248 | glEnableVertexAttribArray(2); 249 | glEnableVertexAttribArray(3); 250 | glEnableVertexAttribArray(4); 251 | glEnableVertexAttribArray(5); 252 | 253 | glBindBuffer(GL_ARRAY_BUFFER, resource.GetVbo()); 254 | glVertexAttribPointer(0, 3, GL_FLOAT, false, 19 * 4, 0); 255 | glVertexAttribPointer(1, 2, GL_FLOAT, false, 19 * 4, 12); 256 | glVertexAttribPointer(2, 3, GL_FLOAT, false, 19 * 4, 20); 257 | glVertexAttribPointer(3, 3, GL_FLOAT, false, 19 * 4, 32); 258 | glVertexAttribPointer(4, 4, GL_FLOAT, false, 19 * 4, 44); 259 | glVertexAttribPointer(5, 4, GL_FLOAT, false, 19 * 4, 60); 260 | 261 | glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, resource.GetIbo()); 262 | glDrawElements(GL_TRIANGLES, resource.GetSize(), GL_UNSIGNED_INT, 0); 263 | 264 | glDisableVertexAttribArray(0); 265 | glDisableVertexAttribArray(1); 266 | glDisableVertexAttribArray(2); 267 | glDisableVertexAttribArray(3); 268 | glDisableVertexAttribArray(4); 269 | glDisableVertexAttribArray(5); 270 | } 271 | } -------------------------------------------------------------------------------- /src/com/base/game/AnimationUtil.java: -------------------------------------------------------------------------------- 1 | package com.base.game; 2 | 3 | import java.io.File; 4 | import java.nio.FloatBuffer; 5 | import java.nio.IntBuffer; 6 | import java.util.HashMap; 7 | 8 | import org.lwjgl.assimp.AIAnimation; 9 | import org.lwjgl.assimp.AIBone; 10 | import org.lwjgl.assimp.AIFace; 11 | import org.lwjgl.assimp.AIMatrix4x4; 12 | import org.lwjgl.assimp.AIMesh; 13 | import org.lwjgl.assimp.AIScene; 14 | import org.lwjgl.assimp.AIVector3D; 15 | import org.lwjgl.assimp.AIVertexWeight; 16 | import org.lwjgl.assimp.Assimp; 17 | 18 | import com.base.engine.core.Matrix4f; 19 | import com.base.engine.core.Util; 20 | 21 | public class AnimationUtil { 22 | public static final AnimatedComponent loadAnimatedFile(File file) 23 | { 24 | AIScene scene = Assimp.aiImportFile(file.toString(), 25 | Assimp.aiProcess_Triangulate | 26 | Assimp.aiProcess_GenSmoothNormals | 27 | Assimp.aiProcess_FlipUVs | 28 | Assimp.aiProcess_CalcTangentSpace | 29 | Assimp.aiProcess_LimitBoneWeights 30 | ); 31 | 32 | if(scene == null | scene.mNumAnimations() == 0) 33 | { 34 | System.err.println("the imported file does not contain any animations."); 35 | System.exit(0); 36 | } 37 | 38 | AIMesh mesh = AIMesh.create(scene.mMeshes().get(0)); 39 | 40 | int sizeOfVertex = 19; 41 | int sizeOfVertexUnrigged = 11; 42 | /** 43 | * position data 3f 44 | * normal data 3f 45 | * tangent data 3f 46 | * texcoord data 2f 47 | * 48 | * bone info 4f 49 | * bone info 4f 50 | */ 51 | float array[] = new float[mesh.mNumVertices() * sizeOfVertex]; 52 | int index = 0; 53 | 54 | for(int v = 0; v < mesh.mNumVertices(); v++) 55 | { 56 | AIVector3D position = mesh.mVertices().get(v); 57 | AIVector3D normal = mesh.mNormals().get(v); 58 | AIVector3D tangent = mesh.mTangents().get(v); 59 | AIVector3D texCoord = mesh.mTextureCoords(0).get(v); 60 | /** 61 | * The above assumes that the program has texture coordinates, if it doesn't the program will throw a null pointer exception. 62 | */ 63 | 64 | array[index++] = position.x(); 65 | array[index++] = position.y(); 66 | array[index++] = position.z(); 67 | 68 | array[index++] = texCoord.x(); 69 | array[index++] = texCoord.y(); 70 | 71 | array[index++] = normal.x(); 72 | array[index++] = normal.y(); 73 | array[index++] = normal.z(); 74 | 75 | array[index++] = tangent.x(); 76 | array[index++] = tangent.y(); 77 | array[index++] = tangent.z(); 78 | 79 | array[index++] = 0; 80 | array[index++] = 0; 81 | array[index++] = 0; 82 | array[index++] = 0; 83 | 84 | array[index++] = 0; 85 | array[index++] = 0; 86 | array[index++] = 0; 87 | array[index++] = 0; 88 | } 89 | 90 | index = 0; 91 | /** 92 | * ^ 93 | * this has to be here 94 | */ 95 | IntBuffer indices = Util.CreateIntBuffer(mesh.mNumFaces() * mesh.mFaces().get(0).mNumIndices()); 96 | 97 | for(int f = 0; f < mesh.mNumFaces(); f++) 98 | { 99 | AIFace face = mesh.mFaces().get(f); 100 | for(int ind = 0; ind < face.mNumIndices(); ind++) 101 | indices.put(face.mIndices().get(ind)); 102 | } 103 | 104 | HashMap boneMap = new HashMap<>(); 105 | HashMap bone_index_map0 = new HashMap<>(); 106 | HashMap bone_index_map1 = new HashMap<>(); 107 | 108 | for(int b = 0; b < mesh.mNumBones(); b++) 109 | { 110 | AIBone bone = AIBone.create(mesh.mBones().get(b)); 111 | boneMap.put(bone.mName().dataString(), b); 112 | 113 | for(int w = 0; w < bone.mNumWeights(); w++) 114 | { 115 | AIVertexWeight weight = bone.mWeights().get(w); 116 | int vertexIndex = weight.mVertexId(); 117 | int findex = vertexIndex * sizeOfVertex; 118 | 119 | if(!bone_index_map0.containsKey(vertexIndex)) 120 | { 121 | array[(findex + sizeOfVertexUnrigged) + 0] = b; 122 | array[(findex + sizeOfVertexUnrigged) + 2] = weight.mWeight(); 123 | bone_index_map0.put(vertexIndex, 0); 124 | } else if(bone_index_map0.get(vertexIndex) == 0) 125 | { 126 | array[(findex + sizeOfVertexUnrigged) + 1] = b; 127 | array[(findex + sizeOfVertexUnrigged) + 3] = weight.mWeight(); 128 | bone_index_map0.put(vertexIndex, 1); 129 | } else if(!bone_index_map1.containsKey(vertexIndex)) 130 | { 131 | array[(findex + sizeOfVertexUnrigged) + 4] = b; 132 | array[(findex + sizeOfVertexUnrigged) + 6] = weight.mWeight(); 133 | bone_index_map1.put(vertexIndex, 0); 134 | } else if(bone_index_map1.get(vertexIndex) == 0) 135 | { 136 | array[(findex + sizeOfVertexUnrigged) + 5] = b; 137 | array[(findex + sizeOfVertexUnrigged) + 7] = weight.mWeight(); 138 | bone_index_map1.put(vertexIndex, 1); 139 | } else { 140 | System.err.println("max 4 bones per vertex."); 141 | System.exit(0); 142 | } 143 | } 144 | } 145 | 146 | AIMatrix4x4 inverseRootTransform = scene.mRootNode().mTransformation(); 147 | Matrix4f inverseRootTransformation = new Matrix4f().fromAssimp(inverseRootTransform); 148 | 149 | Bone bones[] = new Bone[boneMap.size()]; 150 | 151 | for(int b = 0; b < mesh.mNumBones(); b++) 152 | { 153 | AIBone bone = AIBone.create(mesh.mBones().get(b)); 154 | bones[b] = new Bone(); 155 | 156 | bones[b].name = bone.mName().dataString(); 157 | bones[b].offsetMatrix = new Matrix4f().fromAssimp(bone.mOffsetMatrix()); 158 | } 159 | 160 | AnimatedComponent component = new AnimatedComponent(); 161 | FloatBuffer vertices = Util.CreateFloatBuffer(array.length); 162 | 163 | for(int i = 0; i < array.length; i++) vertices.put(array[i]); 164 | vertices.flip(); 165 | indices.flip(); 166 | 167 | component.AddVertices(vertices, indices); 168 | 169 | component.animation = AIAnimation.create(scene.mAnimations().get(0)); 170 | component.bones = bones; 171 | component.boneTransforms = new Matrix4f[bones.length]; 172 | component.root = scene.mRootNode(); 173 | component.globalInverseTransform = inverseRootTransformation; 174 | 175 | return component; 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /src/com/base/game/Bone.java: -------------------------------------------------------------------------------- 1 | package com.base.game; 2 | 3 | import com.base.engine.core.Matrix4f; 4 | import com.base.engine.core.Transform; 5 | 6 | public class Bone { 7 | public String name; 8 | public Matrix4f offsetMatrix; 9 | public Matrix4f finalTransformation; 10 | } 11 | -------------------------------------------------------------------------------- /src/com/base/game/LookAtComponent.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.game; 18 | 19 | import com.base.engine.components.GameComponent; 20 | import com.base.engine.core.*; 21 | import com.base.engine.rendering.RenderingEngine; 22 | import com.base.engine.rendering.Shader; 23 | 24 | public class LookAtComponent extends GameComponent 25 | { 26 | private RenderingEngine m_renderingEngine; 27 | 28 | @Override 29 | public void Update(float delta) 30 | { 31 | if(m_renderingEngine != null) 32 | { 33 | Quaternion newRot = GetTransform().GetLookAtRotation(m_renderingEngine.GetMainCamera().GetTransform().GetTransformedPos(), 34 | new Vector3f(0, 1, 0)); 35 | //GetTransform().GetRot().GetUp()); 36 | 37 | GetTransform().SetRot(GetTransform().GetRot().NLerp(newRot, delta * 5.0f, true)); 38 | //GetTransform().SetRot(GetTransform().GetRot().SLerp(newRot, delta * 5.0f, true)); 39 | } 40 | } 41 | 42 | @Override 43 | public void Render(Shader shader, RenderingEngine renderingEngine) 44 | { 45 | this.m_renderingEngine = renderingEngine; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/com/base/game/Main.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.game; 18 | 19 | import com.base.engine.core.CoreEngine; 20 | 21 | public class Main 22 | { 23 | public static void main(String[] args) 24 | { 25 | CoreEngine engine = new CoreEngine(1280, 720, 144, new TestGame()); 26 | engine.CreateWindow("3D Game Engine"); 27 | engine.Start(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/com/base/game/TestGame.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2014 Benny Bobaganoosh 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.base.game; 18 | 19 | import java.io.File; 20 | 21 | import com.base.engine.components.*; 22 | import com.base.engine.core.*; 23 | import com.base.engine.rendering.*; 24 | 25 | public class TestGame extends Game 26 | { 27 | public void Init() 28 | { 29 | Mesh mesh = new Mesh("plane3.obj"); 30 | Material material2 = new Material(new Texture("bricks.jpg"), 1, 8, 31 | new Texture("bricks_normal.jpg"), new Texture("bricks_disp.png"), 0.03f, -0.5f); 32 | 33 | Material material = new Material(new Texture("bricks2.jpg"), 1, 8, 34 | new Texture("bricks2_normal.png"), new Texture("bricks2_disp.jpg"), 0.04f, -1.0f); 35 | 36 | Mesh tempMesh = new Mesh("monkey3.obj"); 37 | 38 | MeshRenderer meshRenderer = new MeshRenderer(mesh, material); 39 | 40 | GameObject planeObject = new GameObject(); 41 | planeObject.AddComponent(meshRenderer); 42 | planeObject.GetTransform().GetPos().Set(0, -1, 5); 43 | 44 | GameObject directionalLightObject = new GameObject(); 45 | DirectionalLight directionalLight = new DirectionalLight(new Vector3f(0,0,1), 0.4f); 46 | 47 | directionalLightObject.AddComponent(directionalLight); 48 | 49 | GameObject pointLightObject = new GameObject(); 50 | pointLightObject.AddComponent(new PointLight(new Vector3f(0, 1, 0), 0.4f, new Attenuation(0, 0, 1))); 51 | 52 | SpotLight spotLight = new SpotLight(new Vector3f(0,1,1), 0.4f, 53 | new Attenuation(0,0,0.1f), 0.7f); 54 | 55 | GameObject spotLightObject = new GameObject(); 56 | spotLightObject.AddComponent(spotLight); 57 | 58 | spotLightObject.GetTransform().GetPos().Set(5, 0, 5); 59 | spotLightObject.GetTransform().SetRot(new Quaternion(new Vector3f(0, 1, 0), (float) Math.toRadians(90.0f))); 60 | 61 | AddObject(planeObject); 62 | AddObject(directionalLightObject); 63 | AddObject(pointLightObject); 64 | AddObject(spotLightObject); 65 | 66 | GameObject testMesh3 = new GameObject().AddComponent(new LookAtComponent()).AddComponent(new MeshRenderer(tempMesh, material)); 67 | 68 | AddObject( 69 | //AddObject( 70 | new GameObject().AddComponent(new FreeLook(0.5f)).AddComponent(new FreeMove(10.0f)) 71 | .AddComponent(new Camera(new Matrix4f().InitPerspective((float) Math.toRadians(70.0f), 72 | (float) Window.GetWidth() / (float) Window.GetHeight(), 0.01f, 1000.0f)))); 73 | 74 | AddObject(new GameObject().AddComponent(AnimationUtil.loadAnimatedFile(new File(".\\res\\test.dae")))); 75 | 76 | testMesh3.GetTransform().GetPos().Set(5, 5, 5); 77 | testMesh3.GetTransform().SetRot(new Quaternion(new Vector3f(0, 1, 0), (float) Math.toRadians(-70.0f))); 78 | 79 | directionalLight.GetTransform().SetRot(new Quaternion(new Vector3f(1, 0, 0), (float) Math.toRadians(-45))); 80 | } 81 | } 82 | --------------------------------------------------------------------------------