// Truly new one created by application
 public ConcealedSector(String worldName, Vector3D sectorPos) {
     WorldName = worldName;
     SectorPosition = sectorPos;
     FileName = GenFileName(worldName, sectorPos);
     BuildersFileName = GenGridBuildersFileName(worldName, sectorPos);
     NeedsSave = true;
 }
Esempio n. 2
0
        public static MyVoxelMap BuildAsteroidSphere(bool multiThread, double radius, byte materialIndex, byte faceMaterialIndex,
                                                     bool hollow = false, int shellWidth = 0)
        {
            var length    = (int)((radius * 2) + 2);
            var buildSize = CalcRequiredSize(length);
            var origin    = new Vector3I(buildSize.X / 2, buildSize.Y / 2, buildSize.Z / 2);

            var action = (Action <MyVoxelBuilderArgs>) delegate(MyVoxelBuilderArgs e)
            {
                VRageMath.Vector3D voxelPosition = e.CoordinatePoint;

                int v = GetSphereVolume(ref voxelPosition, radius, origin);
                if (hollow)
                {
                    int h = GetSphereVolume(ref voxelPosition, radius - shellWidth, origin);
                    e.Volume = (byte)(v - h);
                }
                else
                {
                    e.Volume = (byte)v;
                }
            };

            return(BuildAsteroid(multiThread, buildSize, materialIndex, faceMaterialIndex, action));
        }
Esempio n. 3
0
        public override bool GetBotSpawnPosition(string behaviorType, out VRageMath.Vector3D spawnPosition)
        {
            // CH: TODO: Do this more generically, so that modders would be able to define their own bot types and the way they spawn
            if (behaviorType == "Spider")
            {
                MatrixD spawnMatrix;
                bool    success = GetSpiderSpawnPosition(out spawnMatrix, null);
                spawnPosition = spawnMatrix.Translation;
                return(success);
            }
            else if (MySession.Static.LocalCharacter != null)
            {
                var      pos = MySession.Static.LocalCharacter.PositionComp.GetPosition();
                Vector3  up;
                Vector3D right, forward;

                up = MyGravityProviderSystem.CalculateNaturalGravityInPoint(pos);
                if (up.LengthSquared() < 0.0001f)
                {
                    up = Vector3.Up;
                }
                else
                {
                    up = Vector3D.Normalize(up);
                }
                forward       = Vector3.CalculatePerpendicularVector(up);
                right         = Vector3.Cross(forward, up);
                spawnPosition = MyUtils.GetRandomDiscPosition(ref pos, 5.0f, ref forward, ref right);
                return(true);
            }

            spawnPosition = Vector3D.Zero;
            return(false);
        }
Esempio n. 4
0
        public override bool GetBotSpawnPosition(string behaviorType, out VRageMath.Vector3D spawnPosition)
        {
            if (MySession.LocalCharacter != null)
            {
                var      pos = MySession.LocalCharacter.PositionComp.GetPosition();
                Vector3  up;
                Vector3D right, forward;

                up = MyGravityProviderSystem.CalculateNaturalGravityInPoint(pos);
                if (up.LengthSquared() < 0.0001f)
                {
                    up = Vector3.Up;
                }
                else
                {
                    up = Vector3D.Normalize(up);
                }
                forward       = Vector3.CalculatePerpendicularVector(up);
                right         = Vector3.Cross(forward, up);
                spawnPosition = MyUtils.GetRandomDiscPosition(ref pos, 5.0f, ref forward, ref right);
                return(true);
            }

            spawnPosition = Vector3D.Zero;
            return(false);
        }
Esempio n. 5
0
        public void Update(float updateStepTime)
        {
            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyCamera-Update");
            Zoom.Update(updateStepTime);
            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            Vector3 newCameraPosOffset = Vector3.Zero;

            // spring
            if (CameraSpring.Enabled)
            {
                CameraSpring.Update(updateStepTime, out newCameraPosOffset);
            }
            // shake
            if (CameraShake.ShakeEnabled)
            {
                Vector3 shakePos, shakeDir;
                CameraShake.UpdateShake(updateStepTime, out shakePos, out shakeDir);
                newCameraPosOffset += shakePos;
            }
            // apply
            if (newCameraPosOffset != Vector3.Zero)
            {
                Vector3D newCameraPosOffsetD = newCameraPosOffset;
                Vector3D newCameraPosOffsetRotatedD;
                Vector3D.Rotate(ref newCameraPosOffsetD, ref ViewMatrix, out newCameraPosOffsetRotatedD);
                ViewMatrix.Translation += newCameraPosOffsetRotatedD;
            }

            UpdatePropertiesInternal(ViewMatrix);
        }
Esempio n. 6
0
        public static MyVoxelMap BuildAsteroidSphere(bool multiThread, double radius, string material, string faceMaterial,
                                                     bool hollow = false, int shellWidth = 0)
        {
            var length = (int)((radius * 2) + 2).RoundUpToNearest(64);
            var size   = new Vector3I(length, length, length);
            var origin = new Vector3I(size.X / 2, size.Y / 2, size.Z / 2);

            var action = (Action <MyVoxelBuilderArgs>) delegate(MyVoxelBuilderArgs e)
            {
                VRageMath.Vector3D voxelPosition = e.CoordinatePoint;

                int v = GetSphereVolume(ref voxelPosition, radius, origin);
                if (hollow)
                {
                    int h = GetSphereVolume(ref voxelPosition, radius - shellWidth, origin);
                    e.Volume = (byte)(v - h);
                }
                else
                {
                    e.Volume = (byte)v;
                }
            };

            return(BuildAsteroid(multiThread, size, material, faceMaterial, action));
        }
Esempio n. 7
0
        public static byte GetSphereVolume(ref VRageMath.Vector3D voxelPosition, double radius, VRageMath.Vector3D center)
        {
            double num            = (voxelPosition - center).Length();
            double signedDistance = num - radius;

            signedDistance = MathHelper.Clamp(-signedDistance, -1f, 1f) * 0.5f + 0.5f;
            return((byte)(signedDistance * 255));
        }
Esempio n. 8
0
        public void UpdateScreenSize(MyViewport currentScreenViewport)
        {
            Viewport = currentScreenViewport;

            PreviousPosition = Vector3D.Zero;
            BoundingFrustum  = new BoundingFrustumD(MatrixD.Identity);

            AspectRatio = Viewport.Width / Viewport.Height;
        }
Esempio n. 9
0
        public void BoundingBoxIntersectCustom()
        {
            var point  = new VRageMath.Vector3D(5d, 3.5d, 4d);
            var vector = new VRageMath.Vector3D(-0.03598167d, 0.0110336d, 0.9992915d);
            var box    = new VRageMath.BoundingBoxD(new VRageMath.Vector3D(3d, 3d, 2d), new VRageMath.Vector3D(7d, 4d, 6d));

            VRageMath.Vector3D?p = box.IntersectsRayAt(point, vector * 1000);

            Assert.AreEqual(new VRageMath.Vector3D(4.9176489098920966d, 3.5151384795308953d, 6.00000000000319d), p.Value, "Should Equal");
        }
Esempio n. 10
0
 /// <summary>
 /// Flushes A into the simplex
 /// </summary>
 /// <param name="direction">next search direction</param>
 private bool Update34(out Vec3 direction)
 {
     if (Dimension == 4)
     {
         return(Update4(out direction));
     }
     // assert Dimension == 3.
     Update3(out direction);
     return(false);
 }
Esempio n. 11
0
        public void BoundingBoxIntersectKeen()
        {
            var point  = new VRageMath.Vector3D(5d, 3.5d, 4d);
            var vector = new VRageMath.Vector3D(-0.03598167d, 0.0110336d, 0.9992915d);
            var box    = new VRageMath.BoundingBoxD(new VRageMath.Vector3D(3d, 3d, 2d), new VRageMath.Vector3D(7d, 4d, 6d));
            var ray    = new VRageMath.RayD(point, vector);

            double?f = box.Intersects(ray);

            Assert.AreEqual(0, f, "Should Equal");
        }
Esempio n. 12
0
            public void Update3(out Vec3 searchDirection)
            {
                var ba = B - A;
                var ca = C - A;

                Vec3 norm;

                Vec3.Cross(ref ba, ref ca, out norm);
                var origin = -A;

                Scalar dotRes;
                Vec3   crossRes;

                Vec3.Cross(ref ba, ref norm, out crossRes);
                Vec3.Dot(ref crossRes, ref origin, out dotRes);
                if (dotRes > 0) // origin outside the triangle, BA closest.
                {
                    Dimension = 2;
                    C         = A;
                    Vec3.Cross(ref ba, ref origin, out crossRes);
                    Vec3.Cross(ref crossRes, ref ba, out searchDirection);
                    return;
                }

                Vec3.Cross(ref norm, ref ca, out crossRes);
                Vec3.Dot(ref crossRes, ref origin, out dotRes);
                if (dotRes > 0) // origin outside the triangle, CA closest
                {
                    Dimension = 2;
                    B         = A;
                    Vec3.Cross(ref ca, ref origin, out crossRes);
                    Vec3.Cross(ref crossRes, ref ca, out searchDirection);
                    return;
                }

                Dimension = 3;
                Vec3.Dot(ref norm, ref origin, out dotRes);
                if (dotRes < 0) // origin below the triangle.
                {
                    // reverse winding order, BCD = BAC
                    D = C;
                    C = A;
                    searchDirection = -norm;
                    return;
                }

                D = C;
                C = B;
                B = A;
                searchDirection = norm;
            }
        /// <summary>
        /// Determines which sector the emitting face of a radar is pointing at
        /// </summary>
        /// <param name="antenna"></param>
        /// <returns></returns>
        private Sector DetermineAntennaSector(IMySlimBlock antenna)
        {
            // Start with the default direction
            // The model antenna points in the +X, +Y, and -Z directions
            VRageMath.Vector3D direction
                = new VRageMath.Vector3D(1.0f, 1.0f, -1.0f);

            // Rotate this vector by the orientation of the block
            VRageMath.Vector3D rotated = VRageMath.Vector3D.Rotate(
                direction, antenna.FatBlock.LocalMatrix);

            _logger.debugLog("New radar's vector is " + rotated.ToString(),
                             "DetermineAntennaSector");

            return(SectorExtensions.ClassifyVector(rotated));
        }
Esempio n. 14
0
            public bool Update4(out Vec3 searchDirection)
            {
                var abc = Vec3.Cross(B - A, C - A);

                var origin = -A;

                Scalar dotRes;

                Vec3.Dot(ref abc, ref origin, out dotRes);
                if (dotRes > 0) // outside, ABC closest
                {
                    Dimension = 3;
                    // BCD = BCA
                    D = A;
                    searchDirection = abc;
                    return(false);
                }
                var acd = Vec3.Cross(C - A, D - A);

                Vec3.Dot(ref acd, ref origin, out dotRes);
                if (dotRes > 0) // outside, ACD closest
                {
                    Dimension = 3;
                    // BCD = ACD
                    B = A;
                    searchDirection = acd;
                    return(false);
                }
                var adb = Vec3.Cross(D - A, B - A);

                Vec3.Dot(ref adb, ref origin, out dotRes);
                if (dotRes > 0) // outside, ADB closest
                {
                    Dimension = 3;
                    // BCD = BAD
                    C = A;
                    searchDirection = adb;
                    return(false);
                }

                // skip checking BCD dot origin, we know it's on the inside w.r.t it
                searchDirection = Vec3.Zero;
                return(true);
            }
Esempio n. 15
0
        public void BoundingBoxIntersectCustom()
        {
            var point = new VRageMath.Vector3D(5d, 3.5d, 4d);
            var vector = new VRageMath.Vector3D(-0.03598167d, 0.0110336d, 0.9992915d);
            var box = new VRageMath.BoundingBoxD(new VRageMath.Vector3D(3d, 3d, 2d), new VRageMath.Vector3D(7d, 4d, 6d));

            VRageMath.Vector3D? p = box.IntersectsRayAt(point, vector * 1000);

            Assert.AreEqual(new VRageMath.Vector3D(4.9176489098920966d, 3.5151384795308953d, 6.00000000000319d), p.Value, "Should Equal");
        }
Esempio n. 16
0
 Vector3D IMyCamera.WorldToScreen(ref Vector3D worldPos)
 {
     return Vector3D.Transform(worldPos, ViewProjectionMatrix);
 }
Esempio n. 17
0
 double IMyCamera.GetDistanceWithFOV(Vector3D position)
 {
     return GetDistanceFromPoint(position);
 }
Esempio n. 18
0
 public double GetDistanceFromPoint(Vector3D position)
 {
     return Vector3D.Distance(this.Position, position);
 }
Esempio n. 19
0
 /// <summary>
 /// Gets screen coordinates of 3d world pos in 0 - 1 distance where 1.0 is screen width(for X) or height(for Y).
 /// WARNING: Y is from bottom to top.
 /// </summary>
 /// <param name="worldPos">World position.</param>
 /// <returns>Screen coordinate in 0-1 distance.</returns>
 public Vector3D WorldToScreen(ref Vector3D worldPos)
 {
     return Vector3D.Transform(worldPos, ViewProjectionMatrix);
 }
Esempio n. 20
0
        public void UpdateScreenSize(MyViewport currentScreenViewport)
        {
            Viewport = currentScreenViewport; 

            PreviousPosition = Vector3D.Zero;
            BoundingFrustum = new BoundingFrustumD(MatrixD.Identity);

            AspectRatio = Viewport.Width / Viewport.Height;
        }
Esempio n. 21
0
 public void SetViewMatrix(MatrixD newViewMatrix)
 {
     PreviousPosition = Position;
     UpdatePropertiesInternal(newViewMatrix);
 }
Esempio n. 22
0
 /// <summary>
 /// Gets screen coordinates of 3d world pos in 0 - 1 distance where 1.0 is screen width(for X) or height(for Y).
 /// WARNING: Y is from bottom to top.
 /// </summary>
 /// <param name="worldPos">World position.</param>
 /// <returns>Screen coordinate in 0-1 distance.</returns>
 public Vector3D WorldToScreen(ref Vector3D worldPos)
 {
     return(Vector3D.Transform(worldPos, ViewProjectionMatrix));
 }
Esempio n. 23
0
 // Truly new one created by application
 public ConcealedSector(String worldName, Vector3D sectorPos)
 {
     WorldName = worldName;
     SectorPosition = sectorPos;
     FileName = GenFileName(worldName, sectorPos);
     BuildersFileName = GenGridBuildersFileName(worldName, sectorPos);
     NeedsSave = true;
 }
Esempio n. 24
0
 public void SetViewMatrix(MatrixD newViewMatrix)
 {
     PreviousPosition = Position;
     UpdatePropertiesInternal(newViewMatrix);
 }
Esempio n. 25
0
        public MyObjectBuilder_EntityBase BuildEntity()
        {
            var asteroidCenter = new VRageMath.Vector3D();
            var asteroidSize = new Vector3I();

            string originalFile = null;
            if (IsStockVoxel)
            {
                var stockfile = StockVoxel.SourceFilename;

                if (StockMaterial == null || StockMaterial.Value == null)
                {
                    SourceFile = stockfile;
                    originalFile = SourceFile;
                    var asteroid = new MyVoxelMap();
                    asteroid.Load(stockfile, SpaceEngineersCore.Resources.GetDefaultMaterialName(), false);
                    asteroidCenter = asteroid.BoundingContent.Center;
                    asteroidSize = asteroid.BoundingContent.SizeInt() + 1; // Content size
                }
                else
                {
                    var asteroid = new MyVoxelMap();
                    asteroid.Load(stockfile, StockMaterial.Value);
                    asteroid.ForceBaseMaterial(SpaceEngineersCore.Resources.GetDefaultMaterialName(), StockMaterial.Value);
                    SourceFile = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);
                    asteroid.Save(SourceFile);

                    originalFile = StockVoxel.SourceFilename;
                    asteroidCenter = asteroid.BoundingContent.Center;
                    asteroidSize = asteroid.BoundingContent.SizeInt() + 1; // Content size
                }
            }
            else if (IsFileVoxel)
            {
                originalFile = SourceFile;

                var asteroid = new MyVoxelMap();
                asteroid.Load(SourceFile, SpaceEngineersCore.Resources.GetDefaultMaterialName(), false);
                asteroidCenter = asteroid.BoundingContent.Center;
                asteroidSize = asteroid.BoundingContent.SizeInt() + 1; // Content size

                if (StockMaterial != null && StockMaterial.Value != null)
                {
                    asteroid.ForceBaseMaterial(SpaceEngineersCore.Resources.GetDefaultMaterialName(), StockMaterial.Value);
                    SourceFile = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);
                    asteroid.Save(SourceFile);
                }
            }
            else if (IsSphere)
            {
                string material;
                if (StockMaterial != null && StockMaterial.Value != null)
                    material = StockMaterial.Value;
                else
                    material = SpaceEngineersCore.Resources.GetDefaultMaterialName();

                originalFile = string.Format("sphere_{0}_{1}_{2}{3}", material.ToLowerInvariant(), SphereRadius, SphereShellRadius, MyVoxelMap.V2FileExtension);

                var asteroid = MyVoxelBuilder.BuildAsteroidSphere(SphereRadius > 32, SphereRadius, material, material, SphereShellRadius != 0, SphereShellRadius);
                // TODO: progress bar.
                asteroidCenter = asteroid.BoundingContent.Center;
                asteroidSize = asteroid.BoundingContent.SizeInt() + 1; // Content size
                SourceFile = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);
                asteroid.Save(SourceFile);
            }

            // automatically number all files, and check for duplicate filenames.
            Filename = MainViewModel.CreateUniqueVoxelStorageName(originalFile);

            // Figure out where the Character is facing, and plant the new constrcut right in front.
            // Calculate the hypotenuse, as it will be the safest distance to place in front.
            double distance = Math.Sqrt(Math.Pow(asteroidSize.X, 2) + Math.Pow(asteroidSize.Y, 2) + Math.Pow(asteroidSize.Z, 2)) / 2;

            var vector = new BindableVector3DModel(_dataModel.CharacterPosition.Forward).Vector3D;
            vector.Normalize();
            vector = System.Windows.Media.Media3D.Vector3D.Multiply(vector, distance);
            Position = new BindablePoint3DModel(Point3D.Add(new BindablePoint3DModel(_dataModel.CharacterPosition.Position).Point3D, vector));
            //Forward = new BindableVector3DModel(_dataModel.CharacterPosition.Forward);
            //Up = new BindableVector3DModel(_dataModel.CharacterPosition.Up);
            Forward = new BindableVector3DModel(Vector3.Forward);  // Asteroids currently don't have any orientation.
            Up = new BindableVector3DModel(Vector3.Up);

            var entity = new MyObjectBuilder_VoxelMap
            {
                EntityId = SpaceEngineersApi.GenerateEntityId(IDType.ASTEROID),
                PersistentFlags = MyPersistentEntityFlags2.CastShadows | MyPersistentEntityFlags2.InScene,
                StorageName = Path.GetFileNameWithoutExtension(Filename),
                PositionAndOrientation = new MyPositionAndOrientation
                {
                    Position = Position.ToVector3D() - asteroidCenter,
                    Forward = Forward.ToVector3(),
                    Up = Up.ToVector3()
                }
            };

            return entity;
        }
        private bool BuildEntity()
        {
            var filenamepart = Path.GetFileNameWithoutExtension(Filename);
            var filename     = MainViewModel.CreateUniqueVoxelStorageName(filenamepart + MyVoxelMap.V2FileExtension);

            double multiplier;

            if (IsMultipleScale)
            {
                multiplier = MultipleScale;
            }
            else
            {
                multiplier = MaxLengthScale / Math.Max(Math.Max(OriginalModelSize.Height, OriginalModelSize.Width), OriginalModelSize.Depth);
            }

            var scale           = new ScaleTransform3D(multiplier, multiplier, multiplier);
            var rotateTransform = MeshHelper.TransformVector(new System.Windows.Media.Media3D.Vector3D(0, 0, 0), -RotateRoll, RotateYaw - 90, RotatePitch + 90);

            SourceFile = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);

            var model = MeshHelper.Load(Filename, ignoreErrors: true);

            var meshes      = new List <MyVoxelRayTracer.MyMeshModel>();
            var geometeries = new List <MeshGeometry3D>();

            foreach (var model3D in model.Children)
            {
                var gm       = (GeometryModel3D)model3D;
                var geometry = gm.Geometry as MeshGeometry3D;

                if (geometry != null)
                {
                    geometeries.Add(geometry);
                }
            }
            meshes.Add(new MyVoxelRayTracer.MyMeshModel(geometeries.ToArray(), InsideStockMaterial.MaterialIndex, InsideStockMaterial.MaterialIndex));

            #region handle dialogs and process the conversion

            var doCancel = false;

            var progressModel = new ProgressCancelModel {
                Title = Res.WnProgressTitle, SubTitle = Res.WnProgressTitle, DialogText = Res.WnProgressTxtTimeRemain + " " + Res.WnProgressTxtTimeCalculating
            };
            var progressVm = new ProgressCancelViewModel(this, progressModel);
            progressVm.CloseRequested += delegate(object sender, EventArgs e)
            {
                doCancel = true;
            };

            var cancelFunc = (Func <bool>) delegate
            {
                return(doCancel);
            };

            var completedAction = (Action) delegate
            {
                progressVm.Close();
            };

            MyVoxelMap voxelMap = null;

            var action = (Action) delegate
            {
                voxelMap = MyVoxelRayTracer.ReadModelAsteroidVolmetic(model, meshes, scale, rotateTransform, TraceType, TraceCount, TraceDirection,
                                                                      progressModel.ResetProgress, progressModel.IncrementProgress, cancelFunc, completedAction);
            };

            if (RunInLowPrioity)
            {
                System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.Idle;
            }

            _dialogService.ShowDialog <WindowProgressCancel>(this, progressVm, action);

            if (RunInLowPrioity)
            {
                System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.Normal;
            }

            #endregion

            if (doCancel || voxelMap == null)
            {
                IsValidEntity = false;
                NewEntity     = null;
            }
            else
            {
                voxelMap.ForceShellMaterial(OutsideStockMaterial.Value, (byte)OutsideMaterialDepth);
                voxelMap.Save(SourceFile);

                var position = VRageMath.Vector3D.Zero;
                var forward  = Vector3.Forward;
                var up       = Vector3.Up;

                if (IsAbsolutePosition)
                {
                    position = Position.ToVector3();
                }
                else if (IsInfrontofPlayer)
                {
                    // Figure out where the Character is facing, and plant the new construct centered in front of the Character, but "BuildDistance" units out in front.
                    var lookVector = (VRageMath.Vector3D)_dataModel.CharacterPosition.Forward.ToVector3();
                    lookVector.Normalize();

                    BoundingBoxD       content = voxelMap.BoundingContent.ToBoundingBoxD();
                    VRageMath.Vector3D?boundingIntersectPoint = content.IntersectsRayAt(content.Center, -lookVector * 5000d);

                    if (!boundingIntersectPoint.HasValue)
                    {
                        boundingIntersectPoint = content.Center;
                    }

                    var distance = VRageMath.Vector3D.Distance(boundingIntersectPoint.Value, content.Center) + (float)BuildDistance;
                    VRageMath.Vector3D vector = lookVector * distance;
                    position = VRageMath.Vector3D.Add(_dataModel.CharacterPosition.Position, vector) - content.Center;
                }

                var entity = new MyObjectBuilder_VoxelMap(position, filename)
                {
                    EntityId        = SpaceEngineersApi.GenerateEntityId(IDType.ASTEROID),
                    PersistentFlags = MyPersistentEntityFlags2.CastShadows | MyPersistentEntityFlags2.InScene,
                    StorageName     = Path.GetFileNameWithoutExtension(filename)
                };

                entity.PositionAndOrientation = new MyPositionAndOrientation
                {
                    Position = position,
                    Forward  = forward,
                    Up       = up
                };

                IsValidEntity = voxelMap.BoundingContent.Size.Volume() > 0;

                NewEntity = entity;

                if (BeepWhenFinished)
                {
                    System.Media.SystemSounds.Asterisk.Play();
                }
            }

            return(!doCancel);
        }
Esempio n. 27
0
 Vector3D IMyCamera.WorldToScreen(ref Vector3D worldPos)
 {
     return(Vector3D.Transform(worldPos, ViewProjectionMatrix));
 }
        /// <summary>
        /// Goes through all tracks in the list and determines whether or not
        /// they can currently be seen.  This function does not add or remove
        /// contacts from the list.  That can only be done in ProcessAcquiredContacts.
        /// </summary>
        private void DoTrackingSweep()
        {
            //_logger.debugLog("Beginning sweep", "DoTrackingSweep");

            Vector3D myPos = _grid.WorldAABB.Center;

            // Go through all current tracks and update their makers
            foreach (Track track in _allTracks.Values)
            {
                //_logger.debugLog($"For Track {track.trackId}", "DoTrackingSweep");

                // If the entity is null, this track is only available on the
                // server so use the stored value.  Otherwise get the most
                // up to date value
                if (track.ent != null)
                {
                    //_logger.debugLog("Entity is not null", "DoTrackingSweep");
                    track.position = track.ent.WorldAABB.Center;
                }

                // Transform the coordinates into grid space so we
                // can compare it against our radar coverage
                VRageMath.Vector3D relative
                    = VRageMath.Vector3D.Transform(
                          track.position, _grid.WorldMatrixNormalizedInv);

                //Check that the sector is covered by our radars
                Sector sec = SectorExtensions.ClassifyVector(relative);
                if (IsSectorBlind(sec))
                {
                    //_logger.debugLog("Sector is blind", "DoTrackingSweep");
                    // If a contact is not trackable, clear its GPS marker
                    ClearTrackMarker(track);
                    continue;
                }

                // Vector to target
                Vector3D vecTo = track.position - myPos;

                // If the entity is available, calculate the cross-section
                // Otherwise we will use the stored value from the server
                if (track.ent != null)
                {
                    track.xsec
                        = EWMath.DetermineXSection(track.ent as IMyCubeGrid, vecTo);
                }

                double range = vecTo.Length();
                double minxsec
                    = EWMath.MinimumXSection(
                          Constants.radarBeamWidths[(int)_assignedType], range);
                if (track.xsec < minxsec)
                {
                    //_logger.debugLog("Cross-section not large enough", "DoTrackingSweep");
                    ClearTrackMarker(track);
                    continue;
                }

                // TODO: raycast

                // If all of the previous checks passed, this contact should
                // be visible with a marker
                AddUpdateTrackMarker(track);
            }
        }
Esempio n. 29
0
 void IMySlimBlock.ComputeWorldCenter(out VRageMath.Vector3D worldCenter)
 {
     ComputeWorldCenter(out worldCenter);
 }
Esempio n. 30
0
 double IMyCamera.GetDistanceWithFOV(Vector3D position)
 {
     return(GetDistanceFromPoint(position));
 }
Esempio n. 31
0
 bool IMyEntity.DoOverlapSphereTest(float sphereRadius, VRageMath.Vector3D spherePos)
 {
     return(DoOverlapSphereTest(sphereRadius, spherePos));
 }
Esempio n. 32
0
 public double GetDistanceFromPoint(Vector3D position)
 {
     return(Vector3D.Distance(this.Position, position));
 }
Esempio n. 33
0
        public void BoundingBoxIntersectKeen()
        {
            var point = new VRageMath.Vector3D(5d, 3.5d, 4d);
            var vector = new VRageMath.Vector3D(-0.03598167d, 0.0110336d, 0.9992915d);
            var box = new VRageMath.BoundingBoxD(new VRageMath.Vector3D(3d, 3d, 2d), new VRageMath.Vector3D(7d, 4d, 6d));
            var ray = new VRageMath.RayD(point, vector);

            double? f = box.Intersects(ray);

            Assert.AreEqual(0, f, "Should Equal");
        }
Esempio n. 34
0
 void IMySlimBlock.ComputeScaledCenter(out VRageMath.Vector3D scaledCenter)
 {
     ComputeScaledCenter(out scaledCenter);
 }
Esempio n. 35
0
 public VRageMath.Vector3 DirectionToTarget(VRageMath.Vector3D target)
 {
     return(target);
 }
Esempio n. 36
0
 void IMyEntity.SetPosition(VRageMath.Vector3D pos)
 {
     PositionComp.SetPosition(pos);
 }
Esempio n. 37
0
        public MyObjectBuilder_EntityBase BuildEntity()
        {
            var asteroidCenter = new VRageMath.Vector3D();
            var asteroidSize   = new Vector3I();

            string originalFile = null;

            if (IsStockVoxel)
            {
                var stockfile = StockVoxel.SourceFilename;

                if (StockMaterial == null || StockMaterial.Value == null)
                {
                    SourceFile   = stockfile;
                    originalFile = SourceFile;
                    var asteroid = new MyVoxelMap();
                    asteroid.Load(stockfile);
                    asteroidCenter = asteroid.BoundingContent.Center;
                    asteroidSize   = asteroid.BoundingContent.Size + 1; // Content size
                }
                else
                {
                    var asteroid = new MyVoxelMap();
                    asteroid.Load(stockfile);
                    asteroid.ForceBaseMaterial(SpaceEngineersCore.Resources.GetDefaultMaterialName(), StockMaterial.Value);
                    SourceFile = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);
                    asteroid.Save(SourceFile);

                    originalFile   = StockVoxel.SourceFilename;
                    asteroidCenter = asteroid.BoundingContent.Center;
                    asteroidSize   = asteroid.BoundingContent.Size + 1; // Content size
                }
            }
            else if (IsFileVoxel)
            {
                originalFile = SourceFile;

                var asteroid = new MyVoxelMap();
                asteroid.Load(SourceFile);
                asteroidCenter = asteroid.BoundingContent.Center;
                asteroidSize   = asteroid.BoundingContent.Size + 1; // Content size

                if (StockMaterial != null && StockMaterial.Value != null)
                {
                    asteroid.ForceBaseMaterial(SpaceEngineersCore.Resources.GetDefaultMaterialName(), StockMaterial.Value);
                    SourceFile = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);
                    asteroid.Save(SourceFile);
                }
            }
            else if (IsSphere)
            {
                byte materialIndex;
                if (StockMaterial?.MaterialIndex != null)
                {
                    materialIndex = StockMaterial.MaterialIndex.Value;
                }
                else
                {
                    materialIndex = SpaceEngineersCore.Resources.GetDefaultMaterialIndex();
                }

                string materialName = SpaceEngineersCore.Resources.GetMaterialName(materialIndex);

                originalFile = string.Format("sphere_{0}_{1}_{2}{3}", materialName.ToLowerInvariant(), SphereRadius, SphereShellRadius, MyVoxelMap.V2FileExtension);

                var asteroid = MyVoxelBuilder.BuildAsteroidSphere(SphereRadius > 32, SphereRadius, materialIndex, materialIndex, SphereShellRadius != 0, SphereShellRadius);
                // TODO: progress bar.
                asteroidCenter = asteroid.BoundingContent.Center;
                asteroidSize   = asteroid.BoundingContent.Size + 1; // Content size
                SourceFile     = TempfileUtil.NewFilename(MyVoxelMap.V2FileExtension);
                asteroid.Save(SourceFile);
            }

            // automatically number all files, and check for duplicate filenames.
            Filename = MainViewModel.CreateUniqueVoxelStorageName(originalFile);

            // Figure out where the Character is facing, and plant the new constrcut right in front.
            // Calculate the hypotenuse, as it will be the safest distance to place in front.
            double distance = Math.Sqrt(Math.Pow(asteroidSize.X, 2) + Math.Pow(asteroidSize.Y, 2) + Math.Pow(asteroidSize.Z, 2)) / 2;

            var vector = new BindableVector3DModel(_dataModel.CharacterPosition.Forward).Vector3D;

            vector.Normalize();
            vector   = System.Windows.Media.Media3D.Vector3D.Multiply(vector, distance);
            Position = new BindablePoint3DModel(Point3D.Add(new BindablePoint3DModel(_dataModel.CharacterPosition.Position).Point3D, vector));
            //Forward = new BindableVector3DModel(_dataModel.CharacterPosition.Forward);
            //Up = new BindableVector3DModel(_dataModel.CharacterPosition.Up);
            Forward = new BindableVector3DModel(Vector3.Forward);  // Asteroids currently don't have any orientation.
            Up      = new BindableVector3DModel(Vector3.Up);

            var entity = new MyObjectBuilder_VoxelMap
            {
                EntityId               = SpaceEngineersApi.GenerateEntityId(IDType.ASTEROID),
                PersistentFlags        = MyPersistentEntityFlags2.CastShadows | MyPersistentEntityFlags2.InScene,
                StorageName            = Path.GetFileNameWithoutExtension(Filename),
                PositionAndOrientation = new MyPositionAndOrientation
                {
                    Position = Position.ToVector3D() - asteroidCenter,
                    Forward  = Forward.ToVector3(),
                    Up       = Up.ToVector3()
                }
            };

            return(entity);
        }
Esempio n. 38
0
        public static bool Intersects <T1, T2>(ref T1 shape1, ref T2 shape2, int iterations = 64) where T1 : struct, ConvexShape where T2 : struct, ConvexShape
        {
            Vec3   searchDirection;
            Scalar dotResult;

            var simplex = new Simplex();

            // Initialize the simplex to a line, with searchDirection for next point.
            {
                searchDirection = shape2.Center - shape1.Center;
                if (Vec3.IsZero(searchDirection))
                {
                    searchDirection = Vec3.UnitX;
                }

                // Initial point
                simplex.C       = shape2.FarthestInDirection(searchDirection) - shape1.FarthestInDirection(-searchDirection);
                searchDirection = -simplex.C;
                simplex.Dimension++;

                // Second point, crossing origin
                simplex.B = shape2.FarthestInDirection(searchDirection) - shape1.FarthestInDirection(-searchDirection);
                simplex.Dimension++;

                // Check if we made progress
                Vec3.Dot(ref simplex.B, ref searchDirection, out dotResult);
                if (dotResult < 0)
                {
                    return(false);
                }

                var bc = simplex.C - simplex.B;
                Vec3.Cross(ref bc, ref simplex.B, out searchDirection);
                Vec3.Cross(ref bc, ref searchDirection, out searchDirection);
                if (Vec3.IsZero(searchDirection))
                {
                    // create perp vector to BC
                    if (Math.Abs(bc.Y + bc.Z) > 1e-5 || Math.Abs(bc.X) > 1e-5)
                    {
                        searchDirection = new Vector3D(-(bc.Y + bc.Z), bc.X, bc.X);
                    }
                    else
                    {
                        searchDirection = new Vector3D(bc.Z, bc.Z, -(bc.X + bc.Y));
                    }
                }
            }
            for (var i = 0; i < iterations; i++)
            {
                simplex.A = shape2.FarthestInDirection(searchDirection) - shape1.FarthestInDirection(-searchDirection);
                simplex.Dimension++;

                // Check if we made progress
                Vec3.Dot(ref simplex.A, ref searchDirection, out dotResult);
                if (dotResult < 0)
                {
                    return(false);
                }

                if (simplex.Dimension == 3)
                {
                    simplex.Update3(out searchDirection);
                }
                else
                {
                    // assert Dimension == 4
                    if (simplex.Update4(out searchDirection))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }