Пример #1
0
        private void UpdateDetailVisual()
        {
            const double IDEALRATIO = .4d;

            if (_detailVisual == null)
            {
                return;
            }

            if (pnlDetail.Item != null && pnlDetail.Model != null)
            {
                _detailVisual.Content             = UtilityCore.Clone(pnlDetail.Model);
                _detailRotationInitial.Quaternion = pnlDetail.ModelRotate;

                Rect3D bounds = _detailVisual.Content.Bounds;

                // Center it so that it's at 0,0,0 in model coords
                _detailTranslate.OffsetX = -(bounds.X + (bounds.SizeX / 2d));
                _detailTranslate.OffsetY = -(bounds.Y + (bounds.SizeY / 2d));
                _detailTranslate.OffsetZ = -(bounds.Z + (bounds.SizeZ / 2d));

                // Scale it to the ideal size on screen
                double size = bounds.DiagonalLength();

                double scale = IDEALRATIO / (size / _cameraLength);

                _detailScale.ScaleX = scale;
                _detailScale.ScaleY = scale;
                _detailScale.ScaleZ = scale;
            }
            else
            {
                _detailVisual.Content = GetBlankModel();
            }
        }
Пример #2
0
        //TODO: Rework this class to use SessionSaveLoad.cs
        public static void Save(string baseFolder, string saveFolder, FlyingBeanSession session, FlyingBeanOptions options, ItemOptions itemOptions)
        {
            // Session
            //NOTE: This is in the base folder
            UtilityCore.SerializeToFile(Path.Combine(baseFolder, FILENAME_SESSION), session);

            // ItemOptions
            UtilityCore.SerializeToFile(Path.Combine(saveFolder, FILENAME_ITEMOPTIONS), itemOptions);

            // Options
            FlyingBeanOptions optionCloned = UtilityCore.Clone(options);

            optionCloned.DefaultBeanList = null;                // this is programatically generated, no need to save it
            //optionCloned.NewBeanList		//NOTE: These will be serialized with the options file

            SortedList <string, ShipDNA> winningFilenames;
            SortedList <string, double>  maxScores;

            ExtractHistory(out winningFilenames, out maxScores, options.WinnersFinal);          // can't use cloned.winners, that property is skipped when serializing
            optionCloned.WinningScores = maxScores;

            // Main class
            UtilityCore.SerializeToFile(Path.Combine(saveFolder, FILENAME_OPTIONS), optionCloned);

            // Winning beans
            if (winningFilenames != null)
            {
                foreach (string beanFile in winningFilenames.Keys)
                {
                    UtilityCore.SerializeToFile(Path.Combine(saveFolder, beanFile), winningFilenames[beanFile]);
                }
            }
        }
Пример #3
0
        private static (Model3DGroup model, WeaponHandleDNA dna) GetModel(WeaponHandleDNA dna, WeaponMaterialCache materials)
        {
            WeaponHandleDNA finalDNA = UtilityCore.Clone(dna);

            if (finalDNA.KeyValues == null)
            {
                finalDNA.KeyValues = new SortedList <string, double>();
            }

            Model3DGroup model = null;

            // If there is a mismatch between desired material and type, prefer material
            finalDNA.HandleType = GetHandleType(dna.HandleMaterial, dna.HandleType);

            // Build the handle
            switch (finalDNA.HandleType)
            {
            case WeaponHandleType.Rod:
                model = GetModel_Rod(dna, finalDNA, materials);
                break;

            case WeaponHandleType.Rope:
                throw new ApplicationException("Rope currently isn't supported");

            default:
                throw new ApplicationException("Unknown WeaponHandleType: " + finalDNA.HandleType.ToString());
            }

            return(model, finalDNA);

            #region WRAITH
            //retVal.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex(this.DiffuseColor))));
            //retVal.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex(this.SpecularColor)), this.SpecularPower.Value));
            //retVal.Children.Add(new EmissiveMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex(this.EmissiveColor))));


            //case WeaponHandleMaterial.Wraith:
            //    #region Wraith

            //    retVal.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("6048573E"))));
            //    retVal.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("202C1D33")), 50d));
            //    retVal.Children.Add(new EmissiveMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("1021222B"))));

            //    #endregion
            //    break;



            //if (useDebugVisual)
            //{
            //    geometry.Geometry = UtilityWPF.GetLine(new Point3D(-(handle.Length / 2d), 0, 0), new Point3D(handle.Length / 2d, 0, 0), handle.Radius * 2d);
            //}
            #endregion
        }
Пример #4
0
        private void WeaponSelected(Weapon weapon)
        {
            //TODO: When there are more than just weapon handles, have a major section, then describe each part in sub sections

            //TODO: Density, Mass, Durability, Cost, Damage, Required experience
            //TODO: A small graphic next to mass showing how difficult it would be for the player to yield

            //TODO: A small paragraph describing the weapon in an expander

            pnlContent.Children.Add(GetTextblock_MajorHeader("Weapon Handle"));
            pnlContent.Children.Add(GetTextblock_MinorHeader(weapon.DNA.Handle.HandleMaterial.ToString().Replace('_', ' ')));
            //pnlContent.Children.Add(GetTextblock_Standard(string.Format("Mass: {0}", GetRounded(weapon.m))));

            _model       = UtilityCore.Clone(weapon.Model);
            _modelRotate = new Quaternion(new Vector3D(0, 0, 1), 90);
        }
Пример #5
0
        private static Tuple <Model3DGroup, WeaponAxeDNA> GetModel(WeaponAxeDNA dna, WeaponMaterialCache materials, bool isLeftSide)
        {
            WeaponAxeDNA finalDNA = UtilityCore.Clone(dna);

            if (finalDNA.KeyValues == null)
            {
                finalDNA.KeyValues = new SortedList <string, double>();
            }

            Model3DGroup model = null;

            switch (finalDNA.AxeType)
            {
            case WeaponAxeType.Symetrical:
                model = GetModel_Symetrical(dna, finalDNA, materials);
                break;

            case WeaponAxeType.Lumber:
            case WeaponAxeType.Bearded:
                model = GetModel_Second(dna, finalDNA, materials, finalDNA.AxeType == WeaponAxeType.Bearded);
                break;

            default:
                throw new ApplicationException("Unknown WeaponAxeType: " + finalDNA.AxeType.ToString());
            }

            Transform3DGroup transform = new Transform3DGroup();

            transform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 0, 1), 90)));

            if (dna.IsBackward)
            {
                // This won't make a difference if it's a double sided axe, but will for single sided
                transform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(1, 0, 0), 180)));
            }

            if (isLeftSide)
            {
                transform.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), 180)));
            }

            model.Transform = transform;

            return(Tuple.Create(model, finalDNA));
        }
Пример #6
0
        //TODO: Have an explicit attach point
        private static Tuple <Model3DGroup, WeaponSpikeBallDNA> GetModel(WeaponSpikeBallDNA dna, WeaponMaterialCache materials)
        {
            WeaponSpikeBallDNA finalDNA = UtilityCore.Clone(dna);

            if (finalDNA.KeyValues == null)
            {
                finalDNA.KeyValues = new SortedList <string, double>();
            }

            Model3DGroup model = null;

            switch (finalDNA.Material)
            {
            case WeaponSpikeBallMaterial.Wood:
                model = GetModel_WoodIron(dna, finalDNA, materials);
                break;

            case WeaponSpikeBallMaterial.Bronze_Iron:
                model = GetModel_BronzeIron(dna, finalDNA, materials);
                break;

            case WeaponSpikeBallMaterial.Iron_Steel:
                model = GetModel_IronSteel(dna, finalDNA, materials);
                break;

            case WeaponSpikeBallMaterial.Composite:
                model = GetModel_Composite(dna, finalDNA, materials);
                break;

            case WeaponSpikeBallMaterial.Klinth:
                model = GetModel_Klinth(dna, finalDNA, materials);
                break;

            case WeaponSpikeBallMaterial.Moon:
                model = GetModel_Moon(dna, finalDNA, materials);
                break;

            default:
                throw new ApplicationException("Unknown WeaponSpikeBallMaterial: " + finalDNA.Material.ToString());
            }

            return(Tuple.Create(model, finalDNA));
        }
Пример #7
0
        private void CreateVisual(double sizePercent)
        {
            const double ZOOMFULL = 2.7d;

            if (_item == null)
            {
                return;
            }

            Model3D model = UtilityCore.Clone(_item.Model);

            _rotateTransform = new QuaternionRotation3D(Quaternion.Identity);
            model.Transform  = new RotateTransform3D(_rotateTransform);

            _visual = new ModelVisual3D()
            {
                Content = model
            };

            _camera.Position = (_camera.Position.ToVector().ToUnit() * (_item.Radius * ZOOMFULL / sizePercent)).ToPoint();
            _viewport.Children.Add(_visual);
        }
Пример #8
0
        private static ShipDNA RotateDNA_DoIt(ShipDNA dna, Quaternion rotation, Transform3D positionTransform)
        {
            ShipDNA retVal = UtilityCore.Clone(dna);

            foreach (ShipPartDNA part in retVal.PartsByLayer.SelectMany(o => o.Value))
            {
                // Rotate the orientation
                //part.Orientation = part.Orientation.RotateBy(rotation);
                part.Orientation = rotation.RotateBy(part.Orientation);


                // Apply a transform to the poisition
                part.Position = positionTransform.Transform(part.Position);


                //TODO: See if these need to be rotated as well
                //part.Neurons;
                //part.ExternalLinks;
                //part.InternalLinks;
            }

            return(retVal);
        }
Пример #9
0
        public Icon3D(ShipPartDNA dna, EditorOptions options)
        {
            InitializeComponent();

            // Need to set position to zero, or the image won't be centered (part's model considers position/orientation)
            dna             = UtilityCore.Clone(dna);
            dna.Position    = new Point3D();
            dna.Orientation = Quaternion.Identity;

            PartDesignBase part = BotConstructor.GetPartDesign(dna, options, false);

            this.ItemName = part.PartType;
            this.Part     = part;

            lblName.Text = this.ItemName;

            lblName.Visibility = _showName ? Visibility.Visible : Visibility.Collapsed;

            InitializeTrackball();

            RenderPart();
            InitializeLight();
        }
Пример #10
0
        private void UpdateSlot(int index)
        {
            if (_slots.Count != pnlSlots.Children.Count)
            {
                throw new ApplicationException(string.Format("The list and panel are out of sync.  list={0}, panel={1}", _slots.Count.ToString(), pnlSlots.Children.Count.ToString()));
            }
            else if (_slots.Count < index)
            {
                throw new ArgumentException(string.Format("Invalid slot index: {0}, count={1}", index.ToString(), _slots.Count.ToString()));
            }

            Weapon weapon = null;

            if (_weapons != null && _weapons.Count > index)
            {
                weapon = _weapons[index];
            }

            SlotItem slot = _slots[index];

            slot.Text.Text = (index + 1).ToString();

            if (weapon == null)
            {
                #region Empty

                slot.Text.Fill   = _emptyTextFill;
                slot.Text.Stroke = _emptyTextStroke;
                ((BlurEffect)slot.Text.Effect).Radius = 8;

                if (slot.WeaponVisual != null)
                {
                    slot.Viewport.Children.Remove(slot.WeaponVisual);
                }

                slot.WeaponToken           = null;
                slot.WeaponRotateAnimation = null;
                slot.WeaponVisual          = null;

                #endregion
            }
            else
            {
                #region Filled

                // Darken the background text
                slot.Text.Fill   = _filledTextFill;
                slot.Text.Stroke = _filledTextStroke;
                ((BlurEffect)slot.Text.Effect).Radius = 3;

                // Remove visual if wrong weapon
                if (slot.WeaponToken != null && slot.WeaponToken.Value != weapon.Token)
                {
                    slot.Viewport.Children.Remove(slot.WeaponVisual);
                    slot.WeaponToken  = null;
                    slot.WeaponVisual = null;
                }

                // Add weapon visual
                if (slot.WeaponToken == null)
                {
                    Model3D model = UtilityCore.Clone(weapon.Model);
                    QuaternionRotation3D quatTransform = new QuaternionRotation3D(Math3D.GetRandomRotation());
                    model.Transform = new RotateTransform3D(quatTransform);

                    slot.WeaponRotateAnimation = AnimateRotation.Create_AnyOrientation(quatTransform, 3d);

                    slot.WeaponVisual = new ModelVisual3D()
                    {
                        Content = model
                    };

                    // Pull the camera back to a good distance
                    //NOTE: The positions are nomalized by the caller after this method has finished
                    slot.Camera.Position = (slot.Camera.Position.ToVector().ToUnit() * (weapon.Radius * 2.7d)).ToPoint();

                    slot.Viewport.Children.Add(slot.WeaponVisual);
                    slot.WeaponToken = weapon.Token;
                }

                #endregion
            }
        }
Пример #11
0
 public override Cargo Clone()
 {
     return(new Cargo_ShipPart(UtilityCore.Clone(this.PartDNA), this.Density, this.Volume));
 }
Пример #12
0
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            const double LIFESPAN = 45;     // seconds
            const double MINSCORE = .5;
            const int    LEVEL    = 1;

            lock (_lock)
            {
                if (_isDisposed)
                {
                    return;
                }

                foreach (TrackedBot tracked in _trackedBots)
                {
                    switch (tracked.State)
                    {
                    case BotState.Adding:
                    case BotState.Removing:
                        break;

                    case BotState.None:
                        #region None

                        // Create a bot

                        BotDNA dna        = null;
                        BotDNA winningBot = _winningBot;
                        if (winningBot == null)
                        {
                            dna = GetRandomDNA(_itemOptions, _shellColors).Item1;
                        }
                        else
                        {
                            // Create a mutated copy of the winning design
                            dna          = UtilityCore.Clone(winningBot);
                            dna.UniqueID = Guid.NewGuid();
                            dna.Generation++;

                            if (dna.Parts != null)
                            {
                                MutateUtility.Mutate(dna.Parts, _mutateArgs);
                            }
                        }

                        tracked.State = BotState.Adding;

                        tracked.Lifespan = StaticRandom.NextPercent(LIFESPAN, .1);          // randomizing the lifespan a bit to stagger when bots get killed/created

                        Point3D position = Math3D.GetRandomVector_Circular(HOMINGRADIUS / 4d).ToPoint();
                        _dreamWorld.Add(new OfflineWorld.AddBotArgs(position, null, tracked.BotAdded, dna, LEVEL, new Point3D(0, 0, 0), HOMINGRADIUS, this.WeaponDNA));

                        #endregion
                        break;

                    case BotState.Added:
                        #region Added

                        // See if this should die
                        double age = (DateTime.UtcNow - tracked.Bot.CreationTime).TotalSeconds;
                        if (age > tracked.Lifespan)
                        {
                            FitnessTracker rules = tracked.Rules;
                            tracked.Rules = null;          // set it to null as soon as possible so that the rules tick doesn't do unnecessary work

                            double score = rules.Score / age;

                            if (score > MINSCORE && score > _winningScore)
                            {
                                BotDNA winningDNA = tracked.Bot.DNAFinal;

                                if (winningDNA != null)         // it should be non null long before this point, but just make sure
                                {
                                    _winningScore = score;
                                    _winningBot   = winningDNA;
                                }
                            }

                            // Kill it
                            tracked.State = BotState.Removing;
                            _dreamWorld.Remove(new OfflineWorld.RemoveArgs(tracked.Bot.Token, tracked.BotRemoved));
                        }

                        #endregion
                        break;
                    }

                    _timer.Start();
                }
            }
        }
Пример #13
0
        private void BrainNEAT_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_experiment == null || _ea == null)
                {
                    //NOTE: Just doing this for laziness.  I don't want to write a bunch of logic to train a phenome up front
                    MessageBox.Show("Need to have a running experiment", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                // Get a genome
                NeatGenome genome = _ea.CurrentChampGenome;

                // Create a phenome
                IBlackBox phenome = ExperimentNEATBase.GetBlackBox(genome, _experimentArgs.Activation, _hyperneatArgs);

                // Instantiate a BrainNEAT
                EditorOptions options     = new EditorOptions();
                ItemOptions   itemOptions = new ItemOptions();

                Container energy = new Container()
                {
                    QuantityMax     = 1000,
                    QuantityCurrent = 1000,
                };

                BrainNEATDNA dnaBrain = new BrainNEATDNA()
                {
                    PartType = BrainNEAT.PARTTYPE, Position = new Point3D(0, 0, 0), Orientation = Quaternion.Identity, Scale = new Vector3D(1, 1, 1)
                };

                BrainNEAT brain = new BrainNEAT(options, itemOptions, dnaBrain, energy);


                brain.SetPhenome(phenome, genome, _experimentArgs.Activation, _hyperneatArgs);


                for (int cntr = 0; cntr < 100; cntr++)
                {
                    foreach (INeuron neuron in brain.Neruons_Writeonly)
                    {
                        neuron.SetValue(StaticRandom.NextDouble(-2.5, 2.5));
                    }

                    brain.Update_AnyThread(1);
                }



                #region save/load test2

                // let BrainNEAT do the save/load

                BrainNEATDNA dna2     = (BrainNEATDNA)brain.GetNewDNA();
                string       dna2Text = XamlServices.Save(dna2).Replace('"', '\'');
                BrainNEAT    brain2   = new BrainNEAT(options, itemOptions, dna2, energy);

                for (int cntr = 0; cntr < 100; cntr++)
                {
                    foreach (INeuron neuron in brain2.Neruons_Writeonly)
                    {
                        neuron.SetValue(StaticRandom.NextDouble(-2.5, 2.5));
                    }

                    brain2.Update_AnyThread(1);
                }

                BrainNEATDNA dna3   = (BrainNEATDNA)brain2.GetNewDNA();
                BrainNEAT    brain3 = new BrainNEAT(options, itemOptions, dna3, energy);

                for (int cntr = 0; cntr < 100; cntr++)
                {
                    foreach (INeuron neuron in brain3.Neruons_Writeonly)
                    {
                        neuron.SetValue(StaticRandom.NextDouble(-2.5, 2.5));
                    }

                    brain3.Update_AnyThread(1);
                }

                #endregion
                #region save/load test1

                // initial test, building minimum necessary dna

                BrainNEATDNA brainDNA = new BrainNEATDNA()
                {
                    Activation           = _experimentArgs.Activation,
                    Hyper                = _hyperneatArgs,
                    NEATPositions_Input  = brain.Neruons_Readonly.Select(o => o.Position).ToArray(),
                    NEATPositions_Output = brain.Neruons_Writeonly.Select(o => o.Position).ToArray(),
                    Genome               = ExperimentNEATBase.SavePopulation(new[] { genome }),
                };


                // Make sure this can be serialized/deserialized
                string testString = XamlServices.Save(brainDNA);
                brainDNA = UtilityCore.Clone(brainDNA);


                List <NeatGenome> genomeList = null;
                if (_hyperneatArgs == null)
                {
                    genomeList = ExperimentNEATBase.LoadPopulation(brainDNA.Genome, brainDNA.Activation, brainDNA.NEATPositions_Input.Length, brainDNA.NEATPositions_Output.Length);
                }
                else
                {
                    genomeList = ExperimentNEATBase.LoadPopulation(brainDNA.Genome, brainDNA.Activation, _hyperneatArgs);
                }

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