public Box(AnimatTools.Framework.DataObject doParent)
            : base(doParent)
        {
            m_vGraphicsBoxSize = new Vec3d(this);
            m_vGraphicsBoxSize.X = m_vGraphicsBoxSize.Y = m_vGraphicsBoxSize.Z = 1;

            m_snWidth = new AnimatTools.Framework.ScaledNumber(this, "WidthScaled", "meters", "m");
            m_snHeight = new AnimatTools.Framework.ScaledNumber(this, "HeightScaled", "meters", "m");
            m_snLength = new AnimatTools.Framework.ScaledNumber(this, "LengthScaled", "meters", "m");

            m_vrSize = new DxBoxSizeRef(this);
        }
Example #2
0
 /// <summary>
 /// Replace Y value
 /// </summary>
 /// <param name="v3"></param>
 /// <param name="y"></param>
 /// <returns></returns>
 public static Vec3d SetY(this Vec3d v3, decimal y)
 {
     return(new Vec3d(v3.X, y, v3.Z));
 }
Example #3
0
 /// <summary>
 /// Calculate the square of the distance between two 3D coordinates.
 /// </summary>
 /// <param name="v1">The first 3D coordinate.</param>
 /// <param name="v2">The second 3D coordinate.</param>
 /// <returns>The square of the distance between the given points.</returns>
 /// <!--
 /// vec3d.c
 /// double _pointSquareDist
 /// -->
 internal static decimal PointSquareDistance(this Vec3d v1, Vec3d v2)
 {
     return((v1.X - v2.X).Square() + (v1.Y - v2.Y).Square() + (v1.Z - v2.Z).Square());
 }
        public override bool OnHeldInteractStep(float secondsUsed, ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel)
        {
            if (blockSel == null)
            {
                return(false);
            }

            ILiquidMetalSink be = byEntity.World.BlockAccessor.GetBlockEntity(blockSel.Position) as ILiquidMetalSink;

            if (be == null)
            {
                return(false);
            }

            if (!be.CanReceiveAny)
            {
                return(false);
            }
            KeyValuePair <ItemStack, int> contents = GetContents(byEntity.World, slot.Itemstack);

            if (!be.CanReceive(contents.Key))
            {
                return(false);
            }

            float speed = 1.5f;
            float temp  = GetTemperature(byEntity.World, slot.Itemstack);

            if (byEntity.World is IClientWorldAccessor)
            {
                ModelTransform tf = new ModelTransform();
                tf.EnsureDefaultValues();

                tf.Origin.Set(0.5f, 0.2f, 0.5f);
                tf.Translation.Set(0, 0, -Math.Min(0.25f, speed * secondsUsed / 4));
                tf.Scale      = 1f + Math.Min(0.25f, speed * secondsUsed / 4);
                tf.Rotation.X = Math.Max(-110, -secondsUsed * 90 * speed);
                byEntity.Controls.UsingHeldItemTransformBefore = tf;
            }

            IPlayer byPlayer = null;

            if (byEntity is EntityPlayer)
            {
                byPlayer = byEntity.World.PlayerByUid(((EntityPlayer)byEntity).PlayerUID);
            }


            if (secondsUsed > 1 / speed)
            {
                if ((int)(30 * secondsUsed) % 3 == 1)
                {
                    Vec3d pos =
                        byEntity.Pos.XYZ
                        .Ahead(0.1f, byEntity.Pos.Pitch, byEntity.Pos.Yaw)
                        .Ahead(1.0f, byEntity.Pos.Pitch, byEntity.Pos.Yaw - GameMath.PIHALF)
                    ;
                    pos.Y += byEntity.EyeHeight - 0.4f;

                    smokePouring.minPos = pos.AddCopy(-0.15, -0.15, -0.15);

                    Vec3d blockpos = blockSel.Position.ToVec3d().Add(0.5, 0.2, 0.5);

                    bigMetalSparks.minQuantity = Math.Max(0.2f, 1 - (secondsUsed - 1) / 4);

                    if ((int)(30 * secondsUsed) % 7 == 1)
                    {
                        bigMetalSparks.minPos = pos;
                        bigMetalSparks.minVelocity.Set(-2, -1, -2);
                        bigMetalSparks.addVelocity.Set(4, 1, 4);
                        byEntity.World.SpawnParticles(bigMetalSparks, byPlayer);

                        byEntity.World.SpawnParticles(smokePouring, byPlayer);
                    }

                    float     y2       = 0;
                    Block     block    = byEntity.World.BlockAccessor.GetBlock(blockSel.Position);
                    Cuboidf[] collboxs = block.GetCollisionBoxes(byEntity.World.BlockAccessor, blockSel.Position);
                    for (int i = 0; collboxs != null && i < collboxs.Length; i++)
                    {
                        y2 = Math.Max(y2, collboxs[i].Y2);
                    }

                    // Metal Spark on the mold
                    bigMetalSparks.minVelocity.Set(-2, 1, -2);
                    bigMetalSparks.addVelocity.Set(4, 5, 4);
                    bigMetalSparks.minPos = blockpos.AddCopy(-0.25, y2 - 2 / 16f, -0.25);
                    bigMetalSparks.addPos.Set(0.5, 0, 0.5);
                    bigMetalSparks.glowLevel = (byte)GameMath.Clamp((int)temp - 770, 48, 128);
                    byEntity.World.SpawnParticles(bigMetalSparks, byPlayer);

                    // Smoke on the mold
                    byEntity.World.SpawnParticles(
                        Math.Max(1, 12 - (secondsUsed - 1) * 6),
                        ColorUtil.ToRgba(50, 220, 220, 220),
                        blockpos.AddCopy(-0.5, y2 - 2 / 16f, -0.5),
                        blockpos.Add(0.5, y2 - 2 / 16f + 0.15, 0.5),
                        new Vec3f(-0.5f, 0f, -0.5f),
                        new Vec3f(0.5f, 0f, 0.5f),
                        1.5f,
                        -0.05f,
                        0.75f,
                        EnumParticleModel.Quad,
                        byPlayer
                        );
                }

                int transferedAmount = Math.Min(2, contents.Value);


                be.ReceiveLiquidMetal(contents.Key, ref transferedAmount, temp);

                int newAmount = Math.Max(0, contents.Value - (2 - transferedAmount));
                slot.Itemstack.Attributes.SetInt("units", newAmount);


                if (newAmount <= 0 && byEntity.World is IServerWorldAccessor)
                {
                    slot.Itemstack = new ItemStack(byEntity.World.GetBlock(new AssetLocation(CodeWithoutParts(1) + "-burned")));
                    slot.MarkDirty();
                    // Since we change the item stack we have to call this ourselves
                    OnHeldInteractStop(secondsUsed, slot, byEntity, blockSel, entitySel);
                    return(false);
                }

                return(true);
            }

            return(true);
        }
 public static void ScaleMesh(Mesh d3dMesh, Vec3d vSize)
 {
     ScaleMesh(d3dMesh, (float) vSize.X, (float) vSize.Y, (float) vSize.Z);
 }
        protected override void CalculateDistanceFromCamera()
        {
            Vector3 v3Tmp = this.Worldlocation;

            v3Tmp.TransformCoordinate(CombinedTransformationMatrix  * Device.Transform.World1);

            Vec3d dvTmp = new Vec3d(null, v3Tmp.X, v3Tmp.Y, v3Tmp.Z);
            this.m_fDistFromCamera = dvTmp.Distance(this.ParentStructure.BodyEditor.BodyView.CameraPosition);
        }
        protected virtual void SelectPart(int iX, int iY)
        {
            if(Editor.PhysicalStructure.RootBody != null)
            {
                AnimatTools.DataObjects.Physical.BodyPart bpTmpSelected = null;
                System.Collections.ArrayList colSelected; //list of all elements selected
                bool bCurrentSelectedInList = false;

                //lets find which ones are selected
                colSelected = Editor.PhysicalStructure.TestIntersection(iX, iY, Editor.CommandBar.CommandMode);

                //find out which body is the closest one selected
                foreach (AnimatTools.DataObjects.Physical.BodyPart bpPart in colSelected)
                {
                    if(this.Editor.PropertiesBar.SelectedPart != null && bpPart == this.Editor.PropertiesBar.SelectedPart)
                        bCurrentSelectedInList = true;

                    //got to have at least one body selected if we're in this loop
                    if(bpTmpSelected == null)
                        bpTmpSelected = bpPart;

                    //if rbTmp is closer to the camera than the current selected one
                    //change the current one to the selected one
                    if(bpPart.IntersectionDistance < bpTmpSelected.IntersectionDistance)
                        bpTmpSelected = bpPart;
                }

                if(Editor.CommandBar.CommandMode != AnimatTools.Forms.BodyPlan.Command.enumCommandMode.SelectReceptiveFields || this.Editor.PropertiesBar.SelectedPart == null
                     || this.Editor.PropertiesBar.SelectedPart is AnimatTools.DataObjects.Physical.Joint)
                    this.Editor.PropertiesBar.SelectPart(bpTmpSelected, this.IsCtrlKeyPressed);
                else
                {
                    //If we are in receptive field mode and their is a selcted rigid body part then lets test to see if the user is attempting to
                    //select one of the receptive fields.
                    if(bCurrentSelectedInList)
                    {
                        RigidBodies.RigidBody_DX rbPart = (RigidBodies.RigidBody_DX ) this.Editor.PropertiesBar.SelectedPart;
                        Vec3d vVertex = new Vec3d(null, 0,0,0);

                        if(rbPart.TestReceptiveFieldIntersection(iX, iY, ref vVertex))
                            rbPart.SelectedReceptiveField = vVertex;
                        else
                            this.Editor.PropertiesBar.SelectPart(bpTmpSelected, this.IsCtrlKeyPressed);
                    }
                    else
                        this.Editor.PropertiesBar.SelectPart(bpTmpSelected, this.IsCtrlKeyPressed);
                }
            }
        }
        //float yawOffset;

        private void updateTargetPos()
        {
            float yaw = (float)Math.Atan2(targetEntity.ServerPos.X - entity.ServerPos.X, targetEntity.ServerPos.Z - entity.ServerPos.Z);

            /*tmpVec = tmpVec.Set(entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z);
             * tmpVec.Ahead(10, 0, yaw - GameMath.PI / 2);
             *
             * int tries = 10;
             * double dx, dy, dz;
             * while (tries-- > 0)
             * {
             *  dx = rand.NextDouble() * 8 - 4;
             *  dy = rand.NextDouble() * 8 - 4;
             *  dz = rand.NextDouble() * 8 - 4;
             *
             *  if (entity.Properties.Habitat == EnumHabitat.Land)
             *  {
             *      tmpVec.Y = moveDownToFloor((int)tmpVec.X, tmpVec.Y, (int)tmpVec.Z);
             *  }
             *
             *  tmpVec.Add(dx, dx, dz);
             *
             *  pathTraverser.NavigateTo(targetPos, moveSpeed, 1, OnGoalReached, OnStuck, tries > 0, 999, true);
             * }*/


            // Some simple steering behavior, works really suxy
            tmpVec = tmpVec.Set(entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z);
            tmpVec.Ahead(0.9, 0, yaw - GameMath.PI / 2);

            // Running into wall?
            if (traversable(tmpVec))
            {
                //yawOffset = 0;
                targetPos.Set(entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z).Ahead(10, 0, yaw - GameMath.PI / 2);
                return;
            }

            // Try 90 degrees left
            tmpVec = tmpVec.Set(entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z);
            tmpVec.Ahead(0.9, 0, yaw - GameMath.PI);
            if (traversable(tmpVec))
            {
                targetPos.Set(entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z).Ahead(10, 0, yaw - GameMath.PI);
                return;
            }

            // Try 90 degrees right
            tmpVec = tmpVec.Set(entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z);
            tmpVec.Ahead(0.9, 0, yaw);
            if (traversable(tmpVec))
            {
                targetPos.Set(entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z).Ahead(10, 0, yaw);
                return;
            }

            // Run towards target o.O
            tmpVec = tmpVec.Set(entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z);
            tmpVec.Ahead(0.9, 0, -yaw);
            //if (traversable(tmpVec))
            {
                targetPos.Set(entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z).Ahead(10, 0, -yaw);
                return;
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="origin"></param>
 /// <param name="scale"></param>
 /// <param name="countX"></param>
 /// <param name="countY"></param>
 /// <param name="countZ"></param>
 /// <param name="wrapModeX"></param>
 /// <param name="wrapModeY"></param>
 /// <param name="wrapModeZ"></param>
 /// <param name="sampleMode"></param>
 public GridScalarField3d(Vec3d origin, Vec3d scale, int countX, int countY, int countZ, WrapMode wrapModeX, WrapMode wrapModeY, WrapMode wrapModeZ, SampleMode sampleMode = SampleMode.Linear)
     : base(origin, scale, countX, countY, countZ, wrapModeX, wrapModeY, wrapModeZ, sampleMode)
 {
 }
        public override bool OnHeldInteractStep(float secondsUsed, ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel)
        {
            if (blockSel == null)
            {
                return(false);
            }
            if (slot.Itemstack.TempAttributes.GetInt("refilled") > 0)
            {
                return(false);
            }

            float prevsecondsused = slot.Itemstack.TempAttributes.GetFloat("secondsUsed");

            slot.Itemstack.TempAttributes.SetFloat("secondsUsed", secondsUsed);

            float remainingwater = GetRemainingWateringSeconds(slot.Itemstack);

            SetRemainingWateringSeconds(slot.Itemstack, remainingwater -= secondsUsed - prevsecondsused);


            if (remainingwater <= 0)
            {
                return(false);
            }

            IWorldAccessor world = byEntity.World;

            BlockPos targetPos = blockSel.Position;

            Block facingBlock = world.BlockAccessor.GetBlock(blockSel.Position.AddCopy(blockSel.Face));

            if (facingBlock.Code.Path == "fire")
            {
                world.BlockAccessor.SetBlock(0, blockSel.Position.AddCopy(blockSel.Face));
            }

            Block block           = world.BlockAccessor.GetBlock(blockSel.Position);
            bool  notOnSolidblock = false;

            if ((block.CollisionBoxes == null || block.CollisionBoxes.Length == 0) && !block.IsLiquid())
            {
                notOnSolidblock = true;
                targetPos       = targetPos.DownCopy();
            }

            BlockEntityFarmland be = world.BlockAccessor.GetBlockEntity(targetPos) as BlockEntityFarmland;

            if (be != null)
            {
                be.WaterFarmland(secondsUsed - prevsecondsused);
            }

            float speed = 4f;

            if (world.Side == EnumAppSide.Client)
            {
                ModelTransform tf = new ModelTransform();
                tf.EnsureDefaultValues();

                tf.Origin.Set(0.5f, 0.2f, 0.5f);
                tf.Translation.Set(-Math.Min(0.25f, speed * secondsUsed / 4), 0, 0);

                tf.Rotation.Z = GameMath.Min(60, secondsUsed * 90 * speed, 80 - remainingwater * 5);
                byEntity.Controls.UsingHeldItemTransformBefore = tf;
            }

            IPlayer byPlayer = null;

            if (byEntity is EntityPlayer)
            {
                byPlayer = byEntity.World.PlayerByUid(((EntityPlayer)byEntity).PlayerUID);
            }


            if (secondsUsed > 1 / speed)
            {
                Vec3d pos = blockSel.Position.ToVec3d().Add(blockSel.HitPosition);
                if (notOnSolidblock)
                {
                    pos.Y = (int)pos.Y + 0.05;
                }
                WaterParticles.minPos = pos.Add(-0.125 / 2, 1 / 16f, -0.125 / 2);
                byEntity.World.SpawnParticles(WaterParticles, byPlayer);
            }

            return(true);
        }
Example #11
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="r0"></param>
 /// <param name="r1"></param>
 /// <param name="p0"></param>
 /// <param name="p1"></param>
 public void Set(Vec3d p0, Vec3d p1)
 {
     _delta = p1 - p0;
 }
Example #12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="i0"></param>
 /// <param name="i1"></param>
 /// <param name="p0"></param>
 /// <param name="r0"></param>
 /// <param name="p1"></param>
 /// <param name="r1"></param>
 /// <param name="weight"></param>
 public Translation(int i0, int i1, Vec3d p0, Vec3d p1, double weight = 1.0)
     : this(i0, i1)
 {
     Set(p0, p1);
 }
Example #13
0
 /// <inheritdoc />
 public sealed override void GradientAt(Vec3d point, out double gx, out double gy, out double gz)
 {
     throw new NotImplementedException();
 }
 public abstract Vec3f GetVelocity(Vec3d pos);
 public static Mesh CreateBox(Microsoft.DirectX.Direct3D.Device d3dDevice, Vec3d vSize)
 {
     return CreateBox(d3dDevice, (float) vSize.X, (float) vSize.Y, (float) vSize.Z);
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="point"></param>
 /// <returns></returns>
 public Vec3d GradientAt(Vec3d point)
 {
     // TODO
     throw new NotImplementedException();
 }
Example #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="point"></param>
        /// <param name="scale"></param>
        /// <returns></returns>
        public static double Box(Vec3d point, Vec3d scale)
        {
            var d = Vec3d.Abs(point) - scale;

            return(Math.Min(d.ComponentMax, 0.0) + Vec3d.Min(d, 0.0).Length);
        }
Example #18
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="acceleration"></param>
 /// <param name="capacity"></param>
 /// <param name="strength"></param>
 public FalseWeight(int index, Vec3d acceleration, double strength = 1.0)
 {
     _handle.Index = index;
     _acceleration = acceleration;
     Strength      = strength;
 }
Example #19
0
        private void ribbonButton51_Click(object sender, EventArgs e)
        {
            if (featurePrimitiveLineString == null)
            {
                LineStringGeometry lineString = new LineStringGeometry();
                Vec3d vec3d1 = new Vec3d();
                vec3d1.set(-74, 40.714, 0);
                Vec3d vec3d2 = new Vec3d();
                vec3d2.set(139.75, 35.68, 0);
                lineString.push_back(vec3d1);
                lineString.push_back(vec3d2);

                Feature feature = new Feature();
                feature.setGeometry( lineString );
                featurePrimitiveLineString = new FeaturePrimitive();
                featurePrimitiveLineString.setFeature( feature );
                m_earthRoot.addChild( featurePrimitiveLineString );
            }
        }
Example #20
0
 public override void FinishExecute(bool cancelled)
 {
     base.FinishExecute(cancelled);
     targetPos = null;
     pathTraverser.Stop();
 }
        public override void SaveData(ref AnimatTools.DataObjects.Simulation dsSim, ref AnimatTools.DataObjects.Physical.PhysicalStructure doStructure, ref AnimatTools.Interfaces.StdXml oXml)
        {
            base.SaveData (ref dsSim, ref doStructure, ref oXml);

            oXml.IntoElem();

            if(!oXml.FindChildElement("Constraint", false))
                oXml.AddChildElement("Constraint");
            oXml.IntoElem();
            oXml.SetAttrib("Low",this.m_fltMinMovement);
            oXml.SetAttrib("High", this.m_fltMaxMovement);
            oXml.OutOfElem();

            oXml.AddChildElement("Length", m_fltLength);
            oXml.AddChildElement("EnableMotor",this.m_bEnableMotor);
            oXml.AddChildElement("ServoMotor",this.m_bServoMotor);
            oXml.AddChildElement("ServoGain",this.m_fltServoGain);
            m_snMaxForce.SaveData(ref oXml, "MaxForce");
            m_snMaxVelocity.SaveData(ref oXml, "MaxVelocity");

            RigidBodies.RigidBody_DX rbParent = (RigidBodies.RigidBody_DX)this.Parent;
            Vector3 v3Rot = Util_DX.DecomposeXYZRotationMatrix(this.CombinedTransformationMatrix);;
            float x = Geometry.DegreeToRadian(180);
            m_v3Axis.TransformCoordinate(Matrix.RotationX(Geometry.DegreeToRadian(180)) * Matrix.RotationY(Geometry.DegreeToRadian(180)) * Matrix.RotationZ(Geometry.DegreeToRadian(180)) * Matrix.RotationX(v3Rot.X)* Matrix.RotationY(v3Rot.Y) * Matrix.RotationZ(v3Rot.Z));
            Vec3d vRotationAxis = new Vec3d(null,m_v3Axis.X, m_v3Axis.Y, m_v3Axis.Z);
            Util.SaveVector(ref oXml, "RotationAxis", vRotationAxis);
            m_v3Axis = new Vector3(0,0,1);

            oXml.OutOfElem();
        }
Example #22
0
        /// <summary>
        /// Performs the physics on the specified entity.
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pos"></param>
        public void DoPhysics(float dt, EntityPos pos)
        {
            Vec3d motionBefore       = pos.Motion.Clone();
            bool  feetInLiquidBefore = entity.FeetInLiquid;
            bool  onGroundBefore     = entity.OnGround;
            bool  swimmingBefore     = entity.Swimming;
            bool  onCollidedBefore   = entity.Collided;

            float dtFac = 60 * dt;

            Block belowBlock = entity.World.BlockAccessor.GetBlock((int)pos.X, (int)(pos.Y - 0.05f), (int)pos.Z);

            // On ground drag
            if (entity.OnGround)
            {
                if (!entity.FeetInLiquid)
                {
                    pos.Motion.X *= (1 - groundDragFactor * belowBlock.DragMultiplier);
                    pos.Motion.Z *= (1 - groundDragFactor * belowBlock.DragMultiplier);
                }
            }

            // Water or air drag
            if (entity.FeetInLiquid || entity.Swimming)
            {
                pos.Motion *= (float)Math.Pow(waterDragValue, dt * 33);
            }
            else
            {
                pos.Motion *= (float)Math.Pow(airDragValue, dt * 33);
            }

            Block inblock    = entity.World.BlockAccessor.GetBlock((int)pos.X, (int)(pos.Y), (int)pos.Z);
            Block aboveblock = entity.World.BlockAccessor.GetBlock((int)pos.X, (int)(pos.Y + 1), (int)pos.Z);

            if (entity.FeetInLiquid)
            {
                Vec3d pushvec = inblock.PushVector;
                if (pushvec != null)
                {
                    float pushstrength = 0.3f * 1000f / GameMath.Clamp(entity.MaterialDensity, 750, 2500) * dtFac;

                    pos.Motion.Add(
                        pushvec.X * pushstrength,
                        pushvec.Y * pushstrength,
                        pushvec.Z * pushstrength
                        );
                }
            }


            // Gravity
            if (pos.Y > -100 && entity.ApplyGravity)
            {
                double gravStrength = gravityPerSecond / 60f * dtFac + Math.Max(0, -0.015f * pos.Motion.Y * dtFac);

                if (entity.Swimming)
                {
                    // above 0 => floats
                    // below 0 => sinks
                    float baseboyancy = GameMath.Clamp(1 - entity.MaterialDensity / inblock.MaterialDensity, -1, 1);

                    float waterY = (int)pos.Y + inblock.LiquidLevel / 8f + (aboveblock.IsLiquid() ? 9 / 8f : 0);

                    float bottomSubmergedness = waterY - (float)pos.Y;

                    // 0 = at swim line
                    // 1 = completely submerged
                    float swimlineSubmergedness = GameMath.Clamp(bottomSubmergedness - (entity.CollisionBox.Y2 - (float)entity.SwimmingOffsetY), 0, 1);

                    double boyancyStrength = GameMath.Clamp(60 * baseboyancy * swimlineSubmergedness, -1.5f, 1.5f) - 1;

                    double waterDrag = GameMath.Clamp(100 * Math.Abs(pos.Motion.Y * dtFac) - 0.02f, 1, 1.25f);

                    pos.Motion.Y += gravStrength * boyancyStrength;
                    pos.Motion.Y /= waterDrag;
                }
                else
                {
                    pos.Motion.Y -= gravStrength;
                }
            }


            moveDelta.Set(pos.Motion.X * dtFac, pos.Motion.Y * dtFac, pos.Motion.Z * dtFac);
            nextPosition.Set(pos.X + moveDelta.X, pos.Y + moveDelta.Y, pos.Z + moveDelta.Z);


            bool falling = pos.Motion.Y < 0;

            entity.World.CollisionTester.ApplyTerrainCollision(entity, pos, dtFac, ref outposition);



            if (entity.World.BlockAccessor.IsNotTraversable((int)(pos.X + moveDelta.X), (int)pos.Y, (int)pos.Z))
            {
                outposition.X = pos.X;
            }
            if (entity.World.BlockAccessor.IsNotTraversable((int)pos.X, (int)(pos.Y + moveDelta.Y), (int)pos.Z))
            {
                outposition.Y = pos.Y;
            }
            if (entity.World.BlockAccessor.IsNotTraversable((int)pos.X, (int)pos.Y, (int)(pos.Z + moveDelta.Z)))
            {
                outposition.Z = pos.Z;
            }

            entity.OnGround = entity.CollidedVertically && falling;
            pos.SetPos(outposition);


            if ((nextPosition.X < outposition.X && pos.Motion.X < 0) || (nextPosition.X > outposition.X && pos.Motion.X > 0))
            {
                pos.Motion.X = 0;
            }

            if ((nextPosition.Y < outposition.Y && pos.Motion.Y < 0) || (nextPosition.Y > outposition.Y && pos.Motion.Y > 0))
            {
                pos.Motion.Y = 0;
            }

            if ((nextPosition.Z < outposition.Z && pos.Motion.Z < 0) || (nextPosition.Z > outposition.Z && pos.Motion.Z > 0))
            {
                pos.Motion.Z = 0;
            }



            Block block = entity.World.BlockAccessor.GetBlock(pos.XInt, pos.YInt, pos.ZInt);

            entity.FeetInLiquid = block.MatterState == EnumMatterState.Liquid;
            entity.InLava       = block.LiquidCode == "lava";
            if (entity.FeetInLiquid)
            {
                float waterY = (int)pos.Y + block.LiquidLevel / 8f + (aboveblock.IsLiquid() ? 9 / 8f : 0);
                float bottomSubmergedness = waterY - (float)pos.Y;

                // 0 = at swim line
                // 1 = completely submerged
                float swimlineSubmergedness = bottomSubmergedness - (entity.CollisionBox.Y2 - (float)entity.SwimmingOffsetY);

                entity.Swimming = swimlineSubmergedness > 0;
            }
            else
            {
                entity.Swimming = false;
            }

            if (!onCollidedBefore && entity.Collided)
            {
                entity.OnCollided();
            }

            if (!onGroundBefore && entity.OnGround)
            {
                entity.OnFallToGround(motionBefore.Y);
            }
            if ((!entity.Swimming && !feetInLiquidBefore && entity.FeetInLiquid) || (!entity.FeetInLiquid && !swimmingBefore && entity.Swimming))
            {
                entity.OnCollideWithLiquid();
            }
            if (!falling || entity.OnGround)
            {
                entity.PositionBeforeFalling.Set(outposition);
            }

            if (GlobalConstants.OutsideWorld(pos.X, pos.Y, pos.Z, entity.World.BlockAccessor))
            {
                entity.DespawnReason = new EntityDespawnReason()
                {
                    reason = EnumDespawnReason.Death, damageSourceForDeath = new DamageSource()
                    {
                        Source = EnumDamageSource.Fall
                    }
                };
                return;
            }

            Cuboidd entityBox = entity.World.CollisionTester.entityBox;

            for (int y = (int)entityBox.Y1; y <= (int)entityBox.Y2; y++)
            {
                for (int x = (int)entityBox.X1; x <= (int)entityBox.X2; x++)
                {
                    for (int z = (int)entityBox.Z1; z <= (int)entityBox.Z2; z++)
                    {
                        entity.World.CollisionTester.tmpPos.Set(x, y, z);
                        entity.World.CollisionTester.tempCuboid.Set(x, y, z, x + 1, y + 1, z + 1);
                        if (entity.World.CollisionTester.tempCuboid.IntersectsOrTouches(entityBox))
                        {
                            entity.World.BlockAccessor.GetBlock(x, y, z).OnEntityInside(entity.World, entity, entity.World.CollisionTester.tmpPos);
                        }
                    }
                }
            }

            OnPhysicsTickCallback?.Invoke(dtFac);
        }
        public override void SaveData(ref AnimatTools.DataObjects.Simulation dsSim, ref AnimatTools.DataObjects.Physical.PhysicalStructure doStructure, ref AnimatTools.Interfaces.StdXml oXml)
        {
            base.SaveData (ref dsSim, ref doStructure, ref oXml);

            oXml.IntoElem();

            RigidBodies.RigidBody_DX rbParent = (RigidBodies.RigidBody_DX)this.Parent;
            Vector3 v3Rot = Util_DX.DecomposeXYZRotationMatrix(this.CombinedTransformationMatrix);;
            float x = Geometry.DegreeToRadian(180);

            if(!oXml.FindChildElement("Constraint", false))
                oXml.AddChildElement("Constraint");
            oXml.IntoElem();
            oXml.SetAttrib("Low",this.m_fltMinAngle);
            oXml.SetAttrib("High", this.m_fltMaxAngle);
            oXml.OutOfElem();

            oXml.AddChildElement("EnableMotor",this.m_bEnableMotor);
            oXml.AddChildElement("ServoMotor",this.m_bServoMotor);
            oXml.AddChildElement("ServoGain",this.m_fltServoGain);

            m_snMaxTorque.SaveData(ref oXml, "MaxTorque");
            m_snMaxVelocity.SaveData(ref oXml, "MaxVelocity");

            //			if(v3Rot.Y >= 180)
            //				m_v3Axis.TransformCoordinate(/*Matrix.RotationX(Geometry.DegreeToRadian(180))*  Matrix.RotationY(Geometry.DegreeToRadian(180)) * Matrix.RotationZ(Geometry.DegreeToRadian(180)) **/ Matrix.RotationX(v3Rot.X)* Matrix.RotationY(v3Rot.Y) * Matrix.RotationZ(v3Rot.Z));
            //			else
                //m_v3Axis.TransformCoordinate(Matrix.RotationX(Geometry.DegreeToRadian(180)) * Matrix.RotationY(Geometry.DegreeToRadian(180)) * Matrix.RotationZ(Geometry.DegreeToRadian(180)) * Matrix.RotationX(v3Rot.X)* Matrix.RotationY(v3Rot.Y) * Matrix.RotationZ(v3Rot.Z));
            Matrix m = this.CombinedTransformationMatrix;
            m.M41 = 0;
            m.M42 = 0;
            m.M43 = 0;
            //Quaternion q = Quaternion.RotationYawPitchRoll(v3Rot.Y, v3Rot.X, v3Rot.Z);
            //m_v3Axis.TransformCoordinate(Matrix.RotationQuaternion(q));
            m_v3Axis.TransformCoordinate(m);

            //Vec3d vRotationAxis = new Vec3d(null,1, 0, 0);
            Vec3d vRotationAxis = new Vec3d(null,m_v3Axis.X, m_v3Axis.Y, m_v3Axis.Z);
            Util.SaveVector(ref oXml, "RotationAxis", vRotationAxis);

            oXml.OutOfElem();
            m_v3Axis = new Vector3(0,0,1);
        }
Example #24
0
 /// <inheritdoc />
 void IBody.ApplyTorque(Vec3d delta)
 {
     throw new NotSupportedException(_rotationErrorMessage);
 }
Example #25
0
 /// <inheritdoc />
 public void Calculate(IReadOnlyList <IBody> bodies)
 {
     _handle.Delta = Vec3d.Reject(_start - bodies[_handle].Position, _direction);
 }
Example #26
0
 /// <inheritdoc />
 void IBody.ApplyRotate(Vec3d delta, double weight)
 {
     throw new NotSupportedException(_rotationErrorMessage);
 }
Example #27
0
        public override void OnHeldInteractStart(ItemSlot slot, EntityAgent byEntity, BlockSelection blockSel, EntitySelection entitySel, bool firstEvent, ref EnumHandHandling handling)
        {
            if (blockSel != null)
            {
                if ((byEntity as EntityPlayer)?.Player != null && !api.World.Claims.TryAccess((byEntity as EntityPlayer)?.Player, blockSel.Position, EnumBlockAccessFlags.BuildOrBreak))
                {
                    return;
                }
                if (byEntity.Controls.Sprint)
                {
                    handling = EnumHandHandling.PreventDefault;
                    //if (byEntity.Api.Side == EnumAppSide.Client) return;
                    ITreeAttribute start;
                    Vec3d          pos = blockSel.Position.ToVec3d();

                    if ((start = slot.Itemstack.TempAttributes.GetTreeAttribute("startPoint")) != null)
                    {
                        ITreeAttribute box = slot.Itemstack.Attributes.GetOrAddTreeAttribute("workArea");

                        box.SetDouble("x1", start.GetDouble("x1") > pos.X ? pos.X : start.GetDouble("x1"));
                        box.SetDouble("y1", start.GetDouble("y1") > pos.Y ? pos.Y : start.GetDouble("y1"));
                        box.SetDouble("z1", start.GetDouble("z1") > pos.Z ? pos.Z : start.GetDouble("z1"));
                        box.SetDouble("x2", (start.GetDouble("x1") > pos.X ? start.GetDouble("x1") : pos.X) + 1);
                        box.SetDouble("y2", (start.GetDouble("y1") > pos.Y ? start.GetDouble("y1") : pos.Y));
                        box.SetDouble("z2", (start.GetDouble("z1") > pos.Z ? start.GetDouble("z1") : pos.Z) + 1);

                        slot.Itemstack.TempAttributes.RemoveAttribute("startPoint");
                        ((byEntity as EntityPlayer)?.Player as IServerPlayer)?.SendMessage(GlobalConstants.InfoLogChatGroup, Lang.Get("temporalhack:work-area"), EnumChatType.Notification);
                    }
                    else
                    {
                        slot.Itemstack.Attributes.RemoveAttribute("workArea");

                        start = slot.Itemstack.TempAttributes.GetOrAddTreeAttribute("startPoint");
                        start.SetDouble("x1", pos.X);
                        start.SetDouble("y1", pos.Y);
                        start.SetDouble("z1", pos.Z);

                        ((byEntity as EntityPlayer)?.Player as IServerPlayer)?.SendMessage(GlobalConstants.InfoLogChatGroup, Lang.Get("temporalhack:work-start"), EnumChatType.Notification);
                    }

                    return;
                }

                if (byEntity.Controls.Sneak)
                {
                    handling = EnumHandHandling.PreventDefault;
                    //if (byEntity.Api.Side == EnumAppSide.Client) return;
                    ITreeAttribute tree;
                    BlockEntity    sel = api.World.BlockAccessor.GetBlockEntity(blockSel.Position);

                    if (sel is BlockEntityBarrel)
                    {
                        tree = slot.Itemstack.Attributes.GetOrAddTreeAttribute("workBarrel");
                        tree.SetInt("x", blockSel.Position.X);
                        tree.SetInt("y", blockSel.Position.Y);
                        tree.SetInt("z", blockSel.Position.Z);

                        ((byEntity as EntityPlayer)?.Player as IServerPlayer)?.SendMessage(GlobalConstants.InfoLogChatGroup, Lang.Get("temporalhack:work-barrel"), EnumChatType.Notification);
                    }
                    else if (sel is BlockEntityGenericTypedContainer)
                    {
                        //System.Diagnostics.Debug.WriteLine(blockSel.Position.X + "," + blockSel.Position.Y + "," + blockSel.Position.Z);
                        tree = slot.Itemstack.Attributes.GetOrAddTreeAttribute("workChest");
                        tree.SetInt("x", blockSel.Position.X);
                        tree.SetInt("y", blockSel.Position.Y);
                        tree.SetInt("z", blockSel.Position.Z);

                        ((byEntity as EntityPlayer)?.Player as IServerPlayer)?.SendMessage(GlobalConstants.InfoLogChatGroup, Lang.Get("temporalhack:work-chest"), EnumChatType.Notification);
                    }

                    return;
                }
            }
            else
            {
                if (byEntity.Controls.Sprint && !(entitySel?.Entity is EntityLocust))
                {
                    handling = EnumHandHandling.PreventDefault;
                    if (slot.Itemstack.Attributes.GetBool("recordMode"))
                    {
                        slot.Itemstack.Attributes.SetBool("recordMode", false);
                        ((byEntity as EntityPlayer)?.Player as IServerPlayer)?.SendMessage(GlobalConstants.InfoLogChatGroup, Lang.Get("temporalhack:work-itemcacheoff"), EnumChatType.Notification);
                    }
                    else
                    {
                        slot.Itemstack.Attributes.SetBool("recordMode", true);
                        ((byEntity as EntityPlayer)?.Player as IServerPlayer)?.SendMessage(GlobalConstants.InfoLogChatGroup, Lang.Get("temporalhack:work-itemcacheon"), EnumChatType.Notification);
                    }
                }
            }
        }
Example #28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="position"></param>
 public Particle(Vec3d position)
 {
     _position = position;
 }
Example #29
0
 /// <summary>
 /// Replace X value
 /// </summary>
 /// <param name="v3"></param>
 /// <param name="x"></param>
 /// <returns></returns>
 public static Vec3d SetX(this Vec3d v3, decimal x)
 {
     return(new Vec3d(x, v3.Y, v3.Z));
 }
Example #30
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="other"></param>
 public Particle(Particle other)
 {
     _position = other._position;
     _velocity = other._velocity;
     _mass     = other._mass;
 }
Example #31
0
 /// <summary>
 /// Replace Z value
 /// </summary>
 /// <param name="v3"></param>
 /// <param name="z"></param>
 /// <returns></returns>
 public static Vec3d SetZ(this Vec3d v3, decimal z)
 {
     return(new Vec3d(v3.X, v3.Y, z));
 }
Example #32
0
 /// <inheritdoc />
 public void ApplyForce(Vec3d delta)
 {
     _forceSum += delta;
 }
Example #33
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="point"></param>
 /// <param name="radius"></param>
 /// <returns></returns>
 public static double Sphere(Vec3d point, double radius)
 {
     return(point.Length - radius);
 }
Example #34
0
 /// <inheritdoc />
 public void ApplyMove(Vec3d delta, double weight)
 {
     _moveSum       += delta * weight;
     _moveWeightSum += weight;
 }
Example #35
0
        public void TickEvery25ms(float dt)
        {
            if (ws.api.Side == EnumAppSide.Client)
            {
                clientUpdate(dt);
            }
            else
            {
                double nowTotalHours = ws.api.World.Calendar.TotalHours;
                int    i             = 0;
                while (nowTotalHours - LastUpdateTotalHours > 1 && i++ < 1000)
                {
                    TickEveryInGameHourServer(LastUpdateTotalHours);
                    LastUpdateTotalHours++;
                }

                var   rnd = ws.api.World.Rand;
                float targetLightninMinTemp = CurWeatherEvent.State.LightningMinTemp;
                if (rnd.NextDouble() < CurWeatherEvent.State.LightningRate)
                {
                    ClimateCondition nowcond = ws.api.World.BlockAccessor.GetClimateAt(regionCenterPos, EnumGetClimateMode.ForSuppliedDateValues, ws.api.World.Calendar.TotalDays);
                    if (nowcond.Temperature >= targetLightninMinTemp && nowcond.RainCloudOverlay > 0.15)
                    {
                        Vec3d pos = regionCenterPos.ToVec3d().Add(-200 + rnd.NextDouble() * 400, ws.api.World.SeaLevel, -200 + rnd.NextDouble() * 400);
                        ws.SpawnLightningFlash(pos);
                    }
                }
            }

            if (Transitioning)
            {
                float speed = ws.api.World.Calendar.SpeedOfTime / 60f;
                Weight += dt / TransitionDelay * speed;

                if (Weight > 1)
                {
                    Transitioning = false;
                    Weight        = 1;
                }
            }
            else
            {
                if (ws.autoChangePatterns && ws.api.Side == EnumAppSide.Server && ws.api.World.Calendar.TotalHours > NewWePattern.State.ActiveUntilTotalHours)
                {
                    TriggerTransition();
                }
            }

            if (ws.autoChangePatterns && ws.api.Side == EnumAppSide.Server)
            {
                bool sendPacket = false;

                if (ws.api.World.Calendar.TotalHours > CurWindPattern.State.ActiveUntilTotalHours)
                {
                    CurWindPattern = WindPatterns[Rand.NextInt(WindPatterns.Length)];
                    CurWindPattern.OnBeginUse();
                    sendPacket = true;
                }

                if (ws.api.World.Calendar.TotalHours > CurWeatherEvent.State.ActiveUntilTotalHours || CurWeatherEvent.ShouldStop(weatherData.climateCond.Rainfall, weatherData.climateCond.Temperature))
                {
                    CurWeatherEvent = RandomWeatherEvent();
                    CurWeatherEvent.OnBeginUse();
                    sendPacket = true;
                }

                if (sendPacket)
                {
                    wsServer.SendWeatherStateUpdate(new WeatherState()
                    {
                        RegionX         = regionX,
                        RegionZ         = regionZ,
                        NewPattern      = NewWePattern.State,
                        OldPattern      = OldWePattern.State,
                        WindPattern     = CurWindPattern.State,
                        WeatherEvent    = CurWeatherEvent?.State,
                        TransitionDelay = TransitionDelay,
                        Transitioning   = Transitioning,
                        Weight          = Weight,
                        LcgCurrentSeed  = Rand.currentSeed,
                        LcgMapGenSeed   = Rand.mapGenSeed,
                        LcgWorldSeed    = Rand.worldSeed
                    });
                }
            }


            NewWePattern.Update(dt);
            OldWePattern.Update(dt);

            CurWindPattern.Update(dt);
            CurWeatherEvent.Update(dt);

            float curWindSpeed    = weatherData.curWindSpeed.X;
            float targetWindSpeed = (float)GetWindSpeed(ws.api.World.SeaLevel);

            curWindSpeed += GameMath.Clamp((targetWindSpeed - curWindSpeed) * dt, -0.001f, 0.001f);
            weatherData.curWindSpeed.X = curWindSpeed;

            quarterSecAccum += dt;
            if (quarterSecAccum > 0.25f)
            {
                regionCenterPos.Y = ws.api.World.BlockAccessor.GetRainMapHeightAt(regionCenterPos);
                if (regionCenterPos.Y == 0)
                {
                    regionCenterPos.Y = ws.api.World.SeaLevel;                         // Map chunk might not be loaded. In that case y will be 0.
                }
                ClimateCondition nowcond = ws.api.World.BlockAccessor.GetClimateAt(regionCenterPos);
                if (nowcond != null)
                {
                    weatherData.climateCond = nowcond;
                }

                quarterSecAccum = 0;
            }

            weatherData.BlendedPrecType = CurWeatherEvent.State.PrecType;
        }
Example #36
0
        public override void LoadData(ref AnimatTools.DataObjects.Simulation dsSim, ref AnimatTools.DataObjects.Physical.PhysicalStructure doStructure, ref AnimatTools.Interfaces.StdXml oXml)
        {
            base.LoadData (ref dsSim, ref doStructure, ref oXml);

            oXml.IntoElem();
            m_vGraphicsBoxSize = Util.LoadVec3d(ref oXml, "GraphicsBoxSize", this);
            oXml.OutOfElem(); //out of body
        }
 public static extern void core_Mat_push_back_Vec3d(IntPtr self, Vec3d v);
Example #38
0
        public virtual void SetSize(float width, float height, float depth)
        {
            if(m_d3dMesh != null)
            {
                m_d3dMesh.Dispose();
                m_d3dMesh = null;
            }

            if(m_mshSelectedBoundingBox != null)
            {
                this.m_mshSelectedBoundingBox.Dispose();
                this.m_mshSelectedBoundingBox = null;
            }

            if(m_mshCB != null)
            {
                this.m_mshCB.Dispose();
                this.m_mshCB = null;
            }

            if(m_mshLB != null)
            {
                this.m_mshLB.Dispose();
                this.m_mshLB = null;
            }

            m_vGraphicsBoxSize = new Vec3d(null);
            m_vGraphicsBoxSize.X = width;
            m_vGraphicsBoxSize.Y = height;
            m_vGraphicsBoxSize.Z = depth;

            m_d3dMesh = Util_DX.CreateBox(this.Device, width, height, depth);
            //m_d3dMesh = Mesh.Box(this.Device, width, height, depth);

            float fltScale = (this.MaxDimension * 0.15f);
            if(fltScale > 0.3f) fltScale = 0.3f;

            m_mshSelectedBoundingBox = Mesh.Box(Device, (float)(m_vGraphicsBoxSize.X + fltScale),(float)(m_vGraphicsBoxSize.Y + fltScale), (float)(m_vGraphicsBoxSize.Z + fltScale));
            RefreshSelectionBoxSizes();
        }
Example #39
0
        private void ribbonButton53_Click(object sender, EventArgs e)
        {
            if (featurePolygon == null)
            {
                Vec3d vec1 = new Vec3d();
                vec1.set(0, 40, 0);
                Vec3d vec2 = new Vec3d();
                vec2.set(-60, 40, 0);
                Vec3d vec3 = new Vec3d();
                vec3.set(-60, 60, 0);
                Vec3d vec4 = new Vec3d();
                vec4.set( 0, 60, 0 );

                PolygonGeometry polygon = new PolygonGeometry();
                polygon.push_back( vec1 );
                polygon.push_back( vec2 );
                polygon.push_back( vec3 );
                polygon.push_back( vec4 );
                Feature feature = new Feature();
                feature.setGeometry(polygon);
                featurePolygon = new FeaturePrimitive();
                featurePolygon.setFeature( feature );
                m_earthRoot.addChild( featurePolygon );
            }
        }
Example #40
0
        protected override void CloneInternal(AnimatTools.Framework.DataObject doOriginal, bool bCutData, AnimatTools.Framework.DataObject doRoot)
        {
            base.CloneInternal (doOriginal, bCutData, doRoot);

            Box doOrigBody = (Box) doOriginal;
            m_vGraphicsBoxSize = new Vec3d(this, doOrigBody.m_vGraphicsBoxSize.X, doOrigBody.m_vGraphicsBoxSize.Y, doOrigBody.m_vGraphicsBoxSize.Z);

            m_snHeight = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snHeight.Clone(this, bCutData, doRoot);
            m_snWidth = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snWidth.Clone(this, bCutData, doRoot);
            m_snLength = (AnimatTools.Framework.ScaledNumber) doOrigBody.m_snLength.Clone(this, bCutData, doRoot);
        }
 public static extern void calib3d_RQDecomp3x3_Mat(IntPtr src, IntPtr mtxR, IntPtr mtxQ,
     IntPtr qx, IntPtr qy, IntPtr qz, out Vec3d outVal);
Example #42
0
        OrderedDictionary <BlockPos, float> GetNearblyMultibreakables(IWorldAccessor world, BlockPos pos, Vec3d hitPos)
        {
            OrderedDictionary <BlockPos, float> positions = new OrderedDictionary <BlockPos, float>();

            for (int dx = -1; dx <= 1; dx++)
            {
                for (int dy = -1; dy <= 1; dy++)
                {
                    for (int dz = -1; dz <= 1; dz++)
                    {
                        if (dx == 0 && dy == 0 && dz == 0)
                        {
                            continue;
                        }

                        BlockPos dpos = pos.AddCopy(dx, dy, dz);
                        if (CanMultiBreak(world.BlockAccessor.GetBlock(dpos)))
                        {
                            positions.Add(dpos, hitPos.SquareDistanceTo(dpos.X + 0.5, dpos.Y + 0.5, dpos.Z + 0.5));
                        }
                    }
                }
            }

            return(positions);
        }
        public virtual bool TestReceptiveFieldIntersection(int x, int y, ref Vec3d vVertex)
        {
            if(m_d3dReceptiveFieldPoint != null)
            {
                //a temporary intersect information for the selected bounding box
                IntersectInformation iiTmp = new IntersectInformation();
                Vec3d vSelVertex = new Vec3d(null, 0, 0, 0);
                float fltSelDistance = -1;

                //First find all of the vertex points that are intersected.
                foreach(Vec3d vPoint in m_aryReceptiveFields)
                {
                    Matrix mWorld = Matrix.Translation((float) vPoint.X, (float) vPoint.Y, (float) vPoint.Z) * CombinedTransformationMatrix  * Device.Transform.World1;

                    if(Util_DX.TestIntersectWithMouse(m_d3dReceptiveFieldPoint,Device.Viewport, Device.Transform.Projection, Device.Transform.View, mWorld, x, y, out iiTmp))
                    {
                        if(fltSelDistance < 0 || iiTmp.Dist < fltSelDistance)
                        {
                            fltSelDistance = iiTmp.Dist;
                            vSelVertex = vPoint;
                        }
                    }
                }

                if(fltSelDistance > 0)
                {
                    vVertex = vSelVertex;
                    return true;
                }
            }

            return false;
        }
Example #44
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="countX"></param>
        /// <param name="countY"></param>
        /// <param name="origin"></param>
        /// <param name="scale"></param>
        public GridField3d <T> Create(int countX, int countY, int countZ, Vec3d origin, Vec3d scale)
        {
            var result = Create(countX, countY, countZ);

            result.Origin = origin;
            result.Scale  = scale;
            return(result);
        }
        public override void SaveData(ref AnimatTools.DataObjects.Simulation dsSim, ref AnimatTools.DataObjects.Physical.PhysicalStructure doStructure, ref AnimatTools.Interfaces.StdXml oXml)
        {
            base.SaveData (ref dsSim, ref doStructure, ref oXml);
            Vector3 v3Rot = Util_DX.DecomposeXYZRotationMatrix(this.CombinedTransformationMatrix);

            Vector3 rot = m_v3Rotation;
            rot.Normalize();
            AnimatTools.Framework.Vec3d v = new Vec3d(null, rot.X, rot.Y, rot.Z);

            oXml.IntoElem();
                //oXml.AddChildElement("Stiffness", this.Stiffness.ActualValue);
                //oXml.AddChildElement("Damping", this.Damping.ActualValue);
                oXml.AddChildElement("ConstraintHalfAngle",m_fHalfAngle);

                m_v3Axis.TransformCoordinate(Matrix.RotationX(Geometry.DegreeToRadian(180)) * Matrix.RotationY(Geometry.DegreeToRadian(180)) * Matrix.RotationZ(Geometry.DegreeToRadian(180)) * Matrix.RotationX(v3Rot.X)* Matrix.RotationY(v3Rot.Y) * Matrix.RotationZ(v3Rot.Z));

                Vec3d vRotationAxis = new Vec3d(null,m_v3Axis.X, m_v3Axis.Y, m_v3Axis.Z);
                Util.SaveVector(ref oXml, "ConstraintAxis", vRotationAxis);
            oXml.OutOfElem();

            m_v3Axis = new Vector3(0,0,1);
        }
Example #46
0
        public override bool ContinueExecute(float dt)
        {
            Vec3d pos = targetPoi.Position;

            pathTraverser.CurrentTarget.X = pos.X;
            pathTraverser.CurrentTarget.Y = pos.Y;
            pathTraverser.CurrentTarget.Z = pos.Z;

            Cuboidd targetBox = entity.SelectionBox.ToDouble().Translate(entity.ServerPos.X, entity.ServerPos.Y, entity.ServerPos.Z);
            double  distance  = targetBox.ShortestDistanceFrom(pos);

            float minDist = MinDistanceToTarget();

            if (distance <= minDist)
            {
                pathTraverser.Stop();
                if (animMeta != null)
                {
                    entity.AnimManager.StopAnimation(animMeta.Code);
                }

                EntityBehaviorMultiplyBase bh = entity.GetBehavior <EntityBehaviorMultiplyBase>();
                if (bh != null && !bh.ShouldEat)
                {
                    return(false);
                }

                if (targetPoi.IsSuitableFor(entity, entityDiet) != true)
                {
                    return(false);
                }

                if (eatAnimMeta != null && !eatAnimStarted)
                {
                    entity.AnimManager.StartAnimation((targetPoi is LooseItemFoodSource && eatAnimMetaLooseItems != null) ? eatAnimMetaLooseItems : eatAnimMeta);

                    eatAnimStarted = true;
                }

                eatTimeNow += dt;

                if (targetPoi is LooseItemFoodSource foodSource)
                {
                    entity.World.SpawnCubeParticles(entity.ServerPos.XYZ, foodSource.ItemStack, 0.25f, 1, 0.25f + 0.5f * (float)entity.World.Rand.NextDouble());
                }


                if (eatTimeNow > eatTime * 0.75f && !soundPlayed)
                {
                    soundPlayed = true;
                    if (eatSound != null)
                    {
                        entity.World.PlaySoundAt(eatSound, entity, null, true, 16, 1);
                    }
                }


                if (eatTimeNow >= eatTime)
                {
                    ITreeAttribute tree = entity.WatchedAttributes.GetTreeAttribute("hunger");
                    if (tree == null)
                    {
                        entity.WatchedAttributes["hunger"] = tree = new TreeAttribute();
                    }

                    if (doConsumePortion)
                    {
                        float sat = targetPoi.ConsumeOnePortion();
                        quantityEaten += sat;
                        tree.SetFloat("saturation", sat + tree.GetFloat("saturation", 0));
                        entity.WatchedAttributes.SetDouble("lastMealEatenTotalHours", entity.World.Calendar.TotalHours);
                        entity.WatchedAttributes.MarkPathDirty("hunger");
                    }
                    else
                    {
                        quantityEaten = 1;
                    }

                    failedSeekTargets.Remove(targetPoi);

                    return(false);
                }
            }
            else
            {
                if (!pathTraverser.Active)
                {
                    float rndx = (float)entity.World.Rand.NextDouble() * 0.3f - 0.15f;
                    float rndz = (float)entity.World.Rand.NextDouble() * 0.3f - 0.15f;
                    if (!pathTraverser.NavigateTo(targetPoi.Position.AddCopy(rndx, 0, rndz), moveSpeed, MinDistanceToTarget() - 0.15f, OnGoalReached, OnStuck, false, 500, 1))
                    {
                        return(false);
                    }
                }
            }


            if (nowStuck && entity.World.ElapsedMilliseconds > stuckatMs + eatTime * 1000)
            {
                return(false);
            }


            return(true);
        }
Example #47
0
        /// <summary>
        /// finds intrinsic and extrinsic camera parameters from several fews of a known calibration pattern.
        /// </summary>
        /// <param name="objectPoints">In the new interface it is a vector of vectors of calibration pattern points in the calibration pattern coordinate space. 
        /// The outer vector contains as many elements as the number of the pattern views. If the same calibration pattern is shown in each view and 
        /// it is fully visible, all the vectors will be the same. Although, it is possible to use partially occluded patterns, or even different patterns 
        /// in different views. Then, the vectors will be different. The points are 3D, but since they are in a pattern coordinate system, then, 
        /// if the rig is planar, it may make sense to put the model to a XY coordinate plane so that Z-coordinate of each input object point is 0.
        /// In the old interface all the vectors of object points from different views are concatenated together.</param>
        /// <param name="imagePoints">In the new interface it is a vector of vectors of the projections of calibration pattern points. 
        /// imagePoints.Count() and objectPoints.Count() and imagePoints[i].Count() must be equal to objectPoints[i].Count() for each i.</param>
        /// <param name="imageSize">Size of the image used only to initialize the intrinsic camera matrix.</param>
        /// <param name="cameraMatrix">Output 3x3 floating-point camera matrix. 
        /// If CV_CALIB_USE_INTRINSIC_GUESS and/or CV_CALIB_FIX_ASPECT_RATIO are specified, some or all of fx, fy, cx, cy must be 
        /// initialized before calling the function.</param>
        /// <param name="distCoeffs">Output vector of distortion coefficients (k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6]]) of 4, 5, or 8 elements.</param>
        /// <param name="rvecs">Output vector of rotation vectors (see Rodrigues() ) estimated for each pattern view. That is, each k-th rotation vector 
        /// together with the corresponding k-th translation vector (see the next output parameter description) brings the calibration pattern 
        /// from the model coordinate space (in which object points are specified) to the world coordinate space, that is, a real position of the 
        /// calibration pattern in the k-th pattern view (k=0.. M -1)</param>
        /// <param name="tvecs">Output vector of translation vectors estimated for each pattern view.</param>
        /// <param name="flags">Different flags that may be zero or a combination of the CalibrationFlag values</param>
        /// <param name="criteria">Termination criteria for the iterative optimization algorithm.</param>
        /// <returns></returns>
        public static double CalibrateCamera(
            IEnumerable<IEnumerable<Point3d>> objectPoints,
            IEnumerable<IEnumerable<Point2d>> imagePoints,
            Size imageSize,
            double[,] cameraMatrix,
            double[] distCoeffs,
            out Vec3d[] rvecs,
            out Vec3d[] tvecs,
            CalibrationFlag flags = CalibrationFlag.Zero,
            TermCriteria? criteria = null)
        {
            if (objectPoints == null)
                throw new ArgumentNullException("objectPoints");
            if (objectPoints == null)
                throw new ArgumentNullException("objectPoints");
            if (cameraMatrix == null)
                throw new ArgumentNullException("cameraMatrix");
            if (distCoeffs == null)
                throw new ArgumentNullException("distCoeffs");

            TermCriteria criteria0 = criteria.GetValueOrDefault(
                new TermCriteria(CriteriaType.Iteration | CriteriaType.Epsilon, 30, Double.Epsilon));

            using (var op = new ArrayAddress2<Point3d>(objectPoints))
            using (var ip = new ArrayAddress2<Point2d>(imagePoints))
            using (var rvecsVec = new VectorOfMat())
            using (var tvecsVec = new VectorOfMat())
            {
                double ret = NativeMethods.calib3d_calibrateCamera_vector(
                    op.Pointer, op.Dim1Length, op.Dim2Lengths,
                    ip.Pointer, ip.Dim1Length, ip.Dim2Lengths,
                    imageSize, cameraMatrix, distCoeffs, distCoeffs.Length,
                    rvecsVec.CvPtr, tvecsVec.CvPtr, (int)flags, criteria0);
                Mat[] rvecsM = rvecsVec.ToArray();
                Mat[] tvecsM = tvecsVec.ToArray();
                rvecs = EnumerableEx.SelectToArray(rvecsM, m => m.Get<Vec3d>(0));
                tvecs = EnumerableEx.SelectToArray(tvecsM, m => m.Get<Vec3d>(0));
                return ret;
            }
        }
        public static Vec3d FindScaleFactor(Vec3d vFirst, Vec3d vSecond)
        {
            Vec3d vSizeDiff = new Vec3d(null, 0, 0, 0);

            vSizeDiff.X = vFirst.X/vSecond.X;
            vSizeDiff.Y = vFirst.Y/vSecond.Y;
            vSizeDiff.Z = vFirst.Z/vSecond.Z;

            return vSizeDiff;
        }