Exemplo n.º 1
0
        //NOTE:  Forcing handle to be passed in forces the derived classes to expose static create methods instead of public constructors, but I prefer the certainty
        protected JointBase(World world, IntPtr handle)
        {
            this.World = world;
            this.Handle = handle;

            ObjectStorage.Instance.AddJoint(handle, this);
        }
        public PanelBeanTypes(FlyingBeanOptions options, World world)
        {
            InitializeComponent();

            _world = world;

            this.Options = options;
        }
            public PartSolver1(World world, PartBase[] parts)
            {
                _world = world;

                _parts = parts;
                _hasMoved = new bool[parts.Length];		// defaults to false
                _hulls = parts.Select(o => o.CreateCollisionHull(world)).ToArray();
                _initialPositions = parts.Select(o => Tuple.Create(o.Position, o.Orientation)).ToArray();
            }
Exemplo n.º 4
0
 public EditShipTransfer(Player player, SpaceDockPanel spaceDock, Editor editor, EditorOptions editorOptions, World world, int material_Ship, Map map, ShipExtraArgs shipExtra)
 {
     _player = player;
     _spaceDock = spaceDock;
     _editor = editor;
     _editorOptions = editorOptions;
     _world = world;
     _material_Ship = material_Ship;
     _map = map;
     _shipExtra = shipExtra;
 }
Exemplo n.º 5
0
        public NPCNest(NPCNestDNA dna, double radius, World world, Map map, KeepItems2D keepItems2D, MaterialIDs materialIDs, Viewport3D viewport, EditorOptions editorOptions, ItemOptionsArco itemOptions, IGravityField gravity, DragHitShape dragPlane)
        {
            // Store stuff
            _world = world;
            _map = map;
            _keepItems2D = keepItems2D;
            _materialIDs = materialIDs;
            _viewport = viewport;
            _editorOptions = editorOptions;
            _itemOptions = itemOptions;
            _gravity = gravity;
            _dragPlane = dragPlane;

            // DNA
            NPCNestDNA fixedDNA = GetFinalDNA(dna);
            _shellColors = fixedDNA.ShellColors;
            _botDNA = fixedDNA.BotDNA;
            _weaponDNA = fixedDNA.WeaponDNA;

            //TODO: Hand this a winner list, and filter criteria
            _dreamer = new EvolutionDreamer(_itemOptions, _shellColors, 4);     //TODO: Num bots should come from item options
            _dreamer.WeaponDNA = EvolutionDreamer.GetRandomDNA().Item2;

            #region WPF Model

            var models = GetModel(_shellColors, radius);
            this.Model = models.Item1;
            _eggModels = models.Item2;

            _rotateTransform = new QuaternionRotation3D();
            _translateTransform = new TranslateTransform3D();

            Transform3DGroup transform = new Transform3DGroup();
            transform.Children.Add(new RotateTransform3D(_rotateTransform));
            transform.Children.Add(_translateTransform);

            ModelVisual3D visual = new ModelVisual3D();
            visual.Transform = transform;
            visual.Content = this.Model;

            this.Visuals3D = new Visual3D[] { visual };

            #endregion

            // Energy tank
            _energy = new Container();
            _energy.QuantityMax = _itemOptions.Nest_Energy_Max * radius;
            _energy.QuantityCurrent = _energy.QuantityMax * .5d;

            // Finish
            this.Token = TokenGenerator.NextToken();
            this.Radius = radius;
            this.CreationTime = DateTime.UtcNow;
        }
Exemplo n.º 6
0
        public Egg(Point3D position, World world, int materialID, ItemOptions itemOptions, ShipDNA dna)
        {
            // The radius should be 20% the size of the adult ship
            this.Radius = dna.PartsByLayer.SelectMany(o => o.Value).
                Max(o => o.Position.ToVector().Length + Math1D.Max(o.Scale.X, o.Scale.Y, o.Scale.Z))
                * .2d;

            Vector3D scale = new Vector3D(.75d, .75d, 1d);

            #region WPF Model

            // Material
            MaterialGroup materials = new MaterialGroup();
            materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(WorldColors.EggColor)));
            materials.Children.Add(WorldColors.EggSpecular);

            // Geometry Model
            GeometryModel3D geometry = new GeometryModel3D();
            geometry.Material = materials;
            geometry.BackMaterial = materials;
            geometry.Geometry = UtilityWPF.GetSphere_LatLon(5, this.Radius);
            geometry.Transform = new ScaleTransform3D(scale);

            this.Model = geometry;

            // Model Visual
            ModelVisual3D model = new ModelVisual3D();
            model.Content = geometry;

            #endregion

            #region Physics Body

            Transform3DGroup transform = new Transform3DGroup();
            transform.Children.Add(new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRandomRotation())));
            transform.Children.Add(new TranslateTransform3D(position.ToVector()));

            double volume = (4d / 3d) * Math.PI * scale.X * this.Radius * scale.Y * this.Radius * scale.Z * this.Radius;
            double mass = volume * itemOptions.Egg_Density;

            using (CollisionHull hull = CollisionHull.CreateSphere(world, 0, scale * this.Radius, null))
            {
                this.PhysicsBody = new Body(hull, transform.Value, mass, new Visual3D[] { model });
                this.PhysicsBody.MaterialGroupID = materialID;
                this.PhysicsBody.LinearDamping = .01f;
                this.PhysicsBody.AngularDamping = new Vector3D(.001f, .001f, .001f);
            }

            #endregion

            this.CreationTime = DateTime.UtcNow;
        }
Exemplo n.º 7
0
        public BodyBall(World world)
        {
            this.Model = GetModel();
            ModelVisual3D visual = new ModelVisual3D();
            visual.Content = this.Model;

            using (CollisionHull hull = CollisionHull.CreateNull(world))
            {
                this.PhysicsBody = new Body(hull, Matrix3D.Identity, 100, new[] { visual });
            }

            this.Radius = 2;

            this.CreationTime = DateTime.UtcNow;
        }
Exemplo n.º 8
0
        public Projectile(double radius, double mass, Point3D position, World world, int materialID, Color? color = null, double? maxAge = null, Map map = null)
        {
            if (maxAge != null && map == null)
            {
                throw new ArgumentException("Map must be populated if max age is set");
            }

            this.Radius = radius;
            _maxAge = maxAge;
            _map = map;

            #region WPF Model

            this.Model = GetModel(color);
            this.Model.Transform = new ScaleTransform3D(radius, radius, radius);

            // Model Visual
            ModelVisual3D visual = new ModelVisual3D();
            visual.Content = this.Model;

            #endregion

            #region Physics Body

            Transform3DGroup transform = new Transform3DGroup();
            transform.Children.Add(new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRandomRotation())));
            transform.Children.Add(new TranslateTransform3D(position.ToVector()));

            using (CollisionHull hull = CollisionHull.CreateSphere(world, 0, new Vector3D(radius, radius, radius), null))
            {
                this.PhysicsBody = new Body(hull, transform.Value, mass, new Visual3D[] { visual });
                //this.PhysicsBody.IsContinuousCollision = true;
                this.PhysicsBody.MaterialGroupID = materialID;
                this.PhysicsBody.LinearDamping = .01d;
                this.PhysicsBody.AngularDamping = new Vector3D(.01d, .01d, .01d);

                //this.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(Body_ApplyForceAndTorque);
            }

            #endregion

            this.CreationTime = DateTime.UtcNow;
        }
Exemplo n.º 9
0
        public Mineral(MineralType mineralType, Point3D position, double volumeInCubicMeters, World world, int materialID, SharedVisuals sharedVisuals, double densityMult = 1d, double scale = 1d, decimal credits = 0m)
        {
            this.MineralType = mineralType;
            this.VolumeInCubicMeters = volumeInCubicMeters;
            this.Scale = scale;
            this.Credits = credits;

            this.Model = GetNewVisual(mineralType, sharedVisuals, scale);

            // Model Visual
            ModelVisual3D visual = new ModelVisual3D();        // this is the expensive one, so as few of these should be made as possible
            visual.Content = this.Model;

            this.Density = GetSettingsForMineralType(mineralType).Density * densityMult;

            #region Physics Body

            Transform3DGroup transform = new Transform3DGroup();
            transform.Children.Add(new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRandomRotation())));
            transform.Children.Add(new TranslateTransform3D(position.ToVector()));

            ScaleTransform3D scaleTransform = new ScaleTransform3D(scale, scale, scale);
            Point3D[] hullPoints = UtilityWPF.GetPointsFromMesh((MeshGeometry3D)sharedVisuals.GetMineralMesh(mineralType), scaleTransform);

            using (CollisionHull hull = CollisionHull.CreateConvexHull(world, 0, hullPoints))
            {
                this.PhysicsBody = new Body(hull, transform.Value, this.Density * volumeInCubicMeters, new Visual3D[] { visual });
                this.PhysicsBody.MaterialGroupID = materialID;
                this.PhysicsBody.LinearDamping = .01f;
                this.PhysicsBody.AngularDamping = new Vector3D(.01f, .01f, .01f);

                //this.PhysicsBody.ApplyForce += new BodyForceEventHandler(Body_ApplyForce);
            }

            #endregion

            // Calculate radius
            Point3D aabbMin, aabbMax;
            this.PhysicsBody.GetAABB(out aabbMin, out aabbMax);
            this.Radius = (aabbMax - aabbMin).Length / 2d;

            this.CreationTime = DateTime.UtcNow;
        }
Exemplo n.º 10
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // Init World
                _world = new World();
                _world.Updating += new EventHandler<WorldUpdatingArgs>(World_Updating);
                _world.UnPause();

                // Trackball
                _trackball = new TrackBallRoam(_camera);
                _trackball.EventSource = grdViewPort;		//NOTE:  If this control doesn't have a background color set, the trackball won't see events (I think transparent is ok, just not null)
                _trackball.AllowZoomOnMouseWheel = true;
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete));
                //_trackball.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);
                _trackball.ShouldHitTestOnOrbit = true;

                SetCollisionBoundry();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 11
0
        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {
                _world.Pause();

                //_updateManager.Dispose();

                _map.Dispose();		// this will dispose the physics bodies
                _map = null;

                _world.Dispose();
                _world = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 12
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _itemOptions = new ItemOptions();

                #region Init World

                _boundryMin = new Point3D(-BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF);
                _boundryMax = new Point3D(BOUNDRYSIZEHALF, BOUNDRYSIZEHALF, BOUNDRYSIZEHALF);

                _world = new World();
                //_world.Updating += new EventHandler<WorldUpdatingArgs>(World_Updating);

                List<Point3D[]> innerLines, outerLines;
                _world.SetCollisionBoundry(out innerLines, out outerLines, _boundryMin, _boundryMax);

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

                // Asteroid
                Game.Newt.v2.NewtonDynamics.Material material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .1d;
                _material_Asteroid = _materialManager.AddMaterial(material);

                // Collisions
                //_materialManager.RegisterCollisionEvent(_material_Asteroid, _material_Asteroid, Collision_AsteroidAsteroid);

                #endregion
                #region Map

                _map = new Map(_viewport, null, _world);
                _map.SnapshotFequency_Milliseconds = 250;// 125;
                _map.SnapshotMaxItemsPerNode = 10;
                _map.ShouldBuildSnapshots = false;
                _map.ShouldShowSnapshotLines = false;
                _map.ShouldSnapshotCentersDrift = true;

                // Asteroid doesn't implement up IPartUpdatable
                //_updateManager = new UpdateManager(
                //    new Type[] { typeof(Asteroid) },
                //    new Type[] { typeof(Asteroid) },
                //    _map);

                #endregion

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 13
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _itemOptions = new ItemOptions();

                #region Init World

                _boundryMin = new Point3D(-BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF);
                _boundryMax = new Point3D(BOUNDRYSIZEHALF, BOUNDRYSIZEHALF, BOUNDRYSIZEHALF);

                _world = new World();
                _world.Updating += new EventHandler<WorldUpdatingArgs>(World_Updating);

                List<Point3D[]> innerLines, outerLines;
                _world.SetCollisionBoundry(out innerLines, out outerLines, _boundryMin, _boundryMax);

                //TODO: Only draw the boundry lines if options say to

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

                // Wall
                Game.Newt.v2.NewtonDynamics.Material material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .1d;
                _material_Wall = _materialManager.AddMaterial(material);

                // Bot
                material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Bot = _materialManager.AddMaterial(material);

                // Exploding Bot
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.IsCollidable = false;
                _material_ExplodingBot = _materialManager.AddMaterial(material);

                // Food
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .1d;
                _material_Food = _materialManager.AddMaterial(material);

                // Egg
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .5d;
                _material_Egg = _materialManager.AddMaterial(material);

                // Projectile
                material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Projectile = _materialManager.AddMaterial(material);

                // Collisions
                _materialManager.RegisterCollisionEvent(_material_Bot, _material_Bot, Collision_BotBot);
                _materialManager.RegisterCollisionEvent(_material_Bot, _material_Food, Collision_BotFood);
                //TODO: May want to listen to projectile collisions

                #endregion
                #region Trackball

                // Trackball
                _trackball = new TrackBallRoam(_camera);
                _trackball.KeyPanScale = 15d;
                _trackball.EventSource = grdViewPort;		//NOTE:  If this control doesn't have a background color set, the trackball won't see events (I think transparent is ok, just not null)
                _trackball.AllowZoomOnMouseWheel = true;
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete_NoLeft));
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.Keyboard_ASDW_In));
                _trackball.ShouldHitTestOnOrbit = true;
                //_trackball.UserMovedCamera += new EventHandler<UserMovedCameraArgs>(Trackball_UserMovedCamera);
                //_trackball.GetOrbitRadius += new EventHandler<GetOrbitRadiusArgs>(Trackball_GetOrbitRadius);

                #endregion
                #region Camera Pool

                //TODO: Make the number of threads more configurable, look at how many processors there are
                //_cameraPool = new CameraPool(2, Colors.Black);
                _cameraPool = new CameraPool(1, Colors.Black);

                #endregion
                #region Map

                _map = new Map(_viewport, _cameraPool, _world)
                {
                    SnapshotFequency_Milliseconds = 250,        // 125
                    SnapshotMaxItemsPerNode = 10,
                    ShouldBuildSnapshots = true,
                    ShouldShowSnapshotLines = false,
                    ShouldSnapshotCentersDrift = true,
                };

                _updateManager = new UpdateManager(
                    new Type[] { typeof(Swimbot) },
                    new Type[] { typeof(Swimbot) },
                    _map);

                #endregion
                #region Fields

                _radiation = new RadiationField()
                {
                    AmbientRadiation = 0d,
                };

                //_gravity = new GravityFieldUniform()
                //{
                //    Gravity = new Vector3D(0, 0, 0),
                //};

                //TODO: Support a uniform fluid
                //FluidField

                #endregion
                #region ItemSelectDragLogic

                _selectionLogic = new ItemSelectDragLogic(_map, _camera, _viewport, grdViewPort)
                {
                    ShouldMoveItemWithSpring = true,
                    ShouldSpringCauseTorque = false,
                    SpringColor = null,     // Colors.Chartreuse
                    ShowDebugVisuals = false,       // true
                };

                _selectionLogic.SelectableTypes.Add(typeof(Bot));
                _selectionLogic.SelectableTypes.Add(typeof(Mineral));
                _selectionLogic.SelectableTypes.Add(typeof(Egg));

                _selectionLogic.ItemSelected += new EventHandler<ItemSelectedArgs>(SelectionLogic_ItemSelected);

                #endregion

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 14
0
        public SwarmBot1a(double radius, Point3D position, World world, Map map, SwarmObjectiveStrokes strokes, int materialID, Color? color = null)
        {
            _map = map;
            _strokes = strokes;

            this.Radius = radius;
            this.SearchRadius = radius * 100;

            _settings_OtherBot_Chase = CreateForceSettingInitial_OtherBot_Chase();
            _settings_OtherBot_Passive = CreateForceSettingInitial_OtherBot_Passive();
            _settings_Asteroid = CreateForceSettingInitial_Asteroid();

            #region WPF Model

            this.Model = GetModel(radius, color);
            this.Model.Transform = new ScaleTransform3D(radius, radius, radius);

            // Model Visual
            ModelVisual3D visual = new ModelVisual3D();
            visual.Content = this.Model;

            #endregion

            #region Physics Body

            Transform3DGroup transform = new Transform3DGroup();
            transform.Children.Add(new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRandomRotation())));
            transform.Children.Add(new TranslateTransform3D(position.ToVector()));

            double mass = GetMass(radius);

            using (CollisionHull hull = CollisionHull.CreateSphere(world, 0, new Vector3D(radius / 2, radius / 2, radius / 2), null))
            {
                this.PhysicsBody = new Body(hull, transform.Value, mass, new Visual3D[] { visual });
                //this.PhysicsBody.IsContinuousCollision = true;
                this.PhysicsBody.MaterialGroupID = materialID;
                this.PhysicsBody.LinearDamping = .01d;
                this.PhysicsBody.AngularDamping = new Vector3D(.01d, .01d, .01d);

                this.PhysicsBody.ApplyForceAndTorque += new EventHandler<BodyApplyForceAndTorqueArgs>(Body_ApplyForceAndTorque);
            }

            #endregion

            this.CreationTime = DateTime.UtcNow;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                // Init World
                _world = new World();
                _world.Updating += new EventHandler<WorldUpdatingArgs>(World_Updating);
                _world.SetWorldSize(new Point3D(-100, -100, -100), new Point3D(100, 100, 100));
                _world.UnPause();

                // Camera Trackball
                _trackball = new TrackBallRoam(_camera);
                _trackball.EventSource = grdViewPort;		//NOTE:  If this control doesn't have a background color set, the trackball won't see events (I think transparent is ok, just not null)
                _trackball.AllowZoomOnMouseWheel = true;
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete));
                //_trackball.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);

                // Trackball Controls
                SetupModelTrackball();
                SetupFlowTrackball();

                _field = new FluidFieldUniform()
                {
                    Viscosity = trkFlowViscosity.Value,
                    Flow = GetWorldFlow()
                };

                // Fluid lines
                AddFluidVisuals(Convert.ToInt32(NUMFLUIDVISUALS * _flowViscosity));

                // Force lines
                _forceLines = new ScreenSpaceLines3D(true);
                _forceLines.Color = _colors.ForceLine;
                _forceLines.Thickness = 2d;

                _viewport.Children.Add(_forceLines);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {
                _world.Pause();

                if (_viewer != null)
                {
                    _viewer.Close();
                    _viewer = null;
                }

                _updateManager.Dispose();

                // Explosions
                //foreach (ExplodingBot explosion in _explosions.ToArray())
                //{
                //    DisposeExplosion(explosion);
                //}

                _map.Dispose();		// this will dispose the physics bodies
                _map = null;

                if (_cameraPool != null)
                {
                    _cameraPool.Dispose();
                    _cameraPool = null;
                }

                _world.Dispose();
                _world = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 17
0
        private static Icon3D BuildIcon(Inventory inventory, World world, EditorOptions options, FrameworkElement parent)
        {
            Icon3D retVal = null;

            if (inventory.Ship != null)
            {
                retVal = new Icon3D("", inventory.Ship, world);       // don't want to autorotate the ship icons.  This is a 2D game, and the ships will always be viewed from the top
            }
            else if (inventory.Part != null)
            {
                retVal = new Icon3D(inventory.Part, options)
                {
                    AutoRotateOnMouseHover = true,
                    AutoRotateParent = parent,
                };
            }
            else if (inventory.Mineral != null)
            {
                retVal = new Icon3D(inventory.Mineral.MineralType)
                {
                    AutoRotateOnMouseHover = true,
                    AutoRotateParent = parent,
                };
            }

            if (retVal != null)
            {
                retVal.ShowName = false;
                retVal.ShowBorder = false;
            }

            return retVal;
        }
Exemplo n.º 18
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                #region Init World

                _boundryMin = new Point3D(-100, -100, -100);
                _boundryMax = new Point3D(100, 100, 100);

                _world = new World();
                _world.Updating += new EventHandler<WorldUpdatingArgs>(World_Updating);

                List<Point3D[]> innerLines, outerLines;
                _world.SetCollisionBoundry(out innerLines, out outerLines, _boundryMin, _boundryMax);

                // Don't bother with the boundry lines.  It looks funny with a partial viewport
                //// Draw the lines
                //_boundryLines = new ScreenSpaceLines3D(true);
                //_boundryLines.Thickness = 1d;
                //_boundryLines.Color = _colors.BoundryLines;
                //_viewport.Children.Add(_boundryLines);

                //foreach (Point3D[] line in innerLines)
                //{
                //    _boundryLines.AddLine(line[0], line[1]);
                //}

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

                // Ship
                var material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Ship = _materialManager.AddMaterial(material);

                //_materialManager.RegisterCollisionEvent(_material_Terrain, _material_Bean, Collision_BeanTerrain);

                #endregion
                #region Trackball

                // Trackball
                _trackball = new TrackBallRoam(_camera);
                //_trackball.KeyPanScale = 15d;
                _trackball.EventSource = pnlViewport;		//NOTE:  If this control doesn't have a background color set, the trackball won't see events (I think transparent is ok, just not null)
                _trackball.AllowZoomOnMouseWheel = true;
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete));
                //_trackball.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);
                _trackball.ShouldHitTestOnOrbit = false;

                // Trackball
                _trackballNeural = new TrackBallRoam(_cameraNeural);
                //_trackballNeural.KeyPanScale = 15d;
                _trackballNeural.EventSource = pnlViewportNeural;		//NOTE:  If this control doesn't have a background color set, the trackball won't see events (I think transparent is ok, just not null)
                _trackballNeural.AllowZoomOnMouseWheel = true;
                _trackballNeural.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete));
                //_trackballNeural.GetOrbitRadius += new GetOrbitRadiusHandler(Trackball_GetOrbitRadius);
                _trackballNeural.ShouldHitTestOnOrbit = false;

                #endregion
                #region Map

                //_map = new Map(_viewport, null, _world);
                //_map.SnapshotFequency_Milliseconds = 125;
                //_map.SnapshotMaxItemsPerNode = 10;
                //_map.ShouldBuildSnapshots = false;// true;
                //_map.ShouldShowSnapshotLines = false;
                //_map.ShouldSnapshotCentersDrift = true;

                #endregion
                #region Fields

                _radiation = new RadiationField()
                {
                    AmbientRadiation = 0d,
                };

                _gravityField = new GravityFieldUniform();

                #endregion

                // Trackball Controls
                SetupGravityTrackball();

                UpdateGravity();

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 19
0
        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {

                // Copied from btnClear_Click
                ClearDebugVisuals();
                ClearLinks();
                ClearGravSensors();
                ClearBrains();
                ClearThrusters();
                ClearContainers();




                //_map.Dispose();		// this will dispose the physics bodies
                //_map = null;

                _world.Pause();
                _world.Dispose();
                _world = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        /// <summary>
        /// http://stackoverflow.com/questions/9853216/alternative-to-thread-sleep
        /// </summary>
        private void btnLongTimerWait_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_cancel2 == null)
                {
                    _cancel2 = new CancellationTokenSource();
                }

                CancellationToken cancelToken = _cancel2.Token;

                Task task = Task.Factory.StartNew(a =>
                {
                    // It is from the thread pool.  Explicitly create a thread for cases like this instead of using task
                    //if (Thread.CurrentThread.IsThreadPoolThread)
                    //{
                    //    throw new ApplicationException("Long running thread can't be from the thread pool");
                    //}

                    // World
                    World world = new World(false);
                    world.UnPause();

                    #region Launch Timer

                    // Put a timer in another thread
                    ManualResetEvent elapsedEvent = new ManualResetEvent(false);

                    System.Timers.Timer timer = new System.Timers.Timer();
                    timer.Interval = 25;
                    timer.Elapsed += delegate { elapsedEvent.Set(); };
                    timer.AutoReset = false;
                    timer.Start();

                    #endregion

                    while (!cancelToken.IsCancellationRequested)
                    {
                        // Wait for the timer to tick and send a message
                        elapsedEvent.WaitOne();
                        elapsedEvent.Reset();
                        timer.Start();

                        world.Update();
                    }

                    timer.Stop();

                    world.Pause();      // pause really isn't necessary, since there isn't a timer to stop
                    world.Dispose();
                }, TaskCreationOptions.LongRunning, _cancel2.Token);

                task.ContinueWith(t =>
                {
                    _cancel2 = null;
                    MessageBox.Show("Finished", this.Title, MessageBoxButton.OK, MessageBoxImage.Information);
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 21
0
        public void SetInventory(Inventory inventory, string name, decimal credits, double? creditsPercent, double? volumePercent, World world, string[] actionButtons, EditorOptions options)
        {
            // Icon
            pnlIcon.Content = BuildIcon(inventory, world, options, this);

            // Name
            lblName.Text = name;

            if (inventory.Count == 1)
            {
                lblMultipleX.Visibility = Visibility.Collapsed;
                lblMultiple.Visibility = Visibility.Collapsed;
            }
            else
            {
                lblMultipleX.Visibility = Visibility.Visible;
                lblMultiple.Visibility = Visibility.Visible;
                lblMultiple.Text = inventory.Count.ToString("N0");
            }

            // Price
            lblPrice.Text = credits.ToString("N0");
            if (creditsPercent == null)
            {
                lblPricePercent.Visibility = Visibility.Collapsed;
            }
            else
            {
                lblPricePercent.Text = GetPercentText(creditsPercent.Value);
            }

            // Volume
            lblVolume.Text = Math.Round(inventory.Volume, 2).ToString();
            if (volumePercent == null)
            {
                lblVolumePercent.Visibility = Visibility.Collapsed;
            }
            else
            {
                lblVolumePercent.Text = GetPercentText(volumePercent.Value);
            }

            // Mass
            //lblMass.Text = Math.Round(inventory.Mass, 2).ToString();
            lblMass.Text = inventory.Mass.ToStringSignificantDigits(2);

            // Action Buttons
            pnlActionButtons.Children.Clear();

            switch (actionButtons.Length)
            {
                case 2:
                case 4:
                    pnlActionButtons.Columns = 2;
                    break;

                default:
                    pnlActionButtons.Columns = 3;
                    break;
            }

            pnlActionButtons.Rows = Convert.ToInt32(Math.Ceiling(actionButtons.Length / Convert.ToDouble(pnlActionButtons.Columns)));

            foreach (string action in actionButtons)
            {
                pnlActionButtons.Children.Add(new Button()
                {
                    Content = action
                });
            }

            // Store props
            this.Inventory = inventory;
            this.InventoryName = name;
            this.Credits = credits;
        }
        private void btnThreadTimerWait_Click(object sender, RoutedEventArgs e)
        {
            try
            {


                MessageBox.Show("finish this", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;



                if (_cancel3 == null)
                {
                    _cancel3 = new ManualResetEvent(false);
                }

                Thread workerThread = new Thread(() =>
                {
                    // World
                    World world = new World(false);
                    world.UnPause();

                    #region Launch Timer

                    // Put a timer in another thread
                    ManualResetEvent elapsedEvent = new ManualResetEvent(false);

                    System.Timers.Timer timer = new System.Timers.Timer();
                    timer.Interval = 25;
                    timer.Elapsed += delegate { elapsedEvent.Set(); };
                    timer.AutoReset = false;
                    timer.Start();

                    #endregion

                    WaitHandle[] handles = new WaitHandle[] { _cancel3, elapsedEvent };

                    while (true)
                    {
                        #region Wait for signal to go

                        int handleIndex = WaitHandle.WaitAny(handles);

                        if (handleIndex == 0)
                        {
                            // This thread needs to finish
                            break;      // I would prefer a switch statement, but there is no Exit While statement
                        }
                        else if (handleIndex == 1)
                        {
                            // Timer ticked
                            elapsedEvent.Reset();
                            timer.Start();
                        }
                        else
                        {
                            throw new ApplicationException("Unknown wait handle: " + handleIndex.ToString());
                        }

                        #endregion

                        world.Update();
                    }

                    timer.Stop();

                    world.Pause();      // pause really isn't necessary, since there isn't a timer to stop
                    world.Dispose();
                });

                workerThread.Start();



                //TODO: Figure out how to terminate the thread from this calling thread.  This article says to keep looping and checking workerThread.IsAlive.
                //That's a mess.  If that's the only way, then set up a little thread pool manager to do this
                //http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.90).aspx

                //task.ContinueWith(t =>
                //{
                //    workerThread.Join();
                //    workerThread = null;
                //    _cancel3 = null;
                //    MessageBox.Show("Finished", this.Title, MessageBoxButton.OK, MessageBoxImage.Information);
                //}, TaskScheduler.FromCurrentSynchronizationContext());


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _itemOptions = new ItemOptions();
                _itemOptions.MatterToEnergy_ConversionRate *= .12;
                _itemOptions.MatterToEnergy_AmountToDraw *= 1.25;        //NOTE: In bot, the matter converter group doesn't check if empty often enough.  So if you draw much more, then there will be noticable pulses of not refilling (I assume that's the cause anyway)

                #region Init World

                _boundryMin = new Point3D(-BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF);
                _boundryMax = new Point3D(BOUNDRYSIZEHALF, BOUNDRYSIZEHALF, BOUNDRYSIZEHALF);

                _world = new World();
                _world.Updating += new EventHandler<WorldUpdatingArgs>(World_Updating);

                List<Point3D[]> innerLines, outerLines;
                _world.SetCollisionBoundry(out innerLines, out outerLines, _boundryMin, _boundryMax);

                //NOTE: No need to draw a boundry

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

                // Wall
                Game.Newt.v2.NewtonDynamics.Material material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .1d;
                _material_Wall = _materialManager.AddMaterial(material);

                // Bot
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .1d;
                _material_Bot = _materialManager.AddMaterial(material);

                // Item
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .1d;
                _material_Item = _materialManager.AddMaterial(material);

                // Exploding Item
                material = new Game.Newt.v2.NewtonDynamics.Material();
                material.IsCollidable = false;
                _material_ExplodingItem = _materialManager.AddMaterial(material);

                // Projectile
                material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Projectile = _materialManager.AddMaterial(material);

                // Collisions
                //_materialManager.RegisterCollisionEvent(_material_Bot, _material_Bot, Collision_BotBot);
                //_materialManager.RegisterCollisionEvent(_material_Bot, _material_Item, Collision_BotItem);
                //TODO: projectile collisions

                #endregion
                #region Camera Pool

                //TODO: Make the number of threads more configurable, look at how many processors there are
                _cameraPool = new CameraPool(1, Colors.Black);

                #endregion
                #region Map

                _map = new Map(_viewport, _cameraPool, _world);
                _map.SnapshotFequency_Milliseconds = 250;// 125;
                _map.SnapshotMaxItemsPerNode = 10;
                _map.ShouldBuildSnapshots = true;
                _map.ShouldShowSnapshotLines = false;
                _map.ShouldSnapshotCentersDrift = true;

                _updateManager = new UpdateManager(
                    new Type[] { typeof(DefenseBot) },
                    new Type[] { typeof(DefenseBot) },
                    _map);

                #endregion

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private static World Prep4(params object[] args)
        {
            World world = new World(false);
            world.UnPause();

            return world;
        }
        private void Window_Closed(object sender, EventArgs e)
        {
            try
            {
                RemoveCurrentBody();

                _world.Pause();
                _world.Dispose();
                _world = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
 private static void Tick4(World world, double elapsedTime)
 {
     world.Update();
 }
Exemplo n.º 27
0
        public SwarmBay(EditorOptions options, ItemOptions itemOptions, ShipPartDNA dna, Map map, World world, int material_SwarmBot, IContainer plasma, SwarmObjectiveStrokes strokes)
            : base(options, dna, itemOptions.SwarmBay_Damage.HitpointMin, itemOptions.SwarmBay_Damage.HitpointSlope, itemOptions.SwarmBay_Damage.Damage)
        {
            _itemOptions = itemOptions;
            _map = map;
            _world = world;
            _material_SwarmBot = material_SwarmBot;
            _plasma = plasma;
            _strokes = strokes;

            this.Design = new SwarmBayDesign(options, true);
            this.Design.SetDNA(dna);

            double volume, radius;
            GetMass(out _mass, out volume, out radius, out _scaleActual, dna, itemOptions);
            //this.Radius = radius;

            _timeBetweenBots = StaticRandom.NextPercent(itemOptions.SwarmBay_BirthRate, .1);

            int maxCount = (itemOptions.SwarmBay_MaxCount * Math1D.Avg(dna.Scale.X, dna.Scale.Y, dna.Scale.Z)).ToInt_Round();
            if (maxCount < 0)
            {
                maxCount = 1;
            }
            _maxBots = maxCount;

            _plasmaTankThreshold = itemOptions.SwarmBay_Birth_TankThresholdPercent;

            _birthCost = itemOptions.SwarmBay_BirthCost;
            _birthRadius = itemOptions.SwarmBay_BirthSize / 2d;

            if (_map != null)
            {
                _map.ItemRemoved += Map_ItemRemoved;
            }

            this.Destroyed += SwarmBay_Destroyed;
        }
 private static void Teardown4(World world)
 {
     world.Pause();      // pause really isn't necessary, since there isn't a timer to stop
     world.Dispose();
 }
Exemplo n.º 29
0
        private void Window_Closed(object sender, EventArgs e)
        {
            //TODO: Now that ship creation is async, this can run before ships are finished building.  Disposing world
            //early causes bad things.  See FlyingBeansWindow.Window_Closed for a hacked solution

            try
            {
                _world.Pause();

                _updateManager.Dispose();

                _selectionLogic.UnselectItem();
                _selectionLogic = null;

                // Explosions
                //foreach (ExplodingBot explosion in _explosions.ToArray())
                //{
                //    DisposeExplosion(explosion);
                //}

                _map.Dispose();		// this will dispose the physics bodies
                _map = null;

                if (_cameraPool != null)
                {
                    _cameraPool.Dispose();
                    _cameraPool = null;
                }

                _world.Dispose();
                _world = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                _itemOptions = new ItemOptions();

                #region Init World

                _boundryMin = new Point3D(-BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF, -BOUNDRYSIZEHALF);
                _boundryMax = new Point3D(BOUNDRYSIZEHALF, BOUNDRYSIZEHALF, BOUNDRYSIZEHALF);

                _world = new World();
                _world.Updating += new EventHandler<WorldUpdatingArgs>(World_Updating);

                List<Point3D[]> innerLines, outerLines;
                _world.SetCollisionBoundry(out innerLines, out outerLines, _boundryMin, _boundryMax);

                #endregion
                #region Materials

                _materialManager = new MaterialManager(_world);

                // Wall
                Game.Newt.v2.NewtonDynamics.Material material = new Game.Newt.v2.NewtonDynamics.Material();
                material.Elasticity = .1d;
                _material_Wall = _materialManager.AddMaterial(material);

                // Ball
                material = new Game.Newt.v2.NewtonDynamics.Material();
                _material_Ball = _materialManager.AddMaterial(material);

                #endregion
                #region Trackball

                // Trackball
                _trackball = new TrackBallRoam(_camera);
                _trackball.KeyPanScale = 15d;
                _trackball.EventSource = grdViewPort;		//NOTE:  If this control doesn't have a background color set, the trackball won't see events (I think transparent is ok, just not null)
                _trackball.AllowZoomOnMouseWheel = true;
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.MouseComplete_NoLeft));
                _trackball.Mappings.AddRange(TrackBallMapping.GetPrebuilt(TrackBallMapping.PrebuiltMapping.Keyboard_ASDW_In));
                _trackball.ShouldHitTestOnOrbit = true;
                //_trackball.UserMovedCamera += new EventHandler<UserMovedCameraArgs>(Trackball_UserMovedCamera);
                //_trackball.GetOrbitRadius += new EventHandler<GetOrbitRadiusArgs>(Trackball_GetOrbitRadius);

                #endregion

                #region Chased Ball

                _chasedBall = new ChasedBall();

                _chasedBall.MotionType_Position = MotionType_Position.Stop;
                _chasedBall.MotionType_Orientation = MotionType_Orientation.Stop;

                _chasedBall.BoundrySizeChanged += new EventHandler(ChasedBall_BoundrySizeChanged);

                // Ball visual
                _chasedBallVisual = GetChaseBallVisual_Position();
                _chasedBallTransform = new TranslateTransform3D();
                _chasedBallVisual.Transform = _chasedBallTransform;
                _viewport.Children.Add(_chasedBallVisual);

                // Direction Visual
                var directionVisual = GetChaseBallVisual_Orientation();
                _chasedDirectionModel = directionVisual.Item1;
                _chasedDirectionVisual = directionVisual.Item2;
                _viewport.Children.Add(_chasedDirectionVisual);

                // Panels (the act of instantiating them will update the ball's properties)
                pnlChasePosition.Content = new ChasedPosition(_chasedBall)
                {
                    Foreground = Brushes.White,
                };

                pnlChaseOrientation.Content = new ChasedOrientation(_chasedBall)
                {
                    Foreground = Brushes.White,
                };

                #endregion
                #region Debug Visuals

                // Put these on the viewport before the ball so that it is propertly semitransparent

                //TODO: Draw the bounding box.  Use XYZ colors.  This will help the user stay oriented

                #endregion
                #region Body Ball

                _bodyBall = new BodyBall(_world);

                //_bodyBall.PhysicsBody.AngularDamping = new Vector3D(.0001, .0001, .0001);
                //_bodyBall.PhysicsBody.AngularVelocity = new Vector3D(0, 0, 4 * Math.PI);

                _viewport.Children.AddRange(_bodyBall.Visuals3D);

                #endregion

                RedrawBoundry();

                _world.UnPause();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }