public void Move(float x, float y) { Vector3 offset = new Vector3(); Vector3 right = new Vector3(1, 0, 0); Vector3 up = new Vector3(0, 1, 0); offset += x * right; offset += y * up; offset.NormalizeFast(); offset = Vector3.Multiply(offset, moveSpeed); position += offset; }
/// <summary> /// Offset the position of the camera in coordinates relative to its current orientation /// </summary> /// <param name="x">Movement along the camera ground (left/right)</param> /// <param name="y">Movement along the camera axis (forward)</param> /// <param name="z">Height to move</param> public void Move(float x, float y, float z) { Vector3 offset = new Vector3(); Vector3 forward = new Vector3((float)Math.Sin((float)Orientation.X), 0, (float)Math.Cos((float)Orientation.X)); Vector3 right = new Vector3(-forward.Z, 0, forward.X); offset += x * right; offset += y * forward; offset.Y += z; offset.NormalizeFast(); offset = Vector3.Multiply(offset, MoveSpeed); Position += offset; }
//TODO: Move to entity /// <summary> /// Returns the new position /// </summary> Vector3 Move(Vector3 position, Vector3 rotation, Vector3 movement) { Vector3 offset = new Vector3(); Vector3 forward = new Vector3((float)Math.Sin((float)rotation.X), 0, (float)Math.Cos((float)rotation.X)); Vector3 right = new Vector3(-forward.Z, 0, forward.X); offset += movement.X * right; offset += movement.Z * forward; offset.Y += movement.Y; offset.NormalizeFast(); offset = Vector3.Multiply(offset, moveSpeed); position += offset; return(position); }
/// <summary> /// This function handles the movement of the camera based on OnKeyPress() method in ACWWindow.cs /// </summary> /// <param name="x">The x axis movement value</param> /// <param name="y">The y axis movement value</param> /// <param name="z">The z axis movement value</param> public void Move(float x, float y, float z) { Vector3 offset = new Vector3(); Vector3 forward = new Vector3((float)Math.Sin((float)Orientation.X), 0, (float)Math.Cos((float)Orientation.X)); // Forward and backward movement on the x and z axis Vector3 right = new Vector3(-forward.Z, 0, forward.X); // Right and left movement on the x and z axis // Actually moves the camera using the parameter values offset += x * right; offset += y * forward; offset.Y += z; offset.NormalizeFast(); offset = Vector3.Multiply(offset, MoveSpeed); // Sets the new position of the camera based on the above calculations Position += offset; }
public void Move(float x, float y, float z) { Vector3 offset = Vector3.Zero; offset += transform.Right * x; offset += transform.Forward * z; offset.Y += y; offset.NormalizeFast(); float moveSpeed = MoveSpeed; if (EditorHelpers.KeysDown[(int)Key.ShiftLeft]) { moveSpeed *= 2; } transform.Position += Vector3.Multiply(offset, moveSpeed * MainEditor.DeltaTime); }
public Shell(Vector3 position, Vector3 cannonFacing, Vector3 cannonVelocity, float startSpeed, object shellOwner) { int segments = 8; List<Vector3> vertices = new List<Vector3>(segments + 1); //float unitradius = (float)Math.Sqrt(8); float angleStep = (float)(2 * Math.PI / segments); for (int i = 0; i < segments; i++) { vertices.Add(new Vector3((float)Math.Cos(angleStep * i) * radius, (float)Math.Sin(angleStep * i) * radius, 0)); } vertices.Add(new Vector3(radius, 0, 0)); graphics = GraphicsAspect.Create(this, vertices, position, 1, Color.White, Color.Red); // вычисляем вектор полёта снаряда - сумма импульса выстрела и собственной скорости оружия cannonFacing.NormalizeFast(); Vector3 shootVelocity = cannonFacing * startSpeed + cannonVelocity; Vector2 shootDirection = shootVelocity.Xy; shootDirection.NormalizeFast(); //physics = new PhysicsAspect(this, position, shootVelocity.Xy, startSpeed); physics = PhysicsAspect.Create(this, position, shootDirection, shootVelocity.LengthFast); bounds = BoundSetAspect.Create(this, null); BoundsAspect bound = CircleBoundsAspect.Create(bounds, position.Xy, radius); bounds.AddBound(bound); // снаряд будет быстродвижущимся объектом, для него особый алгоритм определения столкновений bounds.SetAttribute(Strings.CollisionDetectionSpeedType, Strings.CollisionDetectionSpeedTypeFast); damage = DamageAspect.Create(this, 1); //physics = new PhysicsAspect(this, position, Vector2.Zero, 0); //timer = DestroyByTimerAspect.Create(this, new TimeSpan(0, 0, 0, 2, 500)); timer = DestroyByTimerAspect.Create(this, new TimeSpan(0, 0, 0, 1, 0)); this.shellOwner = shellOwner; this.name = "shell"; MessageDispatcher.RegisterHandler(typeof(SetPosition), bounds); MessageDispatcher.RegisterHandler(typeof(SetPosition), graphics); MessageDispatcher.RegisterHandler(typeof(DestroyChildrenOf), this); MessageDispatcher.RegisterHandler(typeof(Kill), this); messageHandler.Handlers.Add(typeof(Kill), HandleKill); }
public void Move(float x, float y, float z) { var offset = new Vector3(); var forward = Orientation; var right = Vector3.Cross(forward, Up); forward.Normalize(); right.Normalize(); offset += x * right; offset += y * forward; offset.Y += z; offset.NormalizeFast(); offset = Vector3.Multiply(offset, MoveSpeed); Position += offset; }
public void Move(float x, float y, float z) { var offset = new Vector3(); var forward = Orientation.UnityDirection(); //new Vector3((float)Math.Sin(Orientation.Yaw), 0, (float)Math.Cos(Orientation.Yaw)); var right = Vector3.Cross(forward, Vector3.UnitY); //new Vector3(-forward.Z, 0, forward.X); if (forward.X == 0) { Console.WriteLine(""); } offset += x * right; offset += y * forward;; offset.Y += z; offset.NormalizeFast(); offset = Vector3.Multiply(offset, MoveSpeed); Position += offset; }
/// <summary> /// The event called when the mouse is moved /// </summary> /// <param name="source">The source of the event</param> /// <param name="args">Mouse event arguments</param> private void Viewer_MouseMoved(object source, MouseEventArgs args) { Vector2 mousePos = new Vector2(args.X, args.Y); Vector2 deltaPos = mousePos - mouseState.lastPos; if (cam.currentMode == InventorCamera.Mode.ORBIT) { float radius = Math.Min(Width, Height) * 0.3f; Vector3 diffStart = new Vector3(mouseState.dragStart.X - (Width / 2), mouseState.dragStart.Y - (Height / 2), 0); float diffLen = diffStart.LengthFast; if (diffLen > radius) //Rotating { Vector3 diffCurrent = new Vector3(args.X - (Width / 2), args.Y - (Height / 2), 0); diffCurrent.NormalizeFast(); float dir = Math.Sign((diffCurrent.X - mouseState.diffOld.X) * (diffCurrent.Y * mouseState.diffOld.Y) * (args.Y - (Height / 2))); float angle = (float)Math.Acos(Vector3.Dot(diffCurrent, mouseState.diffOld)); mouseState.diffOld = diffCurrent; cam.pose *= Matrix4.CreateRotationZ(cameraMult * dir * angle * 0.1f); } else //Orbiting { Vector3 rotationAxis = new Vector3(deltaPos.Y, deltaPos.X, 0); if (rotationAxis != Vector3.Zero) { cam.pose *= Matrix4.CreateFromAxisAngle(rotationAxis, (cameraMult * rotationAxis.LengthFast) / 100.0f); } } } else if (cam.currentMode == InventorCamera.Mode.FINE_ZOOM) { cam.offset += cameraMult * deltaPos.Y; } else if (cam.currentMode == InventorCamera.Mode.MOVE) { cam.pose *= Matrix4.CreateTranslation(cameraMult * deltaPos.X / 10f, cameraMult * -deltaPos.Y / 10f, 0); } mouseState.lastPos = mousePos; }
/// <summary> /// Moves the camera in local space /// </summary> /// <param name="x">Distance to move along the screen's x axis</param> /// <param name="y">Distance to move along the axis of the camera</param> /// <param name="z">Distance to move along the screen's y axis</param> public void Move(float x, float y, float z) { /** When the camera moves, we don't want it to move relative to the world coordinates * (like the XYZ space its position is in), but instead relative to the camera's view. * Like the view angle, this requires a bit of trigonometry. */ Vector3 offset = new Vector3(); Vector3 forward = new Vector3((float)Math.Sin((float)Orientation.X), 0, (float)Math.Cos((float)Orientation.X)); Vector3 right = new Vector3(-forward.Z, 0, forward.X); offset += x * right; offset += y * forward; offset.Y += z; offset.NormalizeFast(); offset = Vector3.Multiply(offset, MoveSpeed); Position += offset; }
public void Move(float x, float y, float z) { var tempPosition = new Vector3(position); Vector3 offset = new Vector3(); Vector3 forward = new Vector3((float)Math.Sin(orientation.X), VerticalMovement ? (float)Math.Sin(orientation.Y) : 0, (float)Math.Cos(orientation.X)); Vector3 right = new Vector3(-forward.Z, 0, forward.X); offset += x * right; offset += y * forward; offset.Y += z; offset.NormalizeFast(); offset = Vector3.Multiply(offset, MoveSpeed); position += offset; OnCameraMove(tempPosition); }
/// <summary> /// Moves the camera in the scene. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> /// <param name="speed"></param> public void Move(float x, float y, float z, float speed) { Vector3 forward = new Vector3( (float)(Math.Sin(Orientation.X)), 0, (float)(Math.Cos(Orientation.X))); Vector3 right = new Vector3( -forward.Z, 0, forward.Z); Vector3 offset = new Vector3(); offset += x * right; offset += y * forward; offset.Y += z; offset.NormalizeFast(); offset = Vector3.Multiply(offset, speed); Position += offset; }
public static Color4 GetColor(Vector3 normal, Vector3 pos, Color4 baseColor) { Color4 result = AmbientColor; normal.NormalizeFast(); foreach (DirectionalLight light in dirLights) { Vector3 dir = -light.Direction.Value; dir.NormalizeFast(); float dot = Vector3.Dot(normal, dir); if (dot < 0f) { continue; } dot *= light.Intensity.Value; result.R += light.Color.Value.R * dot * baseColor.R; result.G += light.Color.Value.G * dot * baseColor.G; result.B += light.Color.Value.B * dot * baseColor.B; } foreach (PointLight light in pointLights) { Vector3 lightPos = light.CachedPosition; /*if (Entity.Has<Transform>(light.Id)) lightPos = Entity.Get<Transform>(light.Id).Position.Value;*/ float dist = (pos - lightPos).LengthFast; float attenuation = light.Intensity.Value / (1f + (2f / light.Radius.Value) * dist + (1f / (light.Radius.Value * light.Radius.Value)) * dist * dist); result.R += light.Color.Value.R * attenuation * baseColor.R; result.G += light.Color.Value.G * attenuation * baseColor.G; result.B += light.Color.Value.B * attenuation * baseColor.B; /*Debug.DrawLater(() => { * GL.Begin(PrimitiveType.Lines); * GL.Color4(Color4.Magenta); * GL.Vertex3(pos); * GL.Vertex3(lightPos); * GL.Color4(Color4.White); * GL.End(); * });*/ } return(result); }
public Vector3 Gravity(float delta, Ray rayOrigin, float player_hitRadius, bool stopFallTrick = false) { if (stopFallTrick) { motion_fallSpeed = 0f; // stop fall } else { motion_fallSpeed += phys_freeFallAccel * delta; // free fall } Vector3 fallVector = new Vector3(-rayOrigin.Up * motion_fallSpeed * delta); float sd = CastRay(rayOrigin.Origin, Vector3.NormalizeFast(fallVector)); // when hit bottom surface if (sd <= player_hitRadius) { motion_fallSpeed = 0f; fallVector = Vector3.Zero; } return(fallVector); }
/// <summary> /// Renders a unit capsule to the given context /// </summary> public static void DrawCapsule(Camera Camera, float Size, Matrix4 bone1, Matrix4 bone2) { if (UnitCapsule == null) { UnitCapsule = new Capsule(); } var shader = ShaderManager.GetShader("Capsule"); shader.UseProgram(); Matrix4 mvp = Camera.MvpMatrix; shader.SetMatrix4x4("mvp", ref mvp); shader.SetVector4("Color", 1, 0, 0, 1); Vector3 position1 = Vector3.TransformPosition(Vector3.Zero, bone1); Vector3 position2 = Vector3.TransformPosition(Vector3.Zero, bone2); Vector3 to = position2 - position1; to.NormalizeFast(); Vector3 axis = Vector3.Cross(Vector3.UnitY, to); float omega = (float)System.Math.Acos(Vector3.Dot(Vector3.UnitY, to)); Matrix4 rotation = Matrix4.CreateFromAxisAngle(axis, omega); Matrix4 transform1 = rotation * Matrix4.CreateTranslation(position1); Matrix4 transform2 = rotation * Matrix4.CreateTranslation(position2); shader.SetMatrix4x4("transform1", ref transform1); shader.SetMatrix4x4("transform2", ref transform2); shader.SetFloat("Size", Size); GL.PointSize(5f); UnitCapsule.Draw(shader); }
public void Move(float x, float y, float z) { Vector3 offset = new Vector3(); Vector3 forward = new Vector3(-(float)System.Math.Sin(Orientation.X), -(float)System.Math.Tan(Orientation.Y), -(float)System.Math.Cos(Orientation.X)); forward.NormalizeFast(); Vector3 right = new Vector3(-forward.Z, 0, forward.X); right.NormalizeFast(); Vector3 up = new Vector3((float)System.Math.Sin(Orientation.Y), (float)System.Math.Tan(Orientation.Y), (float)System.Math.Cos(Orientation.Y)); up.NormalizeFast(); offset += x * right; offset += y * up; offset += z * forward; offset = Vector3.Multiply(offset, MoveSensitivity); Position += offset; }
/// <summary> /// /// </summary> /// <returns></returns> public List <JEntity> GenerateTrees() { Console.WriteLine("Generating Trees..."); List <JEntity> TreeEntities = new List <JEntity>(); string TreeTexturePath = JFileUtils.GetPathToResFile("Tree\\tree_texture_green_brown.png"); string TreeModelPath = JFileUtils.GetPathToResFile("Tree\\tree.obj"); JModelData TreeModelData = JObjFileLoader.LoadObj(TreeModelPath); JRawModel TreeModel = Loader.LoadToVAO(TreeModelData.Vertices, TreeModelData.TextureCoords, TreeModelData.Normals, TreeModelData.Indices); JModelTexture TreeTexture = new JModelTexture(Loader.loadTexture(TreeTexturePath)); JTexturedModel TreeTexturedModel = new JTexturedModel(TreeModel, TreeTexture); Random r = new Random(); for (int i = 0; i < 200; i++) { float posX = (float)r.NextDouble() * 800; float posZ = -(float)r.NextDouble() * 800; float posY = Terrain.GetHeightOfTerrain(posX, posZ); while (posY < WaterTile.Height) { posX = (float)r.NextDouble() * 800; posZ = -(float)r.NextDouble() * 800; posY = Terrain.GetHeightOfTerrain(posX, posZ); } Vector3 orientation = new Vector3((float)r.NextDouble(), 0, (float)r.NextDouble()); orientation.NormalizeFast(); JEntity entity = new JEntity(TreeTexturedModel, new Vector3(posX, posY, posZ), orientation, 0.25f); TreeEntities.Add(entity); } return(TreeEntities); }
public virtual bool hitTest(SSpaceMissileData missile, out Vector3 hitLocation) { var mParams = missile.parameters; float simStep = missile.parameters.simulationStep; float nextTickDist = missile.velocity.LengthFast * simStep; float testDistSq = (nextTickDist + targetObj.worldBoundingSphereRadius); testDistSq *= testDistSq; float toTargetDistSq = (targetObj.Pos - missile.position).LengthSquared; if (toTargetDistSq <= mParams.atTargetDistance * mParams.atTargetDistance) { hitLocation = missile.position; return(true); } else if (testDistSq > toTargetDistSq) { Vector3 velNorm = (missile.velocity - this.velocity); velNorm.NormalizeFast(); SSRay ray = new SSRay(missile.position, velNorm); float rayDistance = 0f; if (targetObj.PreciseIntersect(ref ray, ref rayDistance)) { if (rayDistance - nextTickDist < mParams.atTargetDistance) { hitLocation = missile.position + this.velocity * simStep + velNorm * rayDistance; return(true); } } } hitLocation = new Vector3(float.PositiveInfinity); return(false); }
public void Tick(float deltaTime) { if (!WInput.GetMouseButton(1) || !bEnableUpdates) { return; } Vector3 moveDir = Vector3.Zero; if (WInput.GetKey(System.Windows.Input.Key.W)) { moveDir -= Vector3.UnitZ; } if (WInput.GetKey(System.Windows.Input.Key.S)) { moveDir += Vector3.UnitZ; } if (WInput.GetKey(System.Windows.Input.Key.D)) { moveDir += Vector3.UnitX; } if (WInput.GetKey(System.Windows.Input.Key.A)) { moveDir -= Vector3.UnitX; } // If they're holding down the shift key adjust their FOV when they scroll, otherwise adjust move speed. MoveSpeed += WInput.MouseScrollDelta * 100 * deltaTime; MoveSpeed = WMath.Clamp(MoveSpeed, 100, 8000); if (WInput.GetMouseButton(1)) { Rotate(deltaTime, WInput.MouseDelta.X, WInput.MouseDelta.Y); } float moveSpeed = WInput.GetKey(System.Windows.Input.Key.LeftShift) ? MoveSpeed * 3f : MoveSpeed; // Make it relative to the current rotation. moveDir = Vector3.Transform(moveDir, Transform.Rotation.ToSinglePrecision()); // Do Q and E after we transform the moveDir so they're always in worldspace. if (WInput.GetKey(System.Windows.Input.Key.Q)) { moveDir -= Vector3.UnitY; } if (WInput.GetKey(System.Windows.Input.Key.E)) { moveDir += Vector3.UnitY; } // Normalize the move direction moveDir.NormalizeFast(); // Early out if we're not moving this frame. if (moveDir.LengthFast < 0.1f) { return; } Transform.Position += Vector3.Multiply(moveDir, moveSpeed * deltaTime); }
internal override void Draw(GameObject g, ref Matrix4 viewProjection, ref Matrix4 viewProjectionShadowBiased, ref Matrix4 viewProjectionShadowBiased2, HelperFrustum frustum, ref float[] lightColors, ref float[] lightTargets, ref float[] lightPositions, int lightCount, ref int lightShadow) { if (g == null || !g.HasModel || g.CurrentWorld == null || g.Opacity <= 0) { return; } g.IsInsideScreenSpace = frustum.SphereVsFrustum(g.GetCenterPointForAllHitboxes(), g.GetMaxDiameter() / 2); if (!g.IsInsideScreenSpace) { return; } GL.UseProgram(mProgramId); GL.Disable(EnableCap.Blend); lock (g) { GL.Uniform1(mUniform_BiasCoefficient, KWEngine.ShadowMapCoefficient); GL.Uniform4(mUniform_Glow, g.Glow.X, g.Glow.Y, g.Glow.Z, g.Glow.W); GL.Uniform3(mUniform_TintColor, g.Color.X, g.Color.Y, g.Color.Z); // How many lights are there? GL.Uniform1(mUniform_LightCount, lightCount); GL.Uniform4(mUniform_LightsColors, KWEngine.MAX_LIGHTS, lightColors); GL.Uniform4(mUniform_LightsTargets, KWEngine.MAX_LIGHTS, lightTargets); GL.Uniform4(mUniform_LightsPositions, KWEngine.MAX_LIGHTS, lightPositions); // Sun GL.Uniform4(mUniform_SunIntensity, g.CurrentWorld.GetSunColor()); GL.Uniform3(mUniform_SunPosition, g.CurrentWorld.GetSunPosition().X, g.CurrentWorld.GetSunPosition().Y, g.CurrentWorld.GetSunPosition().Z); Vector3 sunDirection = g.CurrentWorld.GetSunPosition() - g.CurrentWorld.GetSunTarget(); sunDirection.NormalizeFast(); GL.Uniform3(mUniform_SunDirection, ref sunDirection); GL.Uniform1(mUniform_SunAmbient, g.CurrentWorld.SunAmbientFactor); GL.Uniform1(mUniform_SunAffection, g.IsAffectedBySun ? 1 : 0); GL.Uniform1(mUniform_LightAffection, g.IsAffectedByLight ? 1 : 0); // Camera if (!CurrentWorld.IsFirstPersonMode) { GL.Uniform3(mUniform_uCameraPos, g.CurrentWorld.GetCameraPosition().X, g.CurrentWorld.GetCameraPosition().Y, g.CurrentWorld.GetCameraPosition().Z); GL.Uniform3(mUniform_uCameraDirection, g.CurrentWorld.GetCameraLookAtVector()); } else { GL.Uniform3(mUniform_uCameraPos, g.CurrentWorld.GetFirstPersonObject().Position.X, g.CurrentWorld.GetFirstPersonObject().Position.Y + g.CurrentWorld.GetFirstPersonObject().FPSEyeOffset, g.CurrentWorld.GetFirstPersonObject().Position.Z); GL.Uniform3(mUniform_uCameraDirection, HelperCamera.GetLookAtVector()); } // Upload depth texture (shadow mapping) GL.ActiveTexture(TextureUnit.Texture3); GL.BindTexture(TextureTarget.Texture2D, GLWindow.CurrentWindow.TextureShadowMap); GL.Uniform1(mUniform_TextureShadowMap, 3); try { Matrix4.Mult(ref g.ModelMatrixForRenderPass[0], ref viewProjection, out _modelViewProjection); Matrix4.Transpose(ref g.ModelMatrixForRenderPass[0], out _normalMatrix); Matrix4.Invert(ref _normalMatrix, out _normalMatrix); } catch (Exception) { _normalMatrix = g.ModelMatrixForRenderPass[0]; } GL.UniformMatrix4(mUniform_ModelMatrix, false, ref g.ModelMatrixForRenderPass[0]); GL.UniformMatrix4(mUniform_NormalMatrix, false, ref _normalMatrix); GL.UniformMatrix4(mUniform_MVP, false, ref _modelViewProjection); if (lightShadow >= 0) { Matrix4 modelViewProjectionMatrixBiased2 = g.ModelMatrixForRenderPass[0] * viewProjectionShadowBiased2; GL.ActiveTexture(TextureUnit.Texture5); GL.BindTexture(TextureTarget.Texture2D, GLWindow.CurrentWindow.TextureShadowMap2); GL.Uniform1(mUniform_TextureShadowMap2, 5); GL.Uniform1(mUniform_ShadowLightPosition, lightShadow); GL.UniformMatrix4(mUniform_MVPShadowMap2, false, ref modelViewProjectionMatrixBiased2); GL.Uniform1(mUniform_BiasCoefficient2, CurrentWorld.GetLightObjects().ElementAt(lightShadow).ShadowMapBiasCoefficient); } else { GL.Uniform1(mUniform_ShadowLightPosition, -1); GL.ActiveTexture(TextureUnit.Texture5); GL.BindTexture(TextureTarget.Texture2D, GLWindow.CurrentWindow.TextureShadowMap2); GL.Uniform1(mUniform_TextureShadowMap2, 5); } foreach (string meshName in g.Model.Meshes.Keys) { GeoMesh mesh = g.Model.Meshes[meshName]; GL.Uniform1(mUniform_SpecularPower, mesh.Material.SpecularPower); GL.Uniform1(mUniform_SpecularArea, mesh.Material.SpecularArea); // Shadow mapping Matrix4 modelViewProjectionMatrixBiased = g.ModelMatrixForRenderPass[0] * viewProjectionShadowBiased; GL.UniformMatrix4(mUniform_MVPShadowMap, false, ref modelViewProjectionMatrixBiased); GL.Uniform2(mUniform_TextureTransform, mesh.Terrain.mTexX, mesh.Terrain.mTexY); int texId = mesh.Material.TextureDiffuse.OpenGLID; if (texId > 0) { GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, texId); GL.Uniform1(mUniform_Texture, 0); GL.Uniform1(mUniform_TextureUse, 1); } else { GL.Uniform1(mUniform_TextureUse, 0); } texId = mesh.Material.TextureNormal.OpenGLID; if (texId > 0) { GL.ActiveTexture(TextureUnit.Texture1); GL.BindTexture(TextureTarget.Texture2D, texId); GL.Uniform1(mUniform_TextureNormalMap, 1); GL.Uniform1(mUniform_TextureUseNormalMap, 1); } else { GL.Uniform1(mUniform_TextureUseNormalMap, 0); } texId = mesh.Material.TextureSpecular.OpenGLID; if (texId > 0) { GL.ActiveTexture(TextureUnit.Texture2); GL.BindTexture(TextureTarget.Texture2D, texId); GL.Uniform1(mUniform_TextureSpecularMap, 2); GL.Uniform1(mUniform_TextureUseSpecularMap, 1); } else { GL.Uniform1(mUniform_TextureUseSpecularMap, 0); } // Blendmapping: if (mesh.Terrain._texBlend > 0 && mesh.Terrain._texBlend != KWEngine.TextureBlack) { GL.ActiveTexture(TextureUnit.Texture10); GL.BindTexture(TextureTarget.Texture2D, mesh.Terrain._texBlend); GL.Uniform1(mUniform_TextureBlend, 10); GL.ActiveTexture(TextureUnit.Texture11); GL.BindTexture(TextureTarget.Texture2D, mesh.Terrain._texR); GL.Uniform1(mUniform_TextureRed, 11); if (mesh.Terrain._texG > 0 && mesh.Terrain._texG != KWEngine.TextureAlpha) { GL.ActiveTexture(TextureUnit.Texture12); GL.BindTexture(TextureTarget.Texture2D, mesh.Terrain._texG); GL.Uniform1(mUniform_TextureGreen, 12); } if (mesh.Terrain._texB > 0 && mesh.Terrain._texB != KWEngine.TextureAlpha) { GL.ActiveTexture(TextureUnit.Texture13); GL.BindTexture(TextureTarget.Texture2D, mesh.Terrain._texB); GL.Uniform1(mUniform_TextureBlue, 13); } GL.Uniform1(mUniform_UseBlend, 1); } else { GL.Uniform1(mUniform_UseBlend, 0); } GL.BindVertexArray(mesh.VAO); GL.BindBuffer(BufferTarget.ElementArrayBuffer, mesh.VBOIndex); GL.DrawElements(mesh.Primitive, mesh.IndexCount, DrawElementsType.UnsignedInt, 0); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindTexture(TextureTarget.Texture2D, 0); GL.BindVertexArray(0); } } GL.UseProgram(0); }
public bool IsOutOfBounds(Vector3 obj) { Vector3 normalized = new Vector3(obj.X, obj.Y, obj.Z); normalized.NormalizeFast(); float norm = obj.LengthFast; //Vector3 abs = new Vector3(Math.Abs(obj.X), Math.Abs(obj.Y), Math.Abs(obj.Z)); if (norm > _playerLimitRange)//- Math.Abs(normalized.Z*500))//+ normalized.X * _playerLimitEccentricityX + normalized.Z * _playerLimitEccentricityZ) return true; else return false; }
void GenerateChunk(int startx) { // We create a node and position where the chunk starts Node node = _scene.CreateChild(); node.SetPosition2D(startx, 0); // We create components to render the geometries of the surface and the ground var groundComponent = node.CreateComponent <CustomGeometry>(); groundComponent.SetMaterial(_chunkmat); groundComponent.BeginGeometry(0, PrimitiveType.TRIANGLE_LIST); var surfaceComponent = node.CreateComponent <CustomGeometry>(); surfaceComponent.SetMaterial(_surfMat); surfaceComponent.BeginGeometry(0, PrimitiveType.TRIANGLE_LIST); // We initialize and add a single entry to the surface points list List <Vector2> surface = new List <Vector2>() { new Vector2(0, (float)_noise.Evaluate(startx * NoiseScaleX, 0) * NoiseScaleY ) }; // We translate the last surface extrusion point so it's local relative to the chunk we're creating _lastSurfaceExtrusion += Vector3.Left * Chunksize; // We //TODO continue float incr = SurfaceSegmentSize; for (float i = 0; i < Chunksize - float.Epsilon * 2; i += incr) { float iend = i + incr; float tlY = SampleSurface(startx + i); float trY = SampleSurface(startx + iend); float blY = tlY + Chunkheight; float brY = trY + Chunkheight; Vector3 bl = new Vector3(i, blY, -10); Vector3 tl = new Vector3(i, tlY, -10); Vector3 br = new Vector3(iend, brY, -10); Vector3 tr = new Vector3(iend, trY, -10); //phys surface.Add(new Vector2(tr)); //decor CreateDecor(tr + Vector3.Right * startx, tl - tr); //surface visual Vector2 startV = Vector2.UnitX * (i / Chunksize) * SurfaceRepeatPerChunk; Vector2 endV = Vector2.UnitX * (iend / Chunksize * SurfaceRepeatPerChunk); //bl surfaceComponent.DefineVertex(_lastSurfaceExtrusion); surfaceComponent.DefineTexCoord(startV); //tl surfaceComponent.DefineVertex(tl); surfaceComponent.DefineTexCoord(startV - Vector2.UnitY); //tr surfaceComponent.DefineVertex(tr); surfaceComponent.DefineTexCoord(-Vector2.UnitY + endV); //bl surfaceComponent.DefineVertex(_lastSurfaceExtrusion); surfaceComponent.DefineTexCoord(startV); //tr surfaceComponent.DefineVertex(tr); surfaceComponent.DefineTexCoord(-Vector2.UnitY + endV); //br _lastSurfaceExtrusion = tr + Quaternion.FromAxisAngle(Vector3.Back, 90) * Vector3.NormalizeFast(tr - tl); surfaceComponent.DefineVertex(_lastSurfaceExtrusion); surfaceComponent.DefineTexCoord(endV); //ground //bl groundComponent.DefineVertex(bl); groundComponent.DefineTexCoord(new Vector2(bl / Chunksize)); //tl groundComponent.DefineVertex(tl); groundComponent.DefineTexCoord(new Vector2(tl / Chunksize)); //tr groundComponent.DefineVertex(tr); groundComponent.DefineTexCoord(new Vector2(tr / Chunksize)); //bl groundComponent.DefineVertex(bl); groundComponent.DefineTexCoord(new Vector2(bl / Chunksize)); //tr groundComponent.DefineVertex(tr); groundComponent.DefineTexCoord(new Vector2(tr / Chunksize)); //br groundComponent.DefineVertex(br); groundComponent.DefineTexCoord(new Vector2(br / Chunksize)); } surfaceComponent.Commit(); groundComponent.Commit(); CollisionChain2D col = node.CreateComponent <CollisionChain2D>(); col.SetLoop(false); col.SetFriction(10); col.SetVertexCount((uint)surface.Count + 1); _chunks.Add(col); //Vector3 smoother = Quaternion.FromRotationTo(Vector3.Left, new Vector3(-1,-.3f,0)) * new Vector3(surface[0] - surface[1]); //col.SetVertex(0,surface[0] + new Vector2(smoother)); Vector2 smoother = new Vector2(-incr * .5f, (float)_noise.Evaluate((startx - incr * .5f) * NoiseScaleX, 0) * NoiseScaleY - 0.005f); col.SetVertex(0, smoother); uint c2 = 0; foreach (Vector2 surfpoint in surface) { col.SetVertex(++c2, new Vector2(surfpoint.X, surfpoint.Y)); } node.CreateComponent <RigidBody2D>().SetBodyType(BodyType2D.BT_STATIC); }
/// <summary> /// Applies Gram-Schmitt Ortho-normalization to the given two input Vectro3 objects. /// </summary> /// <param name="vec1">The first Vector3 objects to be ortho-normalized</param> /// <param name="vec2">The secound Vector3 objects to be ortho-normalized</param> public static void OrthoNormalize(ref Vector3 vec1, ref Vector3 vec2) { vec1.NormalizeFast(); vec2 = Vector3.Subtract(vec2, ProjectAndCreate(vec2, vec1)); vec2.NormalizeFast(); }
private void MoveDreadnaught() { // ORIENTATION if (InputManager.Mouse.RightClickdown) //Follow cursor position when right click is down or set new orientation if just right click { _savedPlayerCursorPosition = new Vector3(_playerCursor.Position.X, _playerCursor.Position.Y, _playerCursor.Position.Z); } _dreadnaught.AlignTo(_savedPlayerCursorPosition); // POSITION LIMIT CHECK bool commandsEnabled = true; Vector3 command = new Vector3(0, 0, 0); Vector3 repelForce = new Vector3(0, 0, 0); if (!IsOutOfBounds(_dreadnaught.Position)) //if dreadnaught is in bounds, enable controls (player can accelerate spaceship) { commandsEnabled = true; } else { //If out of bounds, disable controls and apply a small "force" towards the origin, until spaceship changes direction if (Vector3.Dot(_dreadnaught.Velocity, _dreadnaught.Position) > 0) { commandsEnabled = false; repelForce = new Vector3(-_dreadnaught.Position.X, -_dreadnaught.Position.Y, -_dreadnaught.Position.Z); repelForce.NormalizeFast(); }//If out of bounds but spaceship has changed direction, enable commands (to allow player to get back) else { commandsEnabled = true; } } // USER COMMANDS CATCH if (commandsEnabled) { if (InputManager.Keyboard.Sdown) if (InputManager.Keyboard.ShiftLeftdown) _camera.Move(_camera.Down, _camera.PositionSpeed * 100); else command.Z -= 1; if (InputManager.Keyboard.Wdown) if (InputManager.Keyboard.ShiftLeftdown) _camera.Move(_camera.Up, _camera.PositionSpeed * 100); else command.Z += 1; if (InputManager.Keyboard.Adown) if (InputManager.Keyboard.ShiftLeftdown) _camera.Move(_camera.Left, _camera.PositionSpeed * 100); else command.X += 1; if (InputManager.Keyboard.Ddown) if (InputManager.Keyboard.ShiftLeftdown) _camera.Move(_camera.Left, _camera.PositionSpeed * 100); else command.X -= 1; } // POSITION command.NormalizeFast(); command += repelForce; //apply repelforce (if any) Vector3 nextVelocity = _dreadnaught.Velocity + (command * _dreadnaught.MaxAcceleration * Game.DeltaTime); //SPEED LAW if (Math.Abs(nextVelocity.X) > _dreadnaught.MaxSpeed) nextVelocity.X = _dreadnaught.Velocity.X; //limit max speed on X if (Math.Abs(nextVelocity.Z) > _dreadnaught.MaxSpeed) nextVelocity.Z = _dreadnaught.Velocity.Z; //limit max speed on Z _dreadnaught.Velocity = nextVelocity; //new speed vector apply _dreadnaught.Position = _dreadnaught.Position + _dreadnaught.Velocity; //POSITION LAW }
private static Intersection TestIntersectionSphereConvexHull(Hitbox caller, Hitbox collider, Vector3 offsetCaller) { float mtvDistance = float.MaxValue; float mtvDirection = 1; float mtvDistanceUp = float.MaxValue; float mtvDirectionUp = 1; MTVTemp = Vector3.Zero; MTVTempUp = Vector3.Zero; float sphereRadius = caller.Owner.Scale.X / 2; int bestCollisionIndex = 0; float shape1Min, shape1Max, shape2Min, shape2Max; for (int i = 0; i < collider.mNormals.Length; i++) { shape1Min = Vector3.Dot((caller.GetCenter() + offsetCaller) - collider.mNormals[i] * sphereRadius, collider.mNormals[i]); shape1Max = Vector3.Dot((caller.GetCenter() + offsetCaller) + collider.mNormals[i] * sphereRadius, collider.mNormals[i]); SatTest(ref collider.mNormals[i], ref collider.mVertices, out shape2Min, out shape2Max, ref ZeroVector); if (!Overlaps(shape1Min, shape1Max, shape2Min, shape2Max)) { return(null); } else { bool m = CalculateOverlap(ref collider.mNormals[i], ref shape1Min, ref shape1Max, ref shape2Min, ref shape2Max, ref mtvDistance, ref mtvDistanceUp, ref MTVTemp, ref MTVTempUp, ref mtvDirection, ref mtvDirectionUp, ref caller.mCenter, ref collider.mCenter, ref offsetCaller); if (m) { bestCollisionIndex = i; } } } Vector3 hullToSphereDirectionVector = Vector3.NormalizeFast((caller.GetCenter() + offsetCaller) - collider.GetCenter()); shape1Min = Vector3.Dot((caller.GetCenter() + offsetCaller) - hullToSphereDirectionVector * sphereRadius, hullToSphereDirectionVector); shape1Max = Vector3.Dot((caller.GetCenter() + offsetCaller) + hullToSphereDirectionVector * sphereRadius, hullToSphereDirectionVector); SatTest(ref hullToSphereDirectionVector, ref collider.mVertices, out shape2Min, out shape2Max, ref ZeroVector); if (!Overlaps(shape1Min, shape1Max, shape2Min, shape2Max)) { return(null); } else { bool m = CalculateOverlap(ref hullToSphereDirectionVector, ref shape1Min, ref shape1Max, ref shape2Min, ref shape2Max, ref mtvDistance, ref mtvDistanceUp, ref MTVTemp, ref MTVTempUp, ref mtvDirection, ref mtvDirectionUp, ref caller.mCenter, ref collider.mCenter, ref offsetCaller); if (m) { bestCollisionIndex = -100; } } if (MTVTemp == Vector3.Zero) { return(null); } Intersection o = new Intersection(collider.Owner, caller, collider, MTVTemp, MTVTempUp, collider.mMesh.Name, bestCollisionIndex == -100 ? hullToSphereDirectionVector : collider.mNormals[bestCollisionIndex]); return(o); }
/// <summary> /// Reflektiert den eingehenden Vektor 'directionIn' am Ebenenvektor 'surfaceNormal' /// </summary> /// <param name="directionIn">Eingehender Vektor</param> /// <param name="surfaceNormal">Ebenenvektor</param> /// <returns>Reflektierter Vektor</returns> public static Vector3 ReflectVector(Vector3 directionIn, Vector3 surfaceNormal) { Vector3 reflectedVector = directionIn - 2 * Vector3.Dot(directionIn, surfaceNormal) * surfaceNormal; return(Vector3.NormalizeFast(reflectedVector)); }
private static Intersection TestIntersectionConvexHullSphere(Hitbox caller, Hitbox collider, Vector3 offsetCaller) { float mtvDistance = float.MaxValue; float mtvDirection = 1; float mtvDistanceUp = float.MaxValue; float mtvDirectionUp = 1; MTVTemp = Vector3.Zero; MTVTempUp = Vector3.Zero; bool useSphereNormal = false; float sphereRadius = collider.Owner.Scale.X / 2; Vector3 collisionSurfaceNormal = new Vector3(0, 0, 0); float shape1Min, shape1Max, shape2Min, shape2Max; for (int i = 0; i < caller.mNormals.Length; i++) { SatTest(ref caller.mNormals[i], ref caller.mVertices, out shape1Min, out shape1Max, ref ZeroVector); shape2Min = Vector3.Dot(collider.GetCenter() - caller.mNormals[i] * sphereRadius, caller.mNormals[i]); shape2Max = Vector3.Dot(collider.GetCenter() + caller.mNormals[i] * sphereRadius, caller.mNormals[i]); if (!Overlaps(shape1Min, shape1Max, shape2Min, shape2Max)) { return(null); } else { bool m = CalculateOverlap(ref caller.mNormals[i], ref shape1Min, ref shape1Max, ref shape2Min, ref shape2Max, ref mtvDistance, ref mtvDistanceUp, ref MTVTemp, ref MTVTempUp, ref mtvDirection, ref mtvDirectionUp, ref caller.mCenter, ref collider.mCenter, ref offsetCaller); if (m) { collisionSurfaceNormal = Vector3.NormalizeFast((caller.mCenter + offsetCaller) - collider.mCenter); } } } //collider is sphere: Vector3 sphereToHullDirectionVector = Vector3.NormalizeFast((caller.GetCenter() + offsetCaller) - collider.GetCenter()); SatTest(ref sphereToHullDirectionVector, ref caller.mVertices, out shape1Min, out shape1Max, ref offsetCaller); shape2Min = Vector3.Dot(collider.GetCenter() - sphereToHullDirectionVector * sphereRadius, sphereToHullDirectionVector); shape2Max = Vector3.Dot(collider.GetCenter() + sphereToHullDirectionVector * sphereRadius, sphereToHullDirectionVector); if (!Overlaps(shape1Min, shape1Max, shape2Min, shape2Max)) { return(null); } else { bool m = CalculateOverlap(ref sphereToHullDirectionVector, ref shape1Min, ref shape1Max, ref shape2Min, ref shape2Max, ref mtvDistance, ref mtvDistanceUp, ref MTVTemp, ref MTVTempUp, ref mtvDirection, ref mtvDirectionUp, ref caller.mCenter, ref collider.mCenter, ref offsetCaller); if (m) { useSphereNormal = true; } } if (MTVTemp == Vector3.Zero) { return(null); } Intersection o = new Intersection(collider.Owner, caller, collider, MTVTemp, MTVTempUp, collider.mMesh.Name, useSphereNormal ? sphereToHullDirectionVector : collisionSurfaceNormal); return(o); }
public override void Act(KeyboardState ks, MouseState ms, float deltaTimeFactor) { bool runs = false; if (CurrentWorld.IsFirstPersonMode && CurrentWorld.GetFirstPersonObject().Equals(this)) { float forward = 0; float strafe = 0; if (ks[Key.A]) { strafe -= 1; runs = true; } if (ks[Key.D]) { strafe += 1; runs = true; } if (ks[Key.W]) { forward += 1; runs = true; } if (ks[Key.S]) { forward -= 1; runs = true; } MoveFPSCamera(ms); MoveAndStrafeFirstPerson(forward, strafe, 0.1f * deltaTimeFactor); FPSEyeOffset = 5; if (ks[Key.Q]) { MoveOffset(0, -0.2f, 0); } if (ks[Key.E]) { MoveOffset(0, +0.2f, 0); } } else { TurnTowardsXZ(GetMouseIntersectionPoint(ms, Plane.Y)); Vector3 cameraLookAt = GetCameraLookAtVector(); cameraLookAt.Y = 0; cameraLookAt.NormalizeFast(); Vector3 strafe = HelperRotation.RotateVector(cameraLookAt, 90, Plane.Y); if (ks[Key.A]) { MoveAlongVector(strafe, 0.1f * deltaTimeFactor); runs = true; } if (ks[Key.D]) { MoveAlongVector(strafe, -0.1f * deltaTimeFactor); runs = true; } if (ks[Key.W]) { MoveAlongVector(cameraLookAt, 0.1f * deltaTimeFactor); runs = true; } if (ks[Key.S]) { MoveAlongVector(cameraLookAt, -0.1f * deltaTimeFactor); runs = true; } if (ks[Key.T]) { MoveOffset(0, 0.2f * deltaTimeFactor, 0); } if (ks[Key.Q]) { _height += 0.5f; } if (ks[Key.E]) { _height -= 0.5f; } } if (IsMouseCursorInsideMyHitbox(ms)) { SetColorOutline(0, 1, 0, 0.2f); } else { SetColorOutline(0, 1, 0, 0); } /* * if (ms.LeftButton == ButtonState.Pressed) * { * GameObject o = PickGameObject(ms); * Console.WriteLine(o); * } */ MoveOffset(0, -0.1f * deltaTimeFactor, 0); List <Intersection> intersections = GetIntersections(); foreach (Intersection i in intersections) { if (i.IsTerrain) { SetPosition(Position.X, i.HeightOnTerrainSuggested, Position.Z); } else { Position += i.MTV; } } AdjustFlashlight(); AdjustAnimation(runs, deltaTimeFactor); Vector3 camPos = this.Position + new Vector3(50, _height, 50); camPos.Y = _height; CurrentWorld.SetCameraPosition(camPos); CurrentWorld.SetCameraTarget(Position.X, 0, Position.Z); }
private void UpdateCameraLookAtVector() { _cameraLookAt = _cameraTarget - _cameraPosition; _cameraLookAt.NormalizeFast(); }
internal override void PhysicalUpdate(double deltaTime) { var v = rigidBody.BulletRigidBody.LinearVelocity; if (Math.Sqrt(v.X * v.X + v.Z * v.Z) > LinearVelocityLimitXZ) { var vxz = new Vector3(v.X, 0.0f, v.Z); vxz.NormalizeFast(); vxz *= LinearVelocityLimitXZ; v.X = vxz.X; v.Z = vxz.Z; } if (Math.Abs(v.Y) > LinearVelocityLimitY) { v.Y = LinearVelocityLimitY; } rigidBody.BulletRigidBody.LinearVelocity = v; if (Kinematic || (FreezePosition && FreezeRotation)) { rigidBody.BulletRigidBody.WorldTransform = GameObject.Transform.WorldTransform; } else if (!FreezePosition && !FreezeRotation) { GameObject.Transform.WorldTransform = /*Matrix4.CreateTranslation(-centerofmass) */ rigidBody.BulletRigidBody.WorldTransform; } else if (FreezePosition && !FreezeRotation) { var m = GameObject.Transform.WorldTransform; var pos = m.ExtractTranslation(); var scale = m.ExtractScale(); var mat = rigidBody.BulletRigidBody.WorldTransform; var rot = mat.ExtractEulerRotation(); if (FreezePosition) { mat.M41 = pos.X; mat.M42 = pos.Y; mat.M43 = pos.Z; } rigidBody.BulletRigidBody.WorldTransform = mat; GameObject.Transform.WorldTransform = MatrixHelper.CreateTransform(ref pos, ref rot, ref scale); } else { var m = GameObject.Transform.WorldTransform; var pos = m.ExtractTranslation(); var rot = m.ExtractEulerRotation(); var scale = m.ExtractScale(); var mm = rigidBody.BulletRigidBody.WorldTransform; var p = mm.ExtractTranslation(); var s = mm.ExtractScale(); Matrix4 mat; MatrixHelper.CreateTransform(ref p, ref rot, ref s, out mat); rigidBody.BulletRigidBody.WorldTransform = mat; GameObject.Transform.WorldTransform = /*Matrix4.CreateTranslation(-centerofmass)*/ MatrixHelper.CreateTransform(ref p, ref rot, ref scale); } }
internal static void PrepareLightsForRenderPass(List <LightObject> lights, ref float[] colors, ref float[] targets, ref float[] positions, ref float[] meta, ref float[] nearFar, ref int count) { int countTemp = 0; IEnumerator <LightObject> enumerator = lights.GetEnumerator(); enumerator.Reset(); Vector3 viewDirection; Vector3 camPosition; if (KWEngine.CurrentWorld.IsFirstPersonMode) { viewDirection = HelperCamera.GetLookAtVector(); camPosition = KWEngine.CurrentWorld.GetFirstPersonObject().Position; } else { viewDirection = KWEngine.CurrentWorld.GetCameraLookAtVector(); camPosition = KWEngine.CurrentWorld.GetCameraPosition(); } for (int i = 0, twocounter = 0, threecounter = 0, arraycounter = 0; i < lights.Count; i++) { bool isInFrustum = true; enumerator.MoveNext(); LightObject l = enumerator.Current; Vector3 cameraToLight = Vector3.NormalizeFast(l.Position - camPosition); float dotProductViewAndLight = Vector3.Dot(viewDirection, cameraToLight); if (dotProductViewAndLight < -0.125f && (camPosition - l.Position).LengthFast > (l.Type != LightType.Sun ? l._zFar * 5 : (KWEngine.CurrentWorld.ZFar * 5))) { isInFrustum = false; } if (isInFrustum) { colors[arraycounter + 0] = l.Color.X; colors[arraycounter + 1] = l.Color.Y; colors[arraycounter + 2] = l.Color.Z; colors[arraycounter + 3] = l.Color.W; // Intensity of color targets[arraycounter + 0] = l.Target.X; targets[arraycounter + 1] = l.Target.Y; targets[arraycounter + 2] = l.Target.Z; if (l.Type == LightType.Point) { targets[arraycounter + 3] = 0; // Point } else if (l.Type == LightType.Directional) { targets[arraycounter + 3] = 1; // Directional } else { targets[arraycounter + 3] = -1; // Sun } positions[arraycounter + 0] = l.Position.X; positions[arraycounter + 1] = l.Position.Y; positions[arraycounter + 2] = l.Position.Z; positions[arraycounter + 3] = l._zFar; meta[threecounter] = l._shadowMapBiasCoefficient; meta[threecounter + 1] = l.IsShadowCaster ? 1 : 0; meta[threecounter + 2] = l._shadowHardness; nearFar[twocounter] = l._zNear; nearFar[twocounter + 1] = l._zFar; countTemp++; arraycounter += 4; threecounter += 3; twocounter += 2; } } count = countTemp; }
internal static List <Vector3> ClipFaces(Hitbox caller, Hitbox collider) { List <Vector3> callerVertices = new List <Vector3>(caller.mVertices); List <Vector3> collisionVolumeVertices = new List <Vector3>(); // Clip caller against collider faces: for (int colliderFaceIndex = 0; colliderFaceIndex < collider.mMesh.Faces.Length; colliderFaceIndex++) { GeoMeshFace colliderClippingFace = collider.mMesh.Faces[colliderFaceIndex]; Vector3 colliderClippingFaceVertex = collider.mVertices[colliderClippingFace.Vertices[0]]; Vector3 colliderClippingFaceNormal = colliderClippingFace.Flip ? collider.mNormals[colliderClippingFace.Normal] : -collider.mNormals[colliderClippingFace.Normal]; for (int callerVertexIndex = 0; callerVertexIndex < callerVertices.Count; callerVertexIndex++) { Vector3 callerVertex1 = callerVertices[callerVertexIndex]; Vector3 callerVertex2 = callerVertices[(callerVertexIndex + 1) % callerVertices.Count]; Vector3 lineDirection = Vector3.NormalizeFast(callerVertex2 - callerVertex1); bool callerVertex1InsideRegion = HelperIntersection.IsInFrontOfPlane(ref callerVertex1, ref colliderClippingFaceNormal, ref colliderClippingFaceVertex); bool callerVertex2InsideRegion = HelperIntersection.IsInFrontOfPlane(ref callerVertex2, ref colliderClippingFaceNormal, ref colliderClippingFaceVertex); if (callerVertex1InsideRegion) { if (callerVertex2InsideRegion) { if (!collisionVolumeVertices.Contains(callerVertex2)) { collisionVolumeVertices.Add(callerVertex2); } } else { Vector3?clippedVertex = ClipLineToPlane(ref callerVertex2, ref lineDirection, ref colliderClippingFaceVertex, ref colliderClippingFaceNormal); if (clippedVertex != null && !collisionVolumeVertices.Contains(clippedVertex.Value)) { collisionVolumeVertices.Add(clippedVertex.Value); } } } else { if (callerVertex2InsideRegion) { Vector3?clippedVertex = ClipLineToPlane(ref callerVertex1, ref lineDirection, ref colliderClippingFaceVertex, ref colliderClippingFaceNormal); if (clippedVertex != null && !collisionVolumeVertices.Contains(clippedVertex.Value)) { collisionVolumeVertices.Add(clippedVertex.Value); } if (!collisionVolumeVertices.Contains(callerVertex2)) { collisionVolumeVertices.Add(callerVertex2); } } } } callerVertices.Clear(); for (int i = 0; i < collisionVolumeVertices.Count; i++) { callerVertices.Add(collisionVolumeVertices[i]); } collisionVolumeVertices.Clear(); } return(callerVertices); }
internal override void Draw(GameObject g, ref Matrix4 viewProjection, ref Matrix4 viewProjectionShadowBiased, ref Matrix4 viewProjectionShadowBiased2, HelperFrustum frustum, ref float[] lightColors, ref float[] lightTargets, ref float[] lightPositions, int lightCount, ref int lightShadow) { if (g == null || !g.HasModel || g.CurrentWorld == null || g.Opacity <= 0) { return; } g.IsInsideScreenSpace = frustum.VolumeVsFrustum(g.GetCenterPointForAllHitboxes(), g.GetMaxDimensions().X, g.GetMaxDimensions().Y, g.GetMaxDimensions().Z); if (!g.IsInsideScreenSpace) { return; } GL.UseProgram(mProgramId); lock (g) { GL.Uniform1(mUniform_BiasCoefficient, KWEngine.ShadowMapCoefficient); GL.Uniform4(mUniform_Glow, g.Glow); GL.Uniform4(mUniform_Outline, g.ColorOutline); GL.Uniform3(mUniform_TintColor, g.Color); // How many lights are there? GL.Uniform1(mUniform_LightCount, lightCount); GL.Uniform4(mUniform_LightsColors, KWEngine.MAX_LIGHTS, lightColors); GL.Uniform4(mUniform_LightsTargets, KWEngine.MAX_LIGHTS, lightTargets); GL.Uniform4(mUniform_LightsPositions, KWEngine.MAX_LIGHTS, lightPositions); // Sun GL.Uniform4(mUniform_SunIntensity, g.CurrentWorld.GetSunColor()); GL.Uniform3(mUniform_SunPosition, g.CurrentWorld.GetSunPosition().X, g.CurrentWorld.GetSunPosition().Y, g.CurrentWorld.GetSunPosition().Z); Vector3 sunDirection = g.CurrentWorld.GetSunPosition() - g.CurrentWorld.GetSunTarget(); sunDirection.NormalizeFast(); GL.Uniform3(mUniform_SunDirection, ref sunDirection); GL.Uniform1(mUniform_SunAmbient, g.CurrentWorld.SunAmbientFactor); GL.Uniform1(mUniform_SunAffection, g.IsAffectedBySun ? 1 : 0); GL.Uniform1(mUniform_LightAffection, g.IsAffectedByLight ? 1 : 0); // Camera if (!CurrentWorld.IsFirstPersonMode) { GL.Uniform3(mUniform_uCameraPos, g.CurrentWorld.GetCameraPosition().X, g.CurrentWorld.GetCameraPosition().Y, g.CurrentWorld.GetCameraPosition().Z); GL.Uniform3(mUniform_uCameraDirection, g.CurrentWorld.GetCameraLookAtVector()); } else { GL.Uniform3(mUniform_uCameraPos, g.CurrentWorld.GetFirstPersonObject().Position.X, g.CurrentWorld.GetFirstPersonObject().Position.Y + g.CurrentWorld.GetFirstPersonObject().FPSEyeOffset, g.CurrentWorld.GetFirstPersonObject().Position.Z); GL.Uniform3(mUniform_uCameraDirection, HelperCamera.GetLookAtVector()); } // Upload depth texture (shadow mapping) GL.ActiveTexture(TextureUnit.Texture3); GL.BindTexture(TextureTarget.Texture2D, GLWindow.CurrentWindow.TextureShadowMap); GL.Uniform1(mUniform_TextureShadowMap, 3); if (lightShadow >= 0) { GL.ActiveTexture(TextureUnit.Texture5); GL.BindTexture(TextureTarget.Texture2D, GLWindow.CurrentWindow.TextureShadowMap2); GL.Uniform1(mUniform_TextureShadowMap2, 5); GL.Uniform1(mUniform_ShadowLightPosition, lightShadow); GL.Uniform1(mUniform_BiasCoefficient2, CurrentWorld.GetLightObjects().ElementAt(lightShadow).ShadowMapBiasCoefficient); } else { GL.ActiveTexture(TextureUnit.Texture5); GL.BindTexture(TextureTarget.Texture2D, GLWindow.CurrentWindow.TextureShadowMap2); GL.Uniform1(mUniform_TextureShadowMap2, 5); GL.Uniform1(mUniform_ShadowLightPosition, -1); } int index = 0; foreach (string meshName in g.Model.Meshes.Keys) { if (g._cubeModel is GeoModelCube6) { index = 0; } // Matrices: try { Matrix4.Mult(ref g.ModelMatrixForRenderPass[index], ref viewProjection, out _modelViewProjection); Matrix4.Transpose(ref g.ModelMatrixForRenderPass[index], out _normalMatrix); Matrix4.Invert(ref _normalMatrix, out _normalMatrix); } catch (Exception) { continue; } GL.UniformMatrix4(mUniform_ModelMatrix, false, ref g.ModelMatrixForRenderPass[index]); GL.UniformMatrix4(mUniform_NormalMatrix, false, ref _normalMatrix); GL.UniformMatrix4(mUniform_MVP, false, ref _modelViewProjection); // Shadow mapping Matrix4 modelViewProjectionMatrixBiased = g.ModelMatrixForRenderPass[index] * viewProjectionShadowBiased; GL.UniformMatrix4(mUniform_MVPShadowMap, false, ref modelViewProjectionMatrixBiased); if (lightShadow >= 0) { Matrix4 modelViewProjectionMatrixBiased2 = g.ModelMatrixForRenderPass[index] * viewProjectionShadowBiased2; GL.UniformMatrix4(mUniform_MVPShadowMap2, false, ref modelViewProjectionMatrixBiased2); } index++; GL.Disable(EnableCap.Blend); GeoMesh mesh = g.Model.Meshes[meshName]; if (mesh.Material.Opacity <= 0) { continue; } if (mesh.Material.Opacity < 1 || g.Opacity < 1) { GL.Enable(EnableCap.Blend); } if (g.Opacity < mesh.Material.Opacity) { GL.Uniform1(mUniform_Opacity, g.Opacity); } else { GL.Uniform1(mUniform_Opacity, mesh.Material.Opacity); } Dictionary <GameObject.Override, object> overrides = null; if (g._overrides.ContainsKey(mesh.Name)) { overrides = g._overrides[mesh.Name]; } if (mesh.BoneNames.Count > 0 && g.AnimationID >= 0 && g.Model.Animations != null && g.Model.Animations.Count > 0) { GL.Uniform1(mUniform_UseAnimations, 1); for (int i = 0; i < g.BoneTranslationMatrices[meshName].Length; i++) { Matrix4 tmp = g.BoneTranslationMatrices[meshName][i]; GL.UniformMatrix4(mUniform_BoneTransforms + i, false, ref tmp); } } else { GL.Uniform1(mUniform_UseAnimations, 0); } if (g._cubeModel != null) { GL.Uniform1(mUniform_SpecularPower, g._cubeModel.SpecularPower); GL.Uniform1(mUniform_SpecularArea, g._cubeModel.SpecularArea); } else { if (overrides == null || overrides.Count == 0) { GL.Uniform1(mUniform_SpecularPower, mesh.Material.SpecularPower); } else { bool found = overrides.TryGetValue(GameObject.Override.SpecularPower, out object value); if (found) { GL.Uniform1(mUniform_SpecularPower, (float)value); } else { GL.Uniform1(mUniform_SpecularPower, mesh.Material.SpecularPower); } } if (overrides == null || overrides.Count == 0) { GL.Uniform1(mUniform_SpecularArea, mesh.Material.SpecularArea); } else { bool found = overrides.TryGetValue(GameObject.Override.SpecularArea, out object value); if (found) { GL.Uniform1(mUniform_SpecularArea, (float)value); } else { GL.Uniform1(mUniform_SpecularArea, mesh.Material.SpecularArea); } } } if (g._cubeModel != null) { UploadMaterialForKWCube(g._cubeModel, mesh, g); GL.Uniform1(mUniform_TextureUseLightMap, 0); } else { if (mesh.Material.TextureLight.OpenGLID > 0) { GL.ActiveTexture(TextureUnit.Texture8); GL.BindTexture(TextureTarget.Texture2D, mesh.Material.TextureLight.OpenGLID); GL.Uniform1(mUniform_TextureLightMap, 8); GL.Uniform1(mUniform_TextureUseLightMap, 1); } else { GL.Uniform1(mUniform_TextureUseLightMap, 0); } bool found = false; object overrideValue = null; if (overrides != null && overrides.Count > 0) { found = overrides.TryGetValue(GameObject.Override.TextureTransform, out overrideValue); } if (found) { Vector2 uvTransform = (Vector2)overrideValue; GL.Uniform2(mUniform_TextureTransform, uvTransform.X, uvTransform.Y); } else { GL.Uniform2(mUniform_TextureTransform, mesh.Material.TextureDiffuse.UVTransform.X, mesh.Material.TextureDiffuse.UVTransform.Y); } // Diffuse texture: overrideValue = null; found = false; int texId = -1; if (overrides != null && overrides.Count > 0) { found = overrides.TryGetValue(GameObject.Override.TextureDiffuse, out overrideValue); } if (found) { texId = ((GeoTexture)overrideValue).OpenGLID; } else { texId = mesh.Material.TextureDiffuse.OpenGLID; } if (texId > 0) { GL.ActiveTexture(TextureUnit.Texture0); GL.BindTexture(TextureTarget.Texture2D, texId); GL.Uniform1(mUniform_Texture, 0); GL.Uniform1(mUniform_TextureUse, 1); GL.Uniform3(mUniform_BaseColor, 1f, 1f, 1f); } else { GL.Uniform1(mUniform_TextureUse, 0); GL.Uniform3(mUniform_BaseColor, mesh.Material.ColorDiffuse.X, mesh.Material.ColorDiffuse.Y, mesh.Material.ColorDiffuse.Z); } overrideValue = null; found = false; texId = -1; if (overrides != null && overrides.Count > 0) { found = overrides.TryGetValue(GameObject.Override.TextureNormal, out overrideValue); } if (found) { texId = ((GeoTexture)overrideValue).OpenGLID; } else { texId = mesh.Material.TextureNormal.OpenGLID; } if (texId > 0) { GL.ActiveTexture(TextureUnit.Texture1); GL.BindTexture(TextureTarget.Texture2D, texId); GL.Uniform1(mUniform_TextureNormalMap, 1); GL.Uniform1(mUniform_TextureUseNormalMap, 1); } else { GL.Uniform1(mUniform_TextureUseNormalMap, 0); } overrideValue = null; found = false; texId = -1; if (overrides != null) { found = overrides.TryGetValue(GameObject.Override.TextureSpecular, out overrideValue); } if (found) { texId = ((GeoTexture)overrideValue).OpenGLID; } else { texId = mesh.Material.TextureSpecular.OpenGLID; } if (texId > 0) { GL.ActiveTexture(TextureUnit.Texture2); GL.BindTexture(TextureTarget.Texture2D, texId); GL.Uniform1(mUniform_TextureSpecularMap, 2); GL.Uniform1(mUniform_TextureUseSpecularMap, 1); if (!found && mesh.Material.TextureSpecularIsRoughness) { GL.Uniform1(mUniform_TextureSpecularIsRoughness, mesh.Material.TextureSpecularIsRoughness ? 1 : 0); } else { GL.Uniform1(mUniform_TextureSpecularIsRoughness, 0); } } else { GL.Uniform1(mUniform_TextureUseSpecularMap, 0); GL.Uniform1(mUniform_TextureSpecularIsRoughness, 0); } if (mesh.Material.TextureEmissive.OpenGLID > 0) { GL.ActiveTexture(TextureUnit.Texture4); GL.BindTexture(TextureTarget.Texture2D, mesh.Material.TextureEmissive.OpenGLID); GL.Uniform1(mUniform_TextureEmissiveMap, 4); GL.Uniform1(mUniform_TextureUseEmissiveMap, 1); } else { GL.Uniform1(mUniform_TextureUseEmissiveMap, 0); } if (g.ColorEmissive.W > 0) { GL.Uniform4(mUniform_EmissiveColor, g.ColorEmissive); } else { GL.Uniform4(mUniform_EmissiveColor, mesh.Material.ColorEmissive); } } GL.BindVertexArray(mesh.VAO); GL.BindBuffer(BufferTarget.ElementArrayBuffer, mesh.VBOIndex); GL.DrawElements(mesh.Primitive, mesh.IndexCount, DrawElementsType.UnsignedInt, 0); //HelperGL.CheckGLErrors(); GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0); GL.BindVertexArray(0); GL.BindTexture(TextureTarget.Texture2D, 0); } } GL.BindTexture(TextureTarget.Texture2D, 0); GL.UseProgram(0); }
public Head() { direction2 = new Vector3(((float)random.NextDouble()) - 0.5f, ((float)random.NextDouble()) - 0.5f, 0); direction2.NormalizeFast(); }
public void Update(float elapsedTime) { t += elapsedTime; if (random.Next(100) == 0) { Vector3 randomDirection = new Vector3(((float)random.NextDouble()) - 0.5f, ((float)random.NextDouble()) - 0.5f, 0); randomDirection.NormalizeFast(); target = targetNode + randomDirection * 30; } direction2 = target - Position; direction2.NormalizeFast(); TargetRotation = DirectionToAngle(direction2); TargetRotation += (float)Math.Sin(t * 4) * 0.5f; //direction2 = AngleToDirection(Rotation); //if (TargetRotation - Rotation > MathHelper.PiOver2) TargetRotation -= MathHelper.Pi; //if (Rotation - TargetRotation > MathHelper.PiOver2) TargetRotation += MathHelper.Pi; Rotation = Rotation * (1 - elapsedTime * 2) + TargetRotation * elapsedTime * 2; Position += direction2 * elapsedTime * 20; Size = 12; float size = Size * 0.75f; //float breath = (float)Math.Sin(t*20); //if (breath > 0) size *= (1.0f + breath); Segment parent = this; Segment current = NextSegment; while (current != null) { size *= 0.9f; current.targetSize = size; current.Size = current.Size * (1.0f - elapsedTime) + current.targetSize * elapsedTime; Vector3 directionToParent = parent.Position - current.Position; float distanceToParent = directionToParent.LengthFast; directionToParent.NormalizeFast(); current.Rotation = DirectionToAngle(directionToParent); float maxDistance = (parent.Size + current.Size) / 4; //float maxDistance = (current.Size + current.Size) / 2; if (distanceToParent > maxDistance) { current.Position = parent.Position - directionToParent * maxDistance; } else { current.Position = current.Position * (1 - elapsedTime * 2) + parent.Position * elapsedTime * 2; } parent = current; current = current.NextSegment; } }
public Vector3 GetZAxis() { return(Vector3.NormalizeFast(Vector3.Transform(Vector3.UnitZ, orientation))); }