Ejemplo n.º 1
0
        // Callback for acceleration 
        // (ODE solver uses x" = F/m) applied to particle i.  
        // The positions and velocities are not necessarily
        // m_akPosition and m_akVelocity since the ODE solver evaluates the
        // impulse function at intermediate positions.
        protected override float3 Acceleration(int i, Real fTime, float3[] akPosition, float3[] akVelocity)
        {
            // Compute spring forces on position X[i].  The positions are not
            // necessarily m_akPosition since the RK4 solver in ParticleSystem
            // evaluates the acceleration function at intermediate positions.  The end
            // points of the curve of masses must be handled separately since each
            // has only one spring attached to it.

            float3 kAcceleration = ExternalAcceleration(i, fTime, akPosition, akVelocity);

            float3 kDiff, kForce;
            Real fRatio;

            if (i > 0)
            {
                int iM1 = i - 1;
                kDiff = akPosition[iM1] - akPosition[i];
                fRatio = m_afLength[iM1] / kDiff.Length;
                kForce = m_afConstant[iM1] * (((Real)1.0) - fRatio) * kDiff;
                kAcceleration += MassInverse[i] * kForce;
            }

            int iP1 = i + 1;
            if (iP1 < NumParticles)
            {
                kDiff = akPosition[iP1] - akPosition[i];
                fRatio = m_afLength[i] / kDiff.Length;
                kForce = m_afConstant[i] * (((Real)1.0) - fRatio) * kDiff;
                kAcceleration += MassInverse[i] * kForce;
            }

            return kAcceleration;
        }
Ejemplo n.º 2
0
        public Sheep(RenderContext rc, float3 position, float3 rotation, float3 scaleFactor,  SceneRenderer sc, Game game)
            : base(rc, position, rotation, scaleFactor, sc)
        {
            _distance = position.Length;
            if (_distance > 60)
            {
                _score = 120;
            }
            if (_distance > 40)
            {
                _score = 80;
            }
            else
            {
                _score = 50;
            }
            Speed = (5 / _distance) * game.Level;
            Radius = 4f;
            _game = game;
            Pos = position;
            _alpha = (float)Math.Tan(Pos.z/Pos.x);
            Tag = "Sheep";
            _level = 1;
            //zufällige Wellenbewegung

            if (position.x % 2 == 0)
            {
                TheWave = SinWave;
            }
            else
            {
                TheWave = CosWave;
            }
        }
Ejemplo n.º 3
0
 public float4x3(float3x3 R, float3 t)
 {
     M11 = R.M11; M12 = R.M12; M13 = R.M13;
     M21 = R.M21; M22 = R.M22; M23 = R.M23;
     M31 = R.M31; M32 = R.M32; M33 = R.M33;
     M41 = t.x; M42 = t.y; M43 = t.z;
 }
Ejemplo n.º 4
0
 public float4x3(float3 r0, float3 r1, float3 r2, float3 r3)
 {
     M11 = r0.x; M12 = r0.y; M13 = r0.z;
     M21 = r1.x; M22 = r1.y; M23 = r1.z;
     M31 = r2.x; M32 = r2.y; M33 = r2.z;
     M41 = r3.x; M42 = r3.y; M43 = r3.z;
 }
Ejemplo n.º 5
0
 public float4(float3 v, float _w)
 {
     x = v.x;
     y = v.y;
     z = v.z;
     w = _w;
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Evaluates the distance to the closest distance field primitive in the field
 /// </summary>
 /// <param name="_Position"></param>
 /// <returns></returns>
 public float EvalDistance( float3 _Position )
 {
     float	Distance = float.MaxValue;
     foreach ( IDistanceFieldPrimitive P in m_Primitives )
         Distance = Math.Min( Distance, P.Eval( _Position ) );
     return Distance;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="PointLight"/> class. Only the channel is needed. Other params
 /// will be set to default value. 
 /// </summary>
 /// <param name="channel">The memory space of the light(0 - 7).</param>
 public PointLight(int channel)
 {
     _type = LightType.Point;
     _position = new float3(0, 0, 0);
     _diffuseColor = new float4(1, 1, 1, 1);
     _channel = channel;
 }
Ejemplo n.º 8
0
 public float4x4(float3x3 R, float3 t)
 {
     M11 = R.M11; M12 = R.M12; M13 = R.M13; M14 = 0;
     M21 = R.M21; M22 = R.M22; M23 = R.M23; M24 = 0;
     M31 = R.M31; M32 = R.M32; M33 = R.M33; M34 = 0;
     M41 = t.x; M42 = t.y; M43 = t.z; M44 = 1;
 }
Ejemplo n.º 9
0
 public float3 axis()
 {
     float3 a = new float3(x, y, z);
     if (Math.Abs(angle()) < 0.0000001f)
         return new float3(1f, 0f, 0f);
     return a * (1 / (float)Math.Sin(angle() / 2.0f));
 }
Ejemplo n.º 10
0
        public void DrawLine(float3 start, float3 end, float width, Color startColor, Color endColor)
        {
            renderer.CurrentBatchRenderer = this;

            if (nv + 6 > renderer.TempBufferSize)
                Flush();

            var delta = (end - start) / (end - start).XY.Length;
            var corner = width / 2 * new float3(-delta.Y, delta.X, delta.Z);

            startColor = Util.PremultiplyAlpha(startColor);
            var sr = startColor.R / 255.0f;
            var sg = startColor.G / 255.0f;
            var sb = startColor.B / 255.0f;
            var sa = startColor.A / 255.0f;

            endColor = Util.PremultiplyAlpha(endColor);
            var er = endColor.R / 255.0f;
            var eg = endColor.G / 255.0f;
            var eb = endColor.B / 255.0f;
            var ea = endColor.A / 255.0f;

            vertices[nv++] = new Vertex(start - corner + Offset, sr, sg, sb, sa, 0, 0);
            vertices[nv++] = new Vertex(start + corner + Offset, sr, sg, sb, sa, 0, 0);
            vertices[nv++] = new Vertex(end + corner + Offset, er, eg, eb, ea, 0, 0);
            vertices[nv++] = new Vertex(end + corner + Offset, er, eg, eb, ea, 0, 0);
            vertices[nv++] = new Vertex(end - corner + Offset, er, eg, eb, ea, 0, 0);
            vertices[nv++] = new Vertex(start - corner + Offset, sr, sg, sb, sa, 0, 0);
        }
Ejemplo n.º 11
0
 public BoxShape AddBoxShape(float3 boxHalfExtents)
 {
     IBoxShapeImp iBoxShapeImp = _dwi.AddBoxShape(boxHalfExtents);
     var retval = new BoxShape();
     retval.BoxShapeImp = iBoxShapeImp;
     iBoxShapeImp.UserObject = retval;
     return retval;
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Lerp Function for Float3.
 /// </summary>
 public static float3 Float3Lerp(float3 val1, float3 val2, float time1, float time2)
 {
     float3 values = new float3();
     values.x = val1.x + ((val2.x - val1.x) / time1) * time2;
     values.y = val1.y + ((val2.y - val1.y) / time1) * time2;
     values.z = val1.z + ((val2.z - val1.z) / time1) * time2;
     return values;
 }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpotLight"/> class. Only the channel is needed.
 /// </summary>
 /// <param name="channel">The memory space of the light(0 - 7).</param>
 public SpotLight( int channel)
 {
     _type = LightType.Spot;
     _position = new float3(0,0,0);
     _direction = new float3(0,-1,0);
     _diffuseColor = new float4(1, 1, 1, 1);
     _channel = channel;
 }
Ejemplo n.º 14
0
 public static void DrawTargetMarker(WorldRenderer wr, Color color, float3 location)
 {
     var iz = 1 / wr.Viewport.Zoom;
     var offset = new float2(iz, iz);
     var tl = location - offset;
     var br = location + offset;
     Game.Renderer.WorldRgbaColorRenderer.FillRect(tl, br, color);
 }
Ejemplo n.º 15
0
        // is called once a frame
        public override void RenderAFrame()
        {
            RC.Clear(ClearFlags.Color | ClearFlags.Depth);

            Point pt = Input.Instance.GetMousePos();
            var mousePosWorld = new float3(pt.x - Width/2, Height/2 - pt.y, 0);
            mousePosWorld = 2*CamDist/SquareScreenPxls*mousePosWorld;

            var lineWidthFactor = 1.0f;
            if (Input.Instance.IsButton(MouseButtons.Left))
            {
                lineWidthFactor = 3.0f;
                _shaderEffect.SetEffectParam("uLineColor", new float4(1, 0.2f, 0.2f, 0.9f));
            }
            else
            {
                _shaderEffect.SetEffectParam("uLineColor", new float4(0, 0, 0, 1));
            }
            _shaderEffect.SetEffectParam("uLineWidth",
                new float2(lineWidthFactor*LineWidth/_normWidth, lineWidthFactor*LineWidth/_normHeight));

            var curMaxRotChange =
                (float) (MaxRotChange*Math.Abs(Input.Instance.GetAxis(InputAxis.MouseX))*Time.Instance.DeltaTime);
            float angleHorzDelta =
                Math.Min(
                    Math.Max(RotationSpeed*-Input.Instance.GetAxis(InputAxis.MouseX) - _angleHorz, -curMaxRotChange),
                    curMaxRotChange);
            _angleHorz = (float) Math.Max(-0.5f*Math.PI, Math.Min(_angleHorz + angleHorzDelta, 0.5f*Math.PI));

            curMaxRotChange =
                (float) (MaxRotChange*Math.Abs(Input.Instance.GetAxis(InputAxis.MouseY))*Time.Instance.DeltaTime);
            float angleVertDelta =
                Math.Min(
                    Math.Max(RotationSpeed*-Input.Instance.GetAxis(InputAxis.MouseY) - _angleVert, -curMaxRotChange),
                    curMaxRotChange);
            _angleVert = (float) Math.Max(-0.7f*Math.PI, Math.Min(_angleVert + angleVertDelta, 0.2f*Math.PI));

            /* float angleVertDelta =
                Math.Min(Math.Max(_angleVert - RotationSpeed * -Input.Instance.GetAxis(InputAxis.MouseX), -_maxRotChange), _maxRotChange);
            _angleVert += angleVertDelta;*/

            var mtxRot = float4x4.CreateRotationY(_angleHorz)*float4x4.CreateRotationX(_angleVert);
            var mtxCam = float4x4.LookAt(0, 0, CamDist, 0, 0, 0, 0, 1, 0);

            var curDamp = (float) Math.Exp(-Damping*Time.Instance.DeltaTime);
            _angleHorz *= curDamp;
            _angleVert *= curDamp;

            // first mesh
            RC.ModelView = float4x4.CreateRotationX((float) (-0.3*Math.PI))*
                           new float4x4(HandScale, 0, 0, 0, 0, HandScale, 0, 0, 0, 0, HandScale, 0, 0, 0, 0, 1)*mtxRot*
                           float4x4.CreateTranslation(mousePosWorld)*mtxCam;

            _shaderEffect.RenderMesh(_meshTea);

            // swap buffers
            Present();
        }
 /// <summary>
 /// Creates a point light in the scene. Position, color, position, and channel is needed.
 /// It is possible to set up to 8 lights in the scene.
 /// </summary>
 /// <param name="color">The color of the light.</param>
 /// <param name="position">The position in the scene.</param>
 /// <param name="channel">The memory space of the light.(0 - 7)</param>
 public PointLight(float4 color, float3 position, int channel)
 {
     _position = position;
     _diffuseColor = new float4(0.6f, 0.6f, 0.6f, 1);
     _ambientColor = new float4(0.3f, 0.3f, 0.3f, 1);
     _specularColor = new float4(0.1f, 0.1f, 0.1f, 1);
     _type = LightType.Point;
     _channel = channel;
 }
Ejemplo n.º 17
0
 public Quaternion(float3 v, float t)
 {
     v = float3.normalize(v);
     w = (float)Math.Cos(t / 2.0f);
     v = v * (float)Math.Sin(t / 2.0f);
     x = v.x;
     y = v.y;
     z = v.z;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RenderPointLight" /> class. Position, color, type and channel are needed.
 /// </summary>
 /// <param name="position">The position of the light.</param>
 /// <param name="diffuse">The diffuse light color.</param>
 /// <param name="ambient">The ambient light color.</param>
 /// <param name="specular">The specular light color.</param>
 /// <param name="type">The light type.</param>
 /// <param name="channel">The memory space of the light(0 - 7).</param>
 public RenderPointLight(float3 position, float4 diffuse, float4 ambient, float4 specular, Light.LightType type, int channel)
 {
     _position = position;
     _type = Light.LightType.Point;
     _diffuseColor = diffuse;
     _ambientColor = ambient;
     _specularColor = specular;
     _channel = channel;
 }
Ejemplo n.º 19
0
        private static PlaneTriResult getSidePlane(float3 p, float4 plane, float epsilon)
        {
            float d = DistToPt(p, plane);

            if ((d + epsilon) > 0f)
                return PlaneTriResult.PTR_FRONT; // it is 'in front' within the provided epsilon value.

            return PlaneTriResult.PTR_BACK;
        }
Ejemplo n.º 20
0
        public Transformation()
        {
            fMatrix = float3x3.Identity;
            fTranslate = float3.Zero;
            fScale = new float3(1, 1, 1);

            fIsIdentity = true;
            fIsRSMatrix = true;
            fIsUniformScale = true;
        }
 /// <summary>
 /// Creates a directional light in the scene. Direction, color and position will get standart values.
 /// Channel is needed. It is possible to set up to 8 lights in the scene.
 /// </summary>
 /// <param name="channel">The memory space of the light(0 - 7).</param>
 public DirectionalLight( int channel)
 {
     _position = new float3(0,0,0);
     _direction = new float3(0,-1,0);
     _diffuseColor = new float4(0.6f, 0.6f, 0.6f, 1);
     _ambientColor = new float4(0.3f, 0.3f, 0.3f, 1);
     _specularColor = new float4(0.1f, 0.1f, 0.1f, 1);
     _type = LightType.Directional;
     _channel = channel;
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Creates a spot light in the scene. Position, color, position, and channel is needed.
 /// It is possible to set up to 8 lights in the scene.
 /// </summary>
 /// <param name="direction">Direction of the light.</param>
 /// <param name="diffuse">The diffuse light color.</param>
 /// <param name="ambient">The ambient light color.</param>
 /// <param name="specular">The specular light color.</param>
 /// <param name="position">The lights position in the scene.</param>
 /// <param name="channel">The memory space of the light.(0 - 7)</param>
 public SpotLight(float3 direction, float4 diffuse, float4 ambient, float4 specular, float3 position, int channel)
 {
     _direction = direction;
     _position = position;
     _diffuseColor = diffuse;
     _ambientColor = ambient;
     _specularColor = specular;
     _type = LightType.Spot;
     _channel = channel;
 }
Ejemplo n.º 23
0
 public Tomato(RenderContext rc, float3 position, float3 rotation, float3 scaleFactor,SceneRenderer sc, RigidBody tomatoRigidBody, Game game, DynamicWorld world)
     : base(rc, position, rotation, scaleFactor, sc)
 {
     TomatoRb = tomatoRigidBody;
     Radius = 2f;
     Tag = "Tomato";
     timer = 2.0f;
     _game = game;
     _world = world;
 }
Ejemplo n.º 24
0
        public Transformation(Transformation aTrans)
        {
            fMatrix = aTrans.fMatrix;
            fTranslate = aTrans.fTranslate;
            fScale = aTrans.fScale;

            fIsIdentity = aTrans.fIsIdentity;
            fIsRSMatrix = aTrans.fIsRSMatrix;
            fIsUniformScale = aTrans.fIsUniformScale;
        }
Ejemplo n.º 25
0
        public void Transform(float3 position, Quaternion orientation)
        {
            //   Transforms the plane to the space defined by the
            //   given position/orientation
            float3 newNormal = Quaternion.Inverse(orientation) * normal;
            float3 origin = Quaternion.Inverse(orientation) * (-normal * dist - position);

            normal = newNormal;
            dist = -float3.dot(newNormal, origin);
        }
Ejemplo n.º 26
0
        public int getIndex(float3 vtx)
        {
            int idx;
            if (mIndices.TryGetValue(vtx, out idx))
                return idx;

            idx = mVertices.Count;
            mVertices.Add(vtx);
            mIndices.Add(vtx, idx);
            return idx;
        }
Ejemplo n.º 27
0
    public static float Test (float3 lookAt, float3 upDirection) {
        float3.OrthoNormalize(ref lookAt, ref upDirection);

        float w = upDirection.y + lookAt.z;
        float w4Recip = 1.0f / (4.0f * w);
        float x = (upDirection.z - lookAt.y) * w4Recip;
        float y = lookAt.x * w4Recip;
        float z = upDirection.x * w4Recip;

        return w + x + y + z;
    }
 /// <summary>
 /// Initializes a new instance of the <see cref="RenderSpotLight" /> class. Position, direction, color, type and channel.
 /// </summary>
 /// <param name="position">The position of the light.</param>
 /// <param name="direction">The direction of the light.</param>
 /// <param name="diffuse">The diffuse light color.</param>
 /// <param name="ambient">The ambient light color.</param>
 /// <param name="specular">The specular light color.</param>
 /// <param name="angle">The angle of the spot light.</param>
 /// <param name="type">The lighttype.</param>
 /// <param name="channel">The memory space of the light(0 - 7).</param>
 public RenderSpotLight(float3 position, float3 direction, float4 diffuse, float4 ambient, float4 specular, float angle, Light.LightType type, int channel)
 {
     _position = position;
     _direction = direction;
     _type = Light.LightType.Spot;
     _diffuseColor = diffuse;
     _ambientColor = ambient;
     _specularColor = specular;
     _channel = channel;
     _angle = angle;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="Transformation"/> class. No SceneEntity will be set.
 /// </summary>
 public Transformation()
 {
     _hasParent = false;
        _transformMatrix = float4x4.Identity;
     _globalMatrix = _transformMatrix;
     _quaternion = Quaternion.Identity;
     _globalQuaternion = Quaternion.Identity;
        _globalScale = new float3(1,1,1);
        _localScale = new float3(1,1,1);
        _matrixDirty = false;
        _quaternionDirty = false;
        _eulerDirty = false;
 }
Ejemplo n.º 30
0
        private static void addTri(VertexPool vl, List<int> list, float3 p1, float3 p2, float3 p3)
        {
            int i1 = vl.getIndex(p1);
            int i2 = vl.getIndex(p2);
            int i3 = vl.getIndex(p3);

            // do *not* process degenerate triangles!
            if ( i1 != i2 && i1 != i3 && i2 != i3 )
            {
                list.Add(i1);
                list.Add(i2);
                list.Add(i3);
            }
        }
Ejemplo n.º 31
0
        public void TestBoxColliderCreateInvalid()
        {
            float3     center       = new float3(1.0f, 0.0f, 0.0f);
            quaternion orientation  = quaternion.AxisAngle(math.normalize(new float3(4.3f, 1.2f, 0.1f)), 1085.0f);
            float3     size         = new float3(1.0f, 2.0f, 3.0f);
            float      convexRadius = 0.45f;

            // Invalid center, positive infinity
            {
                float3 invalidCenter = new float3(float.PositiveInfinity, 1.0f, 1.0f);
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(invalidCenter, orientation, size, convexRadius)
                    );
            }

            // Invalid center, positive infinity
            {
                float3 invalidCenter = new float3(float.NegativeInfinity, 1.0f, 1.0f);
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(invalidCenter, orientation, size, convexRadius)
                    );
            }

            // Invalid center, nan
            {
                float3 invalidCenter = new float3(float.NaN, 1.0f, 1.0f);
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(invalidCenter, orientation, size, convexRadius)
                    );
            }

            // Negative size
            {
                float3 invalidSize = new float3(-1.0f, 1.0f, 1.0f);
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(center, orientation, invalidSize, convexRadius)
                    );
            }

            // Invalid size, positive inf
            {
                float3 invalidSize = new float3(float.PositiveInfinity, 1.0f, 1.0f);
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(center, orientation, invalidSize, convexRadius)
                    );
            }

            // Invalid size, negative inf
            {
                float3 invalidSize = new float3(float.NegativeInfinity, 1.0f, 1.0f);
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(center, orientation, invalidSize, convexRadius)
                    );
            }

            // Invalid size, nan
            {
                float3 invalidSize = new float3(float.NaN, 1.0f, 1.0f);
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(center, orientation, invalidSize, convexRadius)
                    );
            }

            // Negative convex radius
            {
                float invalidConvexRadius = -0.0001f;
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(center, orientation, size, invalidConvexRadius)
                    );
            }

            // Invalid convex radius, +inf
            {
                float invalidConvexRadius = float.PositiveInfinity;
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(center, orientation, size, invalidConvexRadius)
                    );
            }

            // Invalid convex radius, -inf
            {
                float invalidConvexRadius = float.NegativeInfinity;
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(center, orientation, size, invalidConvexRadius)
                    );
            }

            // Invalid convex radius, nan
            {
                float invalidConvexRadius = float.NaN;
                TestUtils.ThrowsException <System.ArgumentException>(
                    () => BoxCollider.Create(center, orientation, size, invalidConvexRadius)
                    );
            }
        }
Ejemplo n.º 32
0
 public static float Det(float3 a, float3 b, float3 c) => math.dot(math.cross(a, b), c); // TODO: use math.determinant()?
Ejemplo n.º 33
0
 public static float HorizontalMul(float3 v) => v.x * v.y * v.z;
Ejemplo n.º 34
0
 public static int IndexOfMinComponent(float3 v) => v.x < v.y ? ((v.x < v.z) ? 0 : 2) : ((v.y < v.z) ? 1 : 2);
Ejemplo n.º 35
0
        // RenderAFrame is called once a frame
        public override void RenderAFrame()
        {
            // Clear the backbuffer
            RC.Clear(ClearFlags.Color | ClearFlags.Depth);

            UpdateVideos();

            // Mouse and keyboard movement
            if (Keyboard.LeftRightAxis != 0 || Keyboard.UpDownAxis != 0)
            {
                _keys = true;
            }

            if (Mouse.LeftButton)
            {
                _keys         = false;
                _angleVelHorz = -RotationSpeed * Mouse.XVel * DeltaTime * 0.0005f;
                _angleVelVert = -RotationSpeed * Mouse.YVel * DeltaTime * 0.0005f;
            }
            else if (Touch.GetTouchActive(TouchPoints.Touchpoint_0))
            {
                _keys = false;
                var touchVel = Touch.GetVelocity(TouchPoints.Touchpoint_0);
                _angleVelHorz = -RotationSpeed * touchVel.x * DeltaTime * 0.0005f;
                _angleVelVert = -RotationSpeed * touchVel.y * DeltaTime * 0.0005f;
            }
            else
            {
                if (_keys)
                {
                    _angleVelHorz = -RotationSpeed * Keyboard.LeftRightAxis * DeltaTime;
                    _angleVelVert = -RotationSpeed * Keyboard.UpDownAxis * DeltaTime;
                }
                else
                {
                    var curDamp = (float)System.Math.Exp(-Damping * DeltaTime);
                    _angleVelHorz *= curDamp;
                    _angleVelVert *= curDamp;
                }
            }
            if (Input.Keyboard.IsKeyDown(KeyCodes.PageUp) == true)
            {
                _screen.SetHit(10);
            }
            if (Input.Keyboard.IsKeyDown(KeyCodes.PageDown) == true)
            {
                _screen.SetHit(-10);
            }

            _angleHorz += _angleVelHorz;
            _angleVert += _angleVelVert;

            // Create the camera matrix and set it as the current ModelView transformation
            var mtxRot = float4x4.CreateRotationX(_angleVert) * float4x4.CreateRotationY(_angleHorz);

            // 3d mode
            var eyeF    = new float3(0, 110, -1000);
            var targetF = new float3(0, 110, 0);
            var upF     = new float3(0, 1, 0);

            _stereoCam.Prepare(Stereo3DEye.Left);
            for (var x = 0; x < 2; x++)
            {
                var lookAt = _stereoCam.LookAt3D(_stereoCam.CurrentEye, eyeF, targetF, upF);
                var mtx    = lookAt * mtxRot;
                //  var mtxCam = float4x4.LookAt(0, 20, -600, 0, 150, 0, 0, 1, 0);
                RC.ModelView = mtx * float4x4.CreateTranslation(new float3(0, 0, 0));

                // Render the scene loaded in Init()
                //Render FUSEE Rocket
                _sceneRenderer.Render(RC);
                //Render ScreenS3D object
                _screen.Render(_stereoCam, lookAt * mtx);

                _stereoCam.Save();
                if (x == 0)
                {
                    _stereoCam.Prepare(Stereo3DEye.Right);
                }
            }
            _stereoCam.Display();


            #if GUI_SIMPLE
            _guiHandler.RenderGUI();
            #endif

            // Swap buffers: Show the contents of the backbuffer (containing the currently rerndered farame) on the front buffer.
            Present();
        }
Ejemplo n.º 36
0
        protected override void OnUpdate()
        {
            var uniqueTypes = new List <SpawnRandomInSphere>(10);

            EntityManager.GetAllUniqueSharedComponentData(uniqueTypes);

            int spawnInstanceCount = 0;

            for (int sharedIndex = 0; sharedIndex != uniqueTypes.Count; sharedIndex++)
            {
                var spawner = uniqueTypes[sharedIndex];
                m_MainGroup.SetFilter(spawner);
                var entityCount = m_MainGroup.CalculateLength();
                spawnInstanceCount += entityCount;
            }

            if (spawnInstanceCount == 0)
            {
                return;
            }

            var spawnInstances = new NativeArray <SpawnRandomInSphereInstance>(spawnInstanceCount, Allocator.Temp);

            {
                int spawnIndex = 0;
                for (int sharedIndex = 0; sharedIndex != uniqueTypes.Count; sharedIndex++)
                {
                    var spawner = uniqueTypes[sharedIndex];
                    m_MainGroup.SetFilter(spawner);

                    if (m_MainGroup.CalculateLength() == 0)
                    {
                        continue;
                    }

                    var entities  = m_MainGroup.ToEntityArray(Allocator.TempJob);
                    var positions = m_MainGroup.ToComponentDataArray <Position>(Allocator.TempJob);

                    for (int entityIndex = 0; entityIndex < entities.Length; entityIndex++)
                    {
                        var spawnInstance = new SpawnRandomInSphereInstance();

                        spawnInstance.sourceEntity = entities[entityIndex];
                        spawnInstance.spawnerIndex = sharedIndex;
                        spawnInstance.position     = positions[entityIndex].Value;

                        spawnInstances[spawnIndex] = spawnInstance;
                        spawnIndex++;
                    }

                    entities.Dispose();
                    positions.Dispose();
                }
            }

            for (int spawnIndex = 0; spawnIndex < spawnInstances.Length; spawnIndex++)
            {
                int    spawnerIndex   = spawnInstances[spawnIndex].spawnerIndex;
                var    spawner        = uniqueTypes[spawnerIndex];
                int    count          = spawner.count;
                var    entities       = new NativeArray <Entity>(count, Allocator.Temp);
                var    prefab         = spawner.prefab;
                float  radius         = spawner.radius;
                var    spawnPositions = new NativeArray <float3>(count, Allocator.Temp);
                float3 center         = spawnInstances[spawnIndex].position;
                var    sourceEntity   = spawnInstances[spawnIndex].sourceEntity;

                GeneratePoints.RandomPointsInSphere(center, radius, ref spawnPositions);

                EntityManager.Instantiate(prefab, entities);

                for (int i = 0; i < count; i++)
                {
                    var position = new Position
                    {
                        Value = spawnPositions[i]
                    };
                    EntityManager.SetComponentData(entities[i], position);
                }

                EntityManager.RemoveComponent <SpawnRandomInSphere>(sourceEntity);

                spawnPositions.Dispose();
                entities.Dispose();
            }
            spawnInstances.Dispose();
        }
Ejemplo n.º 37
0
 public void PlaceItem()
 {
     float3 mousePos = GETMousePosition();
 }
Ejemplo n.º 38
0
 public static float dot(float3 left, float3 right)
 {
     return(left.x * right.x + left.y * right.y + left.z * right.z);
 }
Ejemplo n.º 39
0
 public matrix3x3(float3 col1, float3 col2, float3 col3)
 {
     m11 = col1.x; m12 = col2.x; m13 = col3.x;
     m21 = col1.y; m22 = col2.y; m23 = col3.y;
     m31 = col1.z; m32 = col2.z; m33 = col3.z;
 }
Ejemplo n.º 40
0
 public static float CalculateTime_Arc(float3 position, float3 target, float gravity, float arcHeight)
 {
     return(math.sqrt(-2 * arcHeight / gravity) + math.sqrt(2 * (target.y - position.y - arcHeight) / gravity));
 }
    public static unsafe void CheckSupport(CharacterControllerStepInput stepInput,
                                           RigidTransform transform, float maxSlope, MaxHitsCollector <DistanceHit> distanceHitsCollector,
                                           ref NativeArray <SurfaceConstraintInfo> constraints, out CharacterSupportState characterState)
    {
        // If no hits, proclaim unsupported state
        if (distanceHitsCollector.NumHits == 0)
        {
            characterState = CharacterSupportState.Unsupported;
            return;
        }

        // Downwards direction must be normalized
        float3 downwardsDirection = -stepInput.Up;

        Assert.IsTrue(Math.IsNormalized(downwardsDirection));

        // Iterate over distance hits and create constraints from them
        for (int i = 0; i < distanceHitsCollector.NumHits; i++)
        {
            DistanceHit hit = distanceHitsCollector.AllHits[i];
            CreateConstraintFromHit(stepInput.World, float3.zero, stepInput.DeltaTime, hit.RigidBodyIndex, hit.ColliderKey,
                                    hit.Position, hit.SurfaceNormal, hit.Distance, true, out SurfaceConstraintInfo constraint);
            constraints[i] = constraint;
        }

        // Solve downwards (don't respect min delta time, try to solve full step)
        float3 outVelocity = downwardsDirection;
        float3 outPosition = transform.pos;

        SimplexSolver.Solve(stepInput.World, stepInput.DeltaTime, stepInput.Up, distanceHitsCollector.NumHits,
                            ref constraints, ref outPosition, ref outVelocity, out float integratedTime, false);

        // Check support state
        {
            if (math.lengthsq(downwardsDirection - outVelocity) < SimplexSolver.c_SimplexSolverEpsilon)
            {
                // If velocity hasn't changed significantly, declare unsupported state
                characterState = CharacterSupportState.Unsupported;
            }
            else if (math.lengthsq(outVelocity) < SimplexSolver.c_SimplexSolverEpsilon)
            {
                // If velocity is very small, declare supported state
                characterState = CharacterSupportState.Supported;
            }
            else
            {
                // Check if sliding or supported
                outVelocity = math.normalize(outVelocity);
                float slopeAngleSin   = math.dot(outVelocity, downwardsDirection);
                float slopeAngleCosSq = 1 - slopeAngleSin * slopeAngleSin;
                float maxSlopeCosine  = math.cos(maxSlope);
                if (slopeAngleCosSq < maxSlopeCosine * maxSlopeCosine - SimplexSolver.c_SimplexSolverEpsilon)
                {
                    characterState = CharacterSupportState.Sliding;
                }
                else
                {
                    characterState = CharacterSupportState.Supported;
                }
            }
        }
    }
    private static unsafe void CalculateAndStoreDeferredImpulses(
        CharacterControllerStepInput stepInput, float characterMass, float3 linearVelocity, int numConstraints,
        ref NativeArray <SurfaceConstraintInfo> constraints, ref BlockStream.Writer deferredImpulseWriter)
    {
        PhysicsWorld world = stepInput.World;

        for (int i = 0; i < numConstraints; i++)
        {
            SurfaceConstraintInfo constraint = constraints[i];

            int rigidBodyIndex = constraint.RigidBodyIndex;
            if (rigidBodyIndex < 0 || rigidBodyIndex >= world.NumDynamicBodies)
            {
                // Invalid and static bodies should be skipped
                continue;
            }

            RigidBody body = world.Bodies[rigidBodyIndex];

            float3 pointRelVel = world.GetLinearVelocity(rigidBodyIndex, constraint.HitPosition);
            pointRelVel -= linearVelocity;

            float projectedVelocity = math.dot(pointRelVel, constraint.Plane.Normal);

            // Required velocity change
            float deltaVelocity = -projectedVelocity * stepInput.Damping;

            float distance = constraint.Plane.Distance;
            if (distance < 0.0f)
            {
                deltaVelocity += (distance / stepInput.DeltaTime) * stepInput.Tau;
            }

            // Calculate impulse
            MotionVelocity mv      = world.MotionVelocities[rigidBodyIndex];
            float3         impulse = float3.zero;
            if (deltaVelocity < 0.0f)
            {
                // Impulse magnitude
                float impulseMagnitude = 0.0f;
                {
                    float objectMassInv = GetInvMassAtPoint(constraint.HitPosition, constraint.Plane.Normal, body, mv);
                    impulseMagnitude = deltaVelocity / objectMassInv;
                }

                impulse = impulseMagnitude * constraint.Plane.Normal;
            }

            // Add gravity
            {
                // Effect of gravity on character velocity in the normal direction
                float3 charVelDown = stepInput.Gravity * stepInput.DeltaTime;
                float  relVelN     = math.dot(charVelDown, constraint.Plane.Normal);

                // Subtract separation velocity if separating contact
                {
                    bool  isSeparatingContact = projectedVelocity < 0.0f;
                    float newRelVelN          = relVelN - projectedVelocity;
                    relVelN = math.select(relVelN, newRelVelN, isSeparatingContact);
                }

                // If resulting velocity is negative, an impulse is applied to stop the character
                // from falling into the body
                {
                    float3 newImpulse = impulse;
                    newImpulse += relVelN * characterMass * constraint.Plane.Normal;
                    impulse     = math.select(impulse, newImpulse, relVelN < 0.0f);
                }
            }

            // Store impulse
            deferredImpulseWriter.Write(
                new DeferredCharacterControllerImpulse()
            {
                Entity  = body.Entity,
                Impulse = impulse,
                Point   = constraint.HitPosition
            });
        }
    }
        public void Execute(int index)
        {
            {
                if (index % DynamicBoneBeta.MAX_TRANSFORM_LIMIT == 0)
                {
                    return;
                }

                int headIndex = index / DynamicBoneBeta.MAX_TRANSFORM_LIMIT;
                DynamicBoneBeta.HeadInfo curHeadInfo = ParticleHeadInfo[headIndex];
                {
                    int singleId = index % DynamicBoneBeta.MAX_TRANSFORM_LIMIT;

                    if (singleId >= curHeadInfo.m_particleCount)
                    {
                        return;
                    }

                    int pIdx = curHeadInfo.m_jobDataOffset + (index % DynamicBoneBeta.MAX_TRANSFORM_LIMIT);

                    DynamicBoneBeta.Particle p = ParticleInfo[pIdx];
                    int p0Idx = curHeadInfo.m_jobDataOffset + p.m_ParentIndex;
                    DynamicBoneBeta.Particle p0 = ParticleInfo[p0Idx];

                    float3 ePos   = p.worldPosition;
                    float3 ep0Pos = p0.worldPosition;

                    float erestLen = math.distance(ep0Pos, ePos);

                    float stiffness = Mathf.Lerp(1.0f, p.m_Stiffness, curHeadInfo.m_Weight);
                    if (stiffness > 0 || p.m_Elasticity > 0)
                    {
                        float4x4 em0             = float4x4.TRS(p0.tmpWorldPosition, p0.worldRotation, p.parentScale);
                        float3   erestPos        = math.mul(em0, new float4(p.localPosition.xyz, 1)).xyz;
                        float3   ed              = erestPos - p.tmpWorldPosition;
                        float3   eStepElasticity = ed * p.m_Elasticity;
                        p.tmpWorldPosition += eStepElasticity;

                        if (stiffness > 0)
                        {
                            float len    = math.distance(erestPos, p.tmpWorldPosition);
                            float maxlen = erestLen * (1 - stiffness) * 2;
                            if (len > maxlen)
                            {
                                float3 max = ed * ((len - maxlen) / len);
                                p.tmpWorldPosition += max;
                            }
                        }
                    }

                    float3 edd   = p0.tmpWorldPosition - p.tmpWorldPosition;
                    float  eleng = math.distance(p0.tmpWorldPosition, p.tmpWorldPosition);
                    if (eleng > 0)
                    {
                        float3 tmp = edd * ((eleng - erestLen) / eleng);
                        p.tmpWorldPosition += tmp;
                    }

                    ParticleInfo[pIdx] = p;
                }
            }
        }
Ejemplo n.º 44
0
        public void DrawBuildingOverlay()
        {
            //Debug.Log("Drawing Select Overlay");
            //float3 worldPos = getMousePosition(); //UtilsInput.GetMouseWorld3DPosition();


            //get grid position
            int2 gridPos = GridSystem.GETGridPosition(_placeBuildingPos);


            //if (gridPos.Equals(placeBuildingGridPos))
            //    return; //currently this will prevent the first go though, so keep it out



            placeBuildingGridPos = gridPos;



            _placeBuildingPos   = GridSystem.GETWorldPositionCellCenter(gridPos, 0, MapType.current);
            _placeBuildingPos.z = zLevel;
            _overlayContainer.transform.position = _placeBuildingPos;

            //draw overlay
            //Debug.Log($"Overlay Possitions: {gridPos}, {placeBuildingPos}");

            Cell cell;

            canPlaceBuilding = true;
            bool canPlaceBuildingCell = true;

            for (int x = 0; x < placeBuildingSo.size.x; x++)
            {
                for (int y = 0; y < placeBuildingSo.size.y; y++)
                {
                    canPlaceBuildingCell = true;


                    //Debug.Log($"Finding Cell::: {x}, {y}, {placeBuildingGridPos}");
                    cell = GridSystem.GETCell(
                        new int2(x + placeBuildingGridPos.x, y + placeBuildingGridPos.y));



                    if (!cell.canBuild)
                    {
                        canPlaceBuilding     = false;
                        canPlaceBuildingCell = false;
                    }


                    if (cell.IsDefault())
                    {
                        //Debug.Log("############################ No data found");
                        canPlaceBuilding     = false;
                        canPlaceBuildingCell = false;
                    }
                    int index = x + (y * placeBuildingSo.size.x);
                    //Debug.Log($"INDE#S: {index}");
                    if (canPlaceBuildingCell)
                    {
                        _overlayCells[index].color = positiveColor;
                    }
                    else
                    {
                        _overlayCells[index].color = negativeColor;
                    }
                }
            }

            ONCanBuildChanged?.Invoke(canPlaceBuilding);

            if (buildButton != null)
            {
                buildButton.interactable = canPlaceBuilding;
            }

            //Debug.Log($"Can build: {canPlaceBuilding}");
        }
		public PlungerMeshBufferElement(float3 v)
		{
			Value = v;
		}
Ejemplo n.º 46
0
        //public GameObject buildingShadowPrefab;
        //TESTING


        /*
         * public GridBuildingItem gridBuildingItem { get {
         *      return buildingComp.item;
         * } }
         */

        public void StartBuildSetup(BuildingDataSo buildingSo)
        {
            //Move to action button menu
            menuManager.SetActivePanel(buildActionButtonMenuId);

            //create our objects
            _overlayContainer = new GameObject("Building Overlay Container");

            GameObject go;
            float2     cellSize = GridSystem.GETCellSize();

            _overlayCells = new SpriteRenderer[buildingSo.size.x * buildingSo.size.y];
            for (int x = 0; x < buildingSo.size.x; x++)
            {
                for (int y = 0; y < buildingSo.size.y; y++)
                {
                    int index = x + (y * buildingSo.size.x);
                    _overlayCells[index] = Instantiate(overlayPrefab, _overlayContainer.transform)
                                           .GetComponent <SpriteRenderer>();
                    _overlayCells[index].transform.position = new float3(
                        x * cellSize.x,
                        y * cellSize.y, 0);
                }
            }


            placeBuilding = true;

            placeBuildingSo = buildingSo;

            //we go thourgh this process to snap to grid
            _placeBuildingPos        = GETMiddleScreenPosition();
            placeBuildingGridPos     = GridSystem.GETGridPosition(_placeBuildingPos);
            _placeBuildingPos        = GridSystem.GETWorldPosition(placeBuildingGridPos, 0, MapType.current);
            _placeBuildingInitialPos = _placeBuildingPos;

            _placeBuildingPos.z = zLevel;
            _overlayContainer.transform.position = _placeBuildingPos;


            /// get the middle closes cell pos.....
            placeBuildingGridPos = GridSystem.GETGridPosition(_placeBuildingPos);


            //BUILD ITEM
            BuildingItem data = new BuildingItem
            {
                pos      = placeBuildingGridPos,
                typeId   = buildingSo.typeId,
                rotation = 0,
                mapType  = MapType.current,
                stage    = BuildingStage.placingStage
            };

            buildingComp = BuildingComp.PlaceBuilding(buildingSo, data, _overlayContainer.transform);
            buildingComp.transform.localPosition = Vector3.zero; //buildingSO.placementOffset;

            /*
             * buildingPrefab = new GameObject(buildingSO.buildingName);
             * buildingPrefab.transform.position = placeBuildingPos; // middle closest cell
             * buildingComp = buildingPrefab.AddComponent<BuildingComp>();
             * buildingComp.buildingSO = buildingSO;
             *
             * buildingComp.Init(data,buildingSO);
             */
            //buildingShadowPrefab = Instantiate(buildingSO.clearPrefab);
            //buildingShadowPrefab.transform.position = placeBuildingPos;

            Debug.Log($"Started building process::: {_placeBuildingPos}");
            DrawBuildingOverlay();

            //buildingGridSize = buildingSize;
        }
Ejemplo n.º 47
0
        // Calculate the eigenvectors and eigenvalues of a symmetric 3x3 matrix
        public static void DiagonalizeSymmetricApproximation(float3x3 a, out float3x3 eigenVectors, out float3 eigenValues)
        {
            float GetMatrixElement(float3x3 m, int row, int col)
            {
                switch (col)
                {
                case 0: return(m.c0[row]);

                case 1: return(m.c1[row]);

                case 2: return(m.c2[row]);

                default: UnityEngine.Assertions.Assert.IsTrue(false); return(0.0f);
                }
            }

            void SetMatrixElement(ref float3x3 m, int row, int col, float x)
            {
                switch (col)
                {
                case 0: m.c0[row] = x; break;

                case 1: m.c1[row] = x; break;

                case 2: m.c2[row] = x; break;

                default: UnityEngine.Assertions.Assert.IsTrue(false); break;
                }
            }

            eigenVectors = float3x3.identity;
            float     epsSq         = 1e-14f * (math.lengthsq(a.c0) + math.lengthsq(a.c1) + math.lengthsq(a.c2));
            const int maxIterations = 10;

            for (int iteration = 0; iteration < maxIterations; iteration++)
            {
                // Find the row (p) and column (q) of the off-diagonal entry with greater magnitude
                int p = 0, q = 1;
                {
                    float maxEntry = math.abs(a.c1[0]);
                    float mag02    = math.abs(a.c2[0]);
                    float mag12    = math.abs(a.c2[1]);
                    if (mag02 > maxEntry)
                    {
                        maxEntry = mag02;
                        p        = 0;
                        q        = 2;
                    }
                    if (mag12 > maxEntry)
                    {
                        maxEntry = mag12;
                        p        = 1;
                        q        = 2;
                    }

                    // Terminate if it's small enough
                    if (maxEntry * maxEntry < epsSq)
                    {
                        break;
                    }
                }

                // Calculate jacobia rotation
                float3x3 j = float3x3.identity;
                {
                    float apq = GetMatrixElement(a, p, q);
                    float tau = (GetMatrixElement(a, q, q) - GetMatrixElement(a, p, p)) / (2.0f * apq);
                    float t   = math.sqrt(1.0f + tau * tau);
                    if (tau > 0.0f)
                    {
                        t = 1.0f / (tau + t);
                    }
                    else
                    {
                        t = 1.0f / (tau - t);
                    }
                    float c = math.rsqrt(1.0f + t * t);
                    float s = t * c;

                    SetMatrixElement(ref j, p, p, c);
                    SetMatrixElement(ref j, q, q, c);
                    SetMatrixElement(ref j, p, q, s);
                    SetMatrixElement(ref j, q, p, -s);
                }

                // Rotate a
                a            = math.mul(math.transpose(j), math.mul(a, j));
                eigenVectors = math.mul(eigenVectors, j);
            }
            eigenValues = new float3(a.c0.x, a.c1.y, a.c2.z);
        }
Ejemplo n.º 48
0
 private void Start()
 {
     Position = transform.position;
 }
Ejemplo n.º 49
0
 public static int IndexOfMaxComponent(float3 v) => v.x > v.y ? ((v.x > v.z) ? 0 : 2) : ((v.y > v.z) ? 1 : 2);
Ejemplo n.º 50
0
 public static lineseg transform(lineseg prim, float3 position, Quaternion rotation)
 {
     prim.start = rotation * prim.start + (Vector3)position;
     prim.end   = rotation * prim.end + (Vector3)position;
     return(prim);
 }
Ejemplo n.º 51
0
 public static float Dotxyz1(float4 lhs, float3 rhs) => math.dot(lhs, new float4(rhs, 1));
Ejemplo n.º 52
0
 public VehicleComponent(uint id, int currentid, float speed, float3 direction, float segpos, float dir, float3 position, int lane, float hitDistAhead)
 {
     Value = new VehicleData(id, currentid, speed, direction, segpos, dir, position, lane, hitDistAhead);
 }
Ejemplo n.º 53
0
 internal void SetPosition(int gameobjectID, int poolID, float3 position)
 {
     _transformAccessArray[poolID][_instancesMap[poolID].sparse[gameobjectID]].position = position;
 }
        void UpdateMeshFromSplineGraph()
        {
            Mesh mesh = meshFilter.sharedMesh;

            if (mesh == null)
            {
                mesh = new Mesh();
            }

            if (radialEdgeCount <= 0)
            {
                // TODO: Cleanup case when radialEdgeCount == 0 due to user still editing into inspector field.
                // This should be handled with a delayed int field.
                return;
            }

            var splineGraph = (splineGraphComponent != null)
                ? splineGraphComponent.GetSplineGraph()
                : splineGraphManager.GetSplineGraph();

            // First, go through and compute the number of vertex ring subdivisions required to represent the spline graph based on curvature.
            Int16 vertexIsValidCount = splineGraph.ComputeVertexIsValidCount();
            Int16 edgeIsValidCount   = splineGraph.ComputeEdgeIsValidCount();

            int[] edgeSubdivisionIndex      = new int[splineGraph.edgePoolChildren.count];
            int[] edgeSubdivisionCount      = new int[splineGraph.edgePoolChildren.count];
            int   meshSubdivisionCountTotal = 0;
            int   meshRingCountTotal        = 0;


            for (Int16 edgeIndex = 0; edgeIndex < splineGraph.edgePoolChildren.count; ++edgeIndex)
            {
                DirectedEdge edge = splineGraph.edgePoolChildren.data[edgeIndex];
                if (edge.IsValid() == 0)
                {
                    continue;
                }

                float splineLength     = splineGraph.payload.edgeLengths.data[edgeIndex];
                int   subdivisionCount = math.max(1, (int)math.floor(subdivisionsPerMeter * splineLength + 0.5f));
                int   ringCount        = subdivisionCount + 1;

                edgeSubdivisionIndex[edgeIndex] = meshSubdivisionCountTotal;
                edgeSubdivisionCount[edgeIndex] = subdivisionCount;
                meshSubdivisionCountTotal      += subdivisionCount;
                meshRingCountTotal += ringCount;
            }

            // TODO: Calculate counts.
            int meshVertexCount = meshRingCountTotal * radialEdgeCount;

            Vector3[] vertices  = new Vector3[meshVertexCount];
            Vector2[] uvs       = new Vector2[meshVertexCount];
            Vector3[] normals   = new Vector3[meshVertexCount];
            Color[]   colors    = new Color[meshVertexCount];
            int[]     triangles = new int[meshVertexCount * 6];

            int meshVertexIndex   = 0;
            int meshTriangleIndex = 0;

            for (Int16 edgeIndex = 0; edgeIndex < splineGraph.edgePoolChildren.count; ++edgeIndex)
            {
                DirectedEdge edge = splineGraph.edgePoolChildren.data[edgeIndex];
                if (edge.IsValid() == 0)
                {
                    continue;
                }

                Int16 vertexIndexChild  = splineGraph.edgePoolChildren.data[edgeIndex].vertexIndex;
                Int16 vertexIndexParent = splineGraph.edgePoolParents.data[edgeIndex].vertexIndex;

                SplineMath.Spline spline       = splineGraph.payload.edgeParentToChildSplines.data[edgeIndex];
                float             splineLength = splineGraph.payload.edgeLengths.data[edgeIndex];

                quaternion rotationParent = splineGraph.payload.rotations.data[vertexIndexParent];
                quaternion rotationChild  = splineGraph.payload.rotations.data[vertexIndexChild];

                SplineMath.Spline splineLeash = splineGraph.payload.edgeParentToChildSplinesLeashes.data[edgeIndex];

                // Find neighboring edge (if it exists) for use in CSG style operation against current one to handle intersections in branching region.
                DirectedVertex vertexParent = splineGraph.vertices.data[vertexIndexParent];
                Debug.Assert(vertexParent.IsValid() == 1);

                DirectedVertex vertexChild = splineGraph.vertices.data[vertexIndexChild];
                Debug.Assert(vertexChild.IsValid() == 1);

                int edgeSubdivisionCurrentCount = edgeSubdivisionCount[edgeIndex];
                for (int s = 0; s <= edgeSubdivisionCurrentCount; ++s)
                {
                    float t = (float)s / (float)edgeSubdivisionCurrentCount;
                    // Debug.Log("s = " + s + ", sCount = " + edgeSubdivisionCurrentCount + ", t = " + t);

                    float vNormalized = t;
                    if (s > 0)
                    {
                        // Compute the relative distance we have traveled between our current edge ring and previous.
                        SplineMath.ComputeSplitAtT(out SplineMath.Spline s00, out SplineMath.Spline s01, spline, t);

                        vNormalized = SplineMath.ComputeLengthEstimate(s00, 1e-5f) / splineLength;
                    }

                    float3     positionOnSpline = SplineMath.EvaluatePositionFromT(spline, t);
                    quaternion rotationOnSpline = SplineMath.EvaluateRotationWithRollFromT(spline, rotationParent, rotationChild, t);
                    // float2 leashMaxOS = math.lerp(leashParent, leashChild, t);
                    float2 leashMaxOS = SplineMath.EvaluatePositionFromT(splineLeash, t).xy;

                    // Generate radial ring of triangles
                    if (s < edgeSubdivisionCurrentCount)
                    {
                        for (int v = 0, vLen = radialEdgeCount; v < vLen; ++v)
                        {
                            triangles[meshTriangleIndex + v * 6 + 0] = meshVertexIndex + ((v + 0) % radialEdgeCount) + (0 * radialEdgeCount);
                            triangles[meshTriangleIndex + v * 6 + 1] = meshVertexIndex + ((v + 0) % radialEdgeCount) + (1 * radialEdgeCount);
                            triangles[meshTriangleIndex + v * 6 + 2] = meshVertexIndex + ((v + 1) % radialEdgeCount) + (1 * radialEdgeCount);

                            triangles[meshTriangleIndex + v * 6 + 3] = meshVertexIndex + ((v + 1) % radialEdgeCount) + (1 * radialEdgeCount);
                            triangles[meshTriangleIndex + v * 6 + 4] = meshVertexIndex + ((v + 1) % radialEdgeCount) + (0 * radialEdgeCount);
                            triangles[meshTriangleIndex + v * 6 + 5] = meshVertexIndex + ((v + 0) % radialEdgeCount) + (0 * radialEdgeCount);
                        }

                        meshTriangleIndex += radialEdgeCount * 6;
                    }

                    // Generate radial ring of vertices.
                    // bool ringIntersectsSibling = false;
                    for (int v = 0; v < radialEdgeCount; ++v)
                    {
                        float  thetaNormalized = (float)v / (float)radialEdgeCount;
                        float  theta           = thetaNormalized * 2.0f * math.PI;
                        float2 vertexOffsetOS  = new float2(
                            math.cos(theta),
                            math.sin(theta)
                            ) * leashMaxOS;// * radius;

                        float3 vertexOffsetWS   = math.mul(rotationOnSpline, new float3(vertexOffsetOS, 0.0f));
                        float3 vertexPositionWS = positionOnSpline + vertexOffsetWS;

                        float vertexIntersectionSignedDistanceMin = float.MaxValue;
                        {
                            for (Int16 edgeIndexSibling = vertexParent.childHead; edgeIndexSibling != -1; edgeIndexSibling = splineGraph.edgePoolChildren.data[edgeIndexSibling].next)
                            {
                                DirectedEdge edgeSibling = splineGraph.edgePoolChildren.data[edgeIndexSibling];
                                Debug.Assert(edgeSibling.IsValid() == 1);

                                if (edgeIndexSibling == edgeIndex)
                                {
                                    // Ignore ourselves.
                                    continue;
                                }

                                // Found our sibling edge. Only use the first one, as we only currently support CSG against a single branch.
                                Int16 siblingVertexIndexChild = edgeSibling.vertexIndex;
                                Debug.Assert(siblingVertexIndexChild != -1);

                                Int16 siblingVertexIndexParent = splineGraph.edgePoolParents.data[edgeIndexSibling].vertexIndex;
                                Debug.Assert(siblingVertexIndexParent != -1);

                                SplineMath.Spline splineSibling         = splineGraph.payload.edgeParentToChildSplines.data[edgeIndexSibling];
                                SplineMath.Spline splineLeashSibling    = splineGraph.payload.edgeParentToChildSplinesLeashes.data[edgeIndexSibling];
                                quaternion        siblingRotationParent = splineGraph.payload.rotations.data[siblingVertexIndexParent];
                                quaternion        siblingRotationChild  = splineGraph.payload.rotations.data[siblingVertexIndexChild];

                                SplineMath.FindTFromClosestPointOnSpline(out float siblingClosestT, out float siblingClosestDistance, vertexPositionWS, splineSibling);

                                float3     siblingPositionOnSpline = SplineMath.EvaluatePositionFromT(splineSibling, siblingClosestT);
                                quaternion siblingRotationOnSpline = SplineMath.EvaluateRotationWithRollFromT(splineSibling, siblingRotationParent, siblingRotationChild, siblingClosestT);
                                float2     siblingLeashMaxOS       = SplineMath.EvaluatePositionFromT(splineLeashSibling, siblingClosestT).xy;

                                float vertexIntersectionSignedDistance = math.length(math.mul(math.inverse(siblingRotationOnSpline), vertexPositionWS - siblingPositionOnSpline).xy / siblingLeashMaxOS) - 1.0f;
                                vertexIntersectionSignedDistanceMin = math.min(vertexIntersectionSignedDistanceMin, vertexIntersectionSignedDistance);
                            }

                            for (Int16 edgeIndexSibling = vertexChild.parentHead; edgeIndexSibling != -1; edgeIndexSibling = splineGraph.edgePoolParents.data[edgeIndexSibling].next)
                            {
                                DirectedEdge edgeSibling = splineGraph.edgePoolChildren.data[edgeIndexSibling];
                                Debug.Assert(edgeSibling.IsValid() == 1);

                                if (edgeIndexSibling == edgeIndex)
                                {
                                    // Ignore ourselves.
                                    continue;
                                }

                                // Found our sibling edge. Only use the first one, as we only currently support CSG against a single branch.
                                Int16 siblingVertexIndexParent = edgeSibling.vertexIndex;
                                Debug.Assert(siblingVertexIndexParent != -1);

                                Int16 siblingVertexIndexChild = splineGraph.edgePoolChildren.data[edgeIndexSibling].vertexIndex;
                                Debug.Assert(siblingVertexIndexChild != -1);

                                SplineMath.Spline splineSibling         = splineGraph.payload.edgeParentToChildSplines.data[edgeIndexSibling];
                                SplineMath.Spline splineLeashSibling    = splineGraph.payload.edgeParentToChildSplinesLeashes.data[edgeIndexSibling];
                                quaternion        siblingRotationParent = splineGraph.payload.rotations.data[siblingVertexIndexParent];
                                quaternion        siblingRotationChild  = splineGraph.payload.rotations.data[siblingVertexIndexChild];

                                SplineMath.FindTFromClosestPointOnSpline(out float siblingClosestT, out float siblingClosestDistance, vertexPositionWS, splineSibling);

                                float3     siblingPositionOnSpline = SplineMath.EvaluatePositionFromT(splineSibling, siblingClosestT);
                                quaternion siblingRotationOnSpline = SplineMath.EvaluateRotationWithRollFromT(splineSibling, siblingRotationParent, siblingRotationChild, siblingClosestT);
                                float2     siblingLeashMaxOS       = SplineMath.EvaluatePositionFromT(splineLeashSibling, siblingClosestT).xy;

                                float vertexIntersectionSignedDistance = math.length(math.mul(math.inverse(siblingRotationOnSpline), vertexPositionWS - siblingPositionOnSpline).xy / siblingLeashMaxOS) - 1.0f;
                                vertexIntersectionSignedDistanceMin = math.min(vertexIntersectionSignedDistanceMin, vertexIntersectionSignedDistance);
                            }
                        }

                        vertices[meshVertexIndex] = vertexPositionWS;
                        uvs[meshVertexIndex]      = new float2(
                            thetaNormalized,
                            vNormalized * splineLength * uvScale // TODO: Gotta figure out propogation of UVs.
                            );
                        normals[meshVertexIndex] = math.normalize(vertexOffsetWS);

                        float vertexIntersectionDistanceFade = math.smoothstep(vertexIntersectionSignedDistanceFadeMin, vertexIntersectionSignedDistanceFadeMax, vertexIntersectionSignedDistanceMin);
                        colors[meshVertexIndex] = new Color(vertexIntersectionDistanceFade, vertexIntersectionDistanceFade, vertexIntersectionDistanceFade, vertexIntersectionDistanceFade);

                        ++meshVertexIndex;
                    }
                }
            }

            // Trim arrays to final size.
            Vector3[] verticesTrimmed  = new Vector3[meshVertexIndex];
            Vector2[] uvsTrimmed       = new Vector2[meshVertexIndex];
            Vector3[] normalsTrimmed   = new Vector3[meshVertexIndex];
            Color[]   colorsTrimmed    = new Color[meshVertexIndex];
            int[]     trianglesTrimmed = new int[meshTriangleIndex];

            Array.Copy(vertices, verticesTrimmed, meshVertexIndex);
            Array.Copy(uvs, uvsTrimmed, meshVertexIndex);
            Array.Copy(normals, normalsTrimmed, meshVertexIndex);
            Array.Copy(colors, colorsTrimmed, meshVertexIndex);
            Array.Copy(triangles, trianglesTrimmed, meshTriangleIndex);

            // Finally assign back data (causes GC allocs).
            mesh.Clear();
            mesh.vertices         = verticesTrimmed;
            mesh.uv               = uvsTrimmed;
            mesh.normals          = normalsTrimmed;
            mesh.colors           = colorsTrimmed;
            mesh.triangles        = trianglesTrimmed;
            meshFilter.sharedMesh = mesh;

            MeshCollider meshCollider = meshFilter.gameObject.GetComponent <MeshCollider>();

            if (meshCollider != null)
            {
                meshCollider.sharedMesh = mesh;
            }
        }
Ejemplo n.º 55
0
 public TileInfo(float3 screenPosition, byte variant)
 {
     ScreenPosition = screenPosition;
     Variant        = variant;
 }
        /// <summary>
        /// Intersects a plane with a line
        /// </summary>
        /// <param name="planeOrigin">The origin of the plane</param>
        /// <param name="planeNormal">The normal of the plane</param>
        /// <param name="lineOrigin">The origin of the line</param>
        /// <param name="lineDirection">The direction of the line</param>
        /// <param name="intersectionPoint">The point where the line hit the plane (if any)</param>
        /// <returns>The collision result</returns>
        public static PlaneLineIntersectionResult PlaneLineIntersection(float3 planeOrigin, float3 planeNormal, float3 lineOrigin,
            float3 lineDirection, out float3 intersectionPoint)
        {
            planeNormal = math.normalize(planeNormal);
            lineDirection = math.normalize(lineDirection);

            if (math.dot(planeNormal, lineDirection) == 0)
            {
                intersectionPoint = float3.zero;
                return (planeOrigin - lineOrigin).Equals(float3.zero) ? PlaneLineIntersectionResult.ParallelInsidePlane : PlaneLineIntersectionResult.NoHit;
            }

            float d = math.dot(planeOrigin, -planeNormal);
            float t = -(d + lineOrigin.z * planeNormal.z + lineOrigin.y * planeNormal.y + lineOrigin.x * planeNormal.x) / (lineDirection.z * planeNormal.z + lineDirection.y * planeNormal.y + lineDirection.x * planeNormal.x);
            intersectionPoint = lineOrigin + t * lineDirection;
            return PlaneLineIntersectionResult.OneHit;
        }
Ejemplo n.º 57
0
        private Entity SpawnCamera(int id, float3 spawnPosition, quaternion spawnRotation, Entity attachEntity, CameraData cameraData)
        {
            if (cameraData.isRenderTexture == 0)
            {
                if (Camera.main)
                {
                    //Camera.main.gameObject.tag = "Untagged";
                    Camera.main.gameObject.SetActive(false);
                    if (canvas)
                    {
                        canvas.SetActive(false);
                    }
                }
            }
            else
            {
                if (canvas)
                {
                    canvas.SetActive(true);
                }
            }
            //AudioManager.instance.SpawnMonsterSpawnSound(spawnPosition);
            cameraDatas.Add(id, cameraData);
            GameObject cameraObject = SpawnCameraGameObject(id, cameraData, spawnPosition, spawnRotation);

            cameraObjects.Add(id, cameraObject);
            var    cameraEntity = AddECSComponents(cameraObject, id, attachEntity, cameraData);
            Camera camera       = cameraObject.GetComponent <Camera>();

            if (World.EntityManager.Exists(attachEntity))
            {
                //Entity charaterEntity = characterSpawnSystem.characters[followID];
                if (cameraData.cameraType == ((byte)CameraDataType.ThirdPerson))
                {
                    Translation characterTranslation = World.EntityManager.GetComponentData <Translation>(attachEntity);
                    Rotation    characterRotation    = World.EntityManager.GetComponentData <Rotation>(attachEntity);
                    spawnPosition  = characterTranslation.Value + new float3(0, cameraData.followCameraData.cameraAddition.y, 0);
                    spawnPosition += math.rotate(characterRotation.Value, new float3(0, 0, cameraData.followCameraData.cameraAddition.z));
                    Quaternion newRotation = new Quaternion(characterRotation.Value.value.x,
                                                            characterRotation.Value.value.y, characterRotation.Value.value.z, characterRotation.Value.value.w);
                    float3 newRotation2 = newRotation.eulerAngles;
                    newRotation2.x = cameraData.followCameraData.cameraRotation.x;
                    spawnRotation  = Quaternion.Euler(newRotation2);
                }
                if (World.EntityManager.HasComponent <CameraLink>(attachEntity))
                {
                    CameraLink cameraLink = World.EntityManager.GetComponentData <CameraLink>(attachEntity);
                    cameraLink.camera = cameraEntity;
                    cameraLink.fov    = camera.fieldOfView;
                    World.EntityManager.SetComponentData(attachEntity, cameraLink);
                }
            }
            else
            {
                World.EntityManager.AddComponentData(cameras[id], new CameraLink
                {
                    camera = cameraEntity,
                    fov    = camera.fieldOfView
                });
            }
            // Setup camera object
            if (cameraData.isRenderTexture == 1)
            {
                CreateRenderTexture(camera, cameraData, id);
            }
            else
            {
                Camera.SetupCurrent(camera);
                camera.tag = "MainCamera";
            }
            Debug.Log("Spawned camera: " + id);
            ResizeRenderTextures();
            return(cameraEntity);
        }
    public static unsafe void CollideAndIntegrate(
        CharacterControllerStepInput stepInput, float characterMass, bool affectBodies, Collider *collider,
        MaxHitsCollector <DistanceHit> distanceHitsCollector, ref NativeArray <ColliderCastHit> castHits, ref NativeArray <SurfaceConstraintInfo> constraints,
        ref RigidTransform transform, ref float3 linearVelocity, ref BlockStream.Writer deferredImpulseWriter)
    {
        // Copy parameters
        float        deltaTime = stepInput.DeltaTime;
        float3       gravity   = stepInput.Gravity;
        float3       up        = stepInput.Up;
        PhysicsWorld world     = stepInput.World;

        float  remainingTime    = deltaTime;
        float3 lastDisplacement = linearVelocity * remainingTime;

        float3     newPosition = transform.pos;
        quaternion orientation = transform.rot;
        float3     newVelocity = linearVelocity;

        float maxSlopeCos = math.cos(stepInput.MaxSlope);

        // Iterate over hits and create constraints from them
        int numDistanceConstraints = 0;

        for (int hitIndex = 0; hitIndex < distanceHitsCollector.NumHits; hitIndex++)
        {
            DistanceHit hit = distanceHitsCollector.AllHits[hitIndex];
            CreateConstraintFromHit(world, gravity, deltaTime, hit.RigidBodyIndex, hit.ColliderKey, hit.Position,
                                    hit.SurfaceNormal, hit.Distance, false, out SurfaceConstraintInfo constraint);

            // Check if max slope plane is required
            float verticalComponent = math.dot(constraint.Plane.Normal, up);
            bool  shouldAddPlane    = verticalComponent > SimplexSolver.c_SimplexSolverEpsilon && verticalComponent < maxSlopeCos;
            if (shouldAddPlane)
            {
                AddMaxSlopeConstraint(up, ref constraint, ref constraints, ref numDistanceConstraints);
            }

            // Add original constraint to the list
            constraints[numDistanceConstraints++] = constraint;
        }

        const float timeEpsilon = 0.000001f;

        for (int i = 0; i < stepInput.MaxIterations && remainingTime > timeEpsilon; i++)
        {
            int    numConstraints  = numDistanceConstraints;
            float3 gravityMovement = gravity * remainingTime * remainingTime * 0.5f;

            // Then do a collider cast (but not in first iteration)
            if (i > 0)
            {
                float3 displacement = lastDisplacement + gravityMovement;
                MaxHitsCollector <ColliderCastHit> collector = new MaxHitsCollector <ColliderCastHit>(1.0f, ref castHits);
                ColliderCastInput input = new ColliderCastInput()
                {
                    Collider    = collider,
                    Orientation = orientation,
                    Start       = newPosition,
                    End         = newPosition + displacement,
                };
                world.CastCollider(input, ref collector);

                // Iterate over hits and create constraints from them
                for (int hitIndex = 0; hitIndex < collector.NumHits; hitIndex++)
                {
                    ColliderCastHit hit = collector.AllHits[hitIndex];

                    bool found = false;
                    for (int distanceHitIndex = 0; distanceHitIndex < distanceHitsCollector.NumHits; distanceHitIndex++)
                    {
                        DistanceHit dHit = distanceHitsCollector.AllHits[distanceHitIndex];
                        if (dHit.RigidBodyIndex == hit.RigidBodyIndex &&
                            dHit.ColliderKey.Equals(hit.ColliderKey))
                        {
                            found = true;
                            break;
                        }
                    }

                    // Skip duplicate hits
                    if (!found)
                    {
                        CreateConstraintFromHit(world, gravity, deltaTime, hit.RigidBodyIndex, hit.ColliderKey, hit.Position, hit.SurfaceNormal,
                                                hit.Fraction * math.length(lastDisplacement), false, out SurfaceConstraintInfo constraint);

                        // Check if max slope plane is required
                        float verticalComponent = math.dot(constraint.Plane.Normal, up);
                        bool  shouldAddPlane    = verticalComponent > SimplexSolver.c_SimplexSolverEpsilon && verticalComponent < maxSlopeCos;
                        if (shouldAddPlane)
                        {
                            AddMaxSlopeConstraint(up, ref constraint, ref constraints, ref numConstraints);
                        }

                        // Add original constraint to the list
                        constraints[numConstraints++] = constraint;
                    }
                }
            }

            // Solve
            float3 prevVelocity = newVelocity;
            float3 prevPosition = newPosition;
            SimplexSolver.Solve(world, remainingTime, up, numConstraints, ref constraints, ref newPosition, ref newVelocity, out float integratedTime);

            // Apply impulses to hit bodies
            if (affectBodies)
            {
                CalculateAndStoreDeferredImpulses(stepInput, characterMass, prevVelocity, numConstraints, ref constraints, ref deferredImpulseWriter);
            }

            float3 newDisplacement = newPosition - prevPosition;

            // Check if we can walk to the position simplex solver has suggested
            MaxHitsCollector <ColliderCastHit> newCollector = new MaxHitsCollector <ColliderCastHit>(1.0f, ref castHits);
            int newContactIndex = -1;

            // If simplex solver moved the character we need to re-cast to make sure it can move to new position
            if (math.lengthsq(newDisplacement) > SimplexSolver.c_SimplexSolverEpsilon)
            {
                float3            displacement = newDisplacement + gravityMovement;
                ColliderCastInput input        = new ColliderCastInput()
                {
                    Collider    = collider,
                    Orientation = orientation,
                    Start       = prevPosition,
                    End         = prevPosition + displacement
                };

                world.CastCollider(input, ref newCollector);

                for (int hitIndex = 0; hitIndex < newCollector.NumHits; hitIndex++)
                {
                    ColliderCastHit hit = newCollector.AllHits[hitIndex];

                    bool found = false;
                    for (int constraintIndex = 0; constraintIndex < numConstraints; constraintIndex++)
                    {
                        SurfaceConstraintInfo constraint = constraints[constraintIndex];
                        if (constraint.RigidBodyIndex == hit.RigidBodyIndex &&
                            constraint.ColliderKey.Equals(hit.ColliderKey))
                        {
                            found = true;
                            break;
                        }
                    }

                    if (!found)
                    {
                        newContactIndex = hitIndex;
                        break;
                    }
                }
            }

            // Move character along the newDisplacement direction until it reaches this new contact
            if (newContactIndex >= 0)
            {
                ColliderCastHit newContact = newCollector.AllHits[newContactIndex];

                Assert.IsTrue(newContact.Fraction >= 0.0f && newContact.Fraction <= 1.0f);

                integratedTime *= newContact.Fraction;
                newPosition     = prevPosition + newDisplacement * newContact.Fraction;
            }

            remainingTime -= integratedTime;

            // Remember last displacement for next iteration
            lastDisplacement = newVelocity * remainingTime;
        }

        // Write back position and velocity
        transform.pos  = newPosition;
        linearVelocity = newVelocity;
    }
Ejemplo n.º 59
0
 public static void CalculateTangents(float3 normal, out float3 tangent, out float3 binormal)
 {
     tangent  = math.normalizesafe(math.cross(normal, ClosestTangentAxis(normal)));
     binormal = math.normalizesafe(math.cross(normal, tangent));
 }
Ejemplo n.º 60
0
 public VehicleData(uint id, int currentid, float speed, float3 forward, float segpos, float dir, float3 position, int lane, float hitDistAhead)
 {
     this.Id            = id;
     this.SegId         = currentid;
     this.Speed         = speed;
     this.Forward       = forward;
     this.CurrentSegPos = segpos;
     this.Direction     = dir;
     this.Position      = position;
     this.Lane          = lane;
     this.HitDistAhead  = hitDistAhead;
 }