Beispiel #1
0
        public FluidPainter2D()
        {
            InitializeComponent();

            this.Background = SystemColors.ControlBrush;

            //NOTE: RandColorType.Any is calculated on the fly isntead of preloaded
            _randColors = new SortedList <RandColorType, Color[]>();
            _randColors.Add(RandColorType.Black_Green, new Color[] { Colors.Black, Colors.Black, Colors.Black, Colors.Chartreuse });
            _randColors.Add(RandColorType.Black_Orange, new Color[] { Colors.Black, Colors.Black, Colors.Black, UtilityWPF.ColorFromHex("F76700") });
            _randColors.Add(RandColorType.Black_Purple, new Color[] { Colors.Black, Colors.Black, Colors.Black, UtilityWPF.ColorFromHex("811CD6") });
            _randColors.Add(RandColorType.Red_Tan_Green, new string[] { "65BA99", "59A386", "F1DDBB", "D6C4A6", "E74C3C", "C74134" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Tans, new string[] { "736753", "594832", "D9CFC7", "BFB6AE", "A68D77" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Skittles, new string[] { "AC1014", "E87011", "FDD526", "73C509", "0980BA", "65286B" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Unispew, new string[] { "FF009C", "FFA11F", "9BFF00", "00FFFD", "8E47FF" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Camo, new string[] { "244034", "5E744A", "9EA755", "0D0A00", "745515" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Cold_Beach, new string[] { "CCC8B1", "858068", "FFFCF6", "B7ECFF", "B1CCCC" }.Select(o => UtilityWPF.ColorFromHex(o)).ToArray());
            _randColors.Add(RandColorType.Mono_Cyan, UtilityCore.Iterate(new string[] { "037B8E" }, Enumerable.Range(0, 10).Select(o => new string[] { "99A3A4", "B8BCBB", "535855", "79756A" }).SelectMany(o => o)).Select(o => UtilityWPF.ColorFromHex(o)).ToArray());

            foreach (string colorType in Enum.GetNames(typeof(RandColorType)))
            {
                cboBrushColorType.Items.Add(colorType.Replace('_', ' '));
                cboRandColorType.Items.Add(colorType.Replace('_', ' '));
            }
            cboBrushColorType.SelectedIndex = StaticRandom.Next(cboBrushColorType.Items.Count);
            cboRandColorType.SelectedIndex  = StaticRandom.Next(cboRandColorType.Items.Count);
        }
Beispiel #2
0
        private static GeometryModel3D GetModel_WoodIron_Ring_Band(double ballRadius, double z, System.Windows.Media.Media3D.Material material, TriangleIndexed[] ball, SortedList <string, double> from, SortedList <string, double> to, string prefix)
        {
            const double ENLARGE = 1.04d;

            GeometryModel3D retVal = new GeometryModel3D();

            retVal.Material     = material;
            retVal.BackMaterial = material;

            double bandHeight     = WeaponDNA.GetKeyValue(prefix + "Height", from, to, StaticRandom.NextPercent(ballRadius * .15, .5));
            double bandHeightHalf = bandHeight / 2d;

            // Slice the hull at the top and bottom band z's
            Point3D[] slice1 = Math3D.GetIntersection_Hull_Plane(ball, new Triangle(new Point3D(0, 0, z - bandHeightHalf), new Point3D(1, 0, z - bandHeightHalf), new Point3D(0, 1, z - bandHeightHalf)));
            Point3D[] slice2 = Math3D.GetIntersection_Hull_Plane(ball, new Triangle(new Point3D(0, 0, z + bandHeightHalf), new Point3D(1, 0, z + bandHeightHalf), new Point3D(0, 1, z + bandHeightHalf)));

            // Enlarge those polygons xy, leave z alone
            slice1 = slice1.Select(o => new Point3D(o.X * ENLARGE, o.Y * ENLARGE, o.Z)).ToArray();
            slice2 = slice2.Select(o => new Point3D(o.X * ENLARGE, o.Y * ENLARGE, o.Z)).ToArray();

            // Now turn those two polygons into a 3d hull
            TriangleIndexed[] band = Math3D.GetConvexHull(UtilityCore.Iterate(slice1, slice2).ToArray());

            retVal.Geometry = UtilityWPF.GetMeshFromTriangles(band);

            return(retVal);
        }
Beispiel #3
0
        public BrainNEAT(EditorOptions options, ItemOptions itemOptions, BrainNEATDNA dna, IContainer energyTanks)
            : base(options, dna, itemOptions.Brain_Damage.HitpointMin, itemOptions.Brain_Damage.HitpointSlope, itemOptions.Brain_Damage.Damage)
        {
            _itemOptions = itemOptions;
            _energyTanks = energyTanks;

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

            if (dna == null || dna.UniqueID == Guid.Empty)
            {
                _uniqueID = Guid.NewGuid();
            }
            else
            {
                _uniqueID = dna.UniqueID;
            }

            Brain.GetMass(out _mass, out _volume, out double radius, out _scaleActual, dna, itemOptions);
            Radius = radius;

            //var neurons = CreateNeurons_HARDCODED(dna, itemOptions);
            var neurons = CreateNeurons(dna, itemOptions);

            _neuronsInput  = neurons.input;
            _neuronsOutput = neurons.output;
            _neuronsAll    = UtilityCore.Iterate <INeuron>(_neuronsInput, _neuronsOutput).ToArray();

            BuildNEATBrain(dna);
        }
Beispiel #4
0
        private static Tuple <string, WinningBean[]> GetWinnersSprtLineage(string lineage, Tuple <string, WinningBean[]> existing, WinningBean[] candidates, int maxPerLineage, bool tracksLivingInstances)
        {
            List <WinningBean> distinctBeans = new List <WinningBean>();

            if (tracksLivingInstances)
            {
                // Existing and candidate lists could have the same instance of a bean (from different moments in time).  Group by
                // bean instances
                var beanGroups = UtilityCore.Iterate(existing == null ? null : existing.Item2, candidates).
                                 GroupBy(o => o.Ship.PhysicsBody). // the physics body implements IComparable (compares on token)
                                 ToArray();

                // Now pull only the best example from each instance of a bean
                foreach (var group in beanGroups)
                {
                    distinctBeans.Add(group.OrderByDescending(o => o.Score).First());
                }
            }
            else
            {
                // DNA should never be shared between existing and new, so everything is unique
                distinctBeans = UtilityCore.Iterate(existing == null ? null : existing.Item2, candidates).ToList();
            }

            // Sort by score, and take the top performers
            WinningBean[] retVal = distinctBeans.
                                   OrderByDescending(o => o.Score).
                                   Take(maxPerLineage).
                                   ToArray();

            // Exit Function
            return(Tuple.Create(lineage, retVal));
        }
Beispiel #5
0
        private static void AddBezierPlate(int count, BezierSegment3D seg1, BezierSegment3D seg2, Model3DGroup group, Material material)
        {
            // Since the bezier curves will have the same number of points, create a bunch of squares linking them (it's up to the caller
            // to make sure the curves don't cross, or you would get a bow tie)
            Point3D[] rim1 = BezierUtil.GetPoints(count, seg1);
            Point3D[] rim2 = BezierUtil.GetPoints(count, seg2);

            Point3D[] allPoints = UtilityCore.Iterate(rim1, rim2).ToArray();

            List <TriangleIndexed> triangles = new List <TriangleIndexed>();

            for (int cntr = 0; cntr < count - 1; cntr++)
            {
                triangles.Add(new TriangleIndexed(count + cntr, count + cntr + 1, cntr, allPoints));    // bottom left
                triangles.Add(new TriangleIndexed(cntr + 1, cntr, count + cntr + 1, allPoints));        // top right
            }

            // Geometry Model
            GeometryModel3D geometry = new GeometryModel3D();

            geometry.Material     = material;
            geometry.BackMaterial = material;
            geometry.Geometry     = UtilityWPF.GetMeshFromTriangles(triangles.ToArray());

            group.Children.Add(geometry);
        }
Beispiel #6
0
        //TODO: keep track of what types were added to map (a type added event) and store the types that implement IPartUpdatable
        //When that happens, ask map to include derived, and only store the base most type that implements IPartUpdatable
        /// <param name="types_main">Types to call update on the main thread (can add the same type to both main and any)</param>
        /// <param name="types_any">Types to call update on any thread (can add the same type to both main and any)</param>
        public UpdateManager(Type[] types_main, Type[] types_any, Map map, int interval = 50, bool useTimer = true)
        {
            #region validate

            Type updateableType = typeof(IPartUpdatable);
            Type nonImplement   = UtilityCore.Iterate(types_main, types_any).
                                  Where(o => !o.GetInterfaces().Any(p => p.Equals(updateableType))).
                                  FirstOrDefault(); // one example is enough

            if (nonImplement != null)
            {
                throw new ArgumentException("Type passed in doesn't implement IPartUpdatable: " + nonImplement.ToString());
            }

            #endregion

            _typesMainUnchecked = types_main;
            _typesAnyUnchecked  = types_any;

            _map = map;

            if (useTimer)
            {
                _timerAnyThread           = new System.Timers.Timer();
                _timerAnyThread.Interval  = 50;
                _timerAnyThread.AutoReset = false;       // makes sure only one tick is firing at a time
                _timerAnyThread.Elapsed  += TimerAnyThread_Elapsed;
                _timerAnyThread.Start();
            }
            else
            {
                _clockAnyThread = new RealtimeClock();
            }
        }
Beispiel #7
0
        private int FindOrCreateTab(Tuple <PartToolItemBase, PartDesignBase> part)
        {
            int index = FindTab(part);

            if (index >= 0)
            {
                return(index);
            }

            string category = part.Item1.Category;

            // Figure out where to insert it
            string[] sorted = SortCategories(UtilityCore.Iterate <string>(_tabStats.Select(o => o.Item1), category));

            index = Array.IndexOf <string>(sorted, category);

            #region create tab

            TabItem tab = new TabItem()
            {
                DataContext = this,
                Header      = PartCategoryIcons.GetIcon(part.Item1.TabName, category, _brushPrimary, _brushSecondary, 24),
                ToolTip     = category,
            };

            ScrollViewer scroll = new ScrollViewer()
            {
                HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled,
                VerticalScrollBarVisibility   = ScrollBarVisibility.Auto,
                Padding = new Thickness(0, 0, 6, 0),
            };

            UniformGrid panel = new UniformGrid()
            {
                Columns  = 1,
                MaxWidth = 200,
            };
            scroll.Content = panel;

            tab.Content = scroll;

            #endregion

            _tabStats.Insert(index, Tuple.Create(category, panel));
            base.Tabs.Insert(index, tab);

            return(index);
        }
        /// <summary>
        /// This version starts with a SOM, then potentially splits the largest node and/or gathers the smallest nodes into a single
        /// </summary>
        /// <returns></returns>
        public static SOMResult Train(ISOMInput[] inputs, SOMRules rules, bool isDisplay2D)
        {
            SOMResult result = SelfOrganizingMaps.TrainSOM(inputs, rules, isDisplay2D);

            if (result.Nodes.Length == 0)
            {
                return(result);
            }
            else if (result.Nodes.Length == 1)
            {
                #region kmeans single node

                if (inputs.Length < 20)
                {
                    return(result);
                }

                return(SelfOrganizingMaps.TrainKMeans(inputs, 5, true));

                #endregion
            }

            var categorized = GetSOM_SplitMerge_Categorize(result);

            List <SOMNode>     nodes     = new List <SOMNode>();
            List <ISOMInput[]> newInputs = new List <ISOMInput[]>();

            foreach (NodeCombo set in UtilityCore.Iterate(categorized.kmeans, categorized.keep))        // UtilityCore.Iterate gracefully skips nulls
            {
                nodes.Add(set.Node);
                newInputs.Add(set.Inputs);
            }

            if (categorized.remaining != null)
            {
                nodes.Add(new SOMNode()
                {
                    Position = MathND.GetCenter(categorized.remaining.Select(o => o.Node.Position)),
                    Weights  = MathND.GetCenter(categorized.remaining.Select(o => o.Node.Weights)),
                });

                newInputs.Add(categorized.remaining.
                              SelectMany(o => o.Inputs).
                              ToArray());
            }

            return(new SOMResult(nodes.ToArray(), newInputs.ToArray(), false));
        }
Beispiel #9
0
        /// <summary>
        /// This merges the current tree with the beans passed in.  Only keeps the top performers, independent of where they came from
        /// </summary>
        private static Tuple <DateTime, WinningSet[]> GetWinners(Tuple <DateTime, WinningSet[]> existing, WinningBean[] candidates, int maxLineages, int maxPerLineage, bool tracksLivingInstances)
        {
            List <WinningSet> retVal = new List <WinningSet>();

            #region Validate candidates

            if (candidates != null)
            {
                if (tracksLivingInstances)
                {
                    if (candidates.Any(o => o.DNA != null))
                    {
                        throw new ArgumentException("When tracking live instances, raw dna shouldn't be passed in");
                    }
                }
                else
                {
                    if (candidates.Any(o => o.Ship != null))
                    {
                        throw new ArgumentException("When tracking dna, live instances shouldn't be passed in");
                    }
                }
            }

            #endregion

            // Shoot through all the unique names across exising and candidate
            foreach (string name in UtilityCore.Iterate(
                         existing == null ? null : existing.Item2.Select(o => o.ShipName),
                         tracksLivingInstances ? candidates.Select(o => o.Ship.Name) : candidates.Select(o => o.DNA.ShipName)
                         ).Distinct())
            {
                // Each name is treated independently of the other names.  So one name could have far worse winners than
                // others, and it wouldn't matter
                retVal.Add(GetWinnersSprtName(name,
                                              existing == null ? null : existing.Item2.Where(o => o.ShipName == name).FirstOrDefault(),
                                              tracksLivingInstances ? candidates.Where(o => o.Ship.Name == name).ToArray() : candidates.Where(o => o.DNA.ShipName == name).ToArray(),
                                              maxLineages, maxPerLineage, tracksLivingInstances));
            }

            // Sort the list by the highest performer
            return(Tuple.Create(DateTime.UtcNow,
                                retVal.OrderByDescending(o => o.BeansByLineage.Max(p => p.Item2.Max(q => q.Score))).
                                ToArray()));
        }
Beispiel #10
0
        private static WinningSet GetWinnersSprtName(string name, WinningSet existing, WinningBean[] candidates, int maxLineages, int maxPerLineage, bool tracksLivingInstances)
        {
            if (candidates == null)
            {
                #region Validate Existing

                //TODO: See if the constraints are more restrictive
                //if (existing != null)
                //{
                //    if (existing.BeansByLineage.Length > maxLineages)
                //    {

                //    }
                //}

                #endregion
                return(existing);
            }

            // Group the candidates up by lineage
            var candidateLineage = candidates.GroupBy(o => tracksLivingInstances ? o.Ship.Lineage : o.DNA.ShipLineage).ToArray();

            List <Tuple <string, WinningBean[]> > retVal = new List <Tuple <string, WinningBean[]> >();

            // Shoot through all the unique lineages across existing and candidate
            foreach (string lineage in UtilityCore.Iterate(
                         existing == null ? null : existing.BeansByLineage.Select(o => o.Item1),
                         candidateLineage.Select(o => o.Key)).
                     Distinct())
            {
                var matchingCandidate = candidateLineage.Where(o => o.Key == lineage).FirstOrDefault();

                // Get the top beans for this lineage
                retVal.Add(GetWinnersSprtLineage(lineage,
                                                 existing == null ? null : existing.BeansByLineage.Where(o => o.Item1 == lineage).FirstOrDefault(),
                                                 matchingCandidate == null ? null : matchingCandidate.ToArray(),
                                                 maxPerLineage, tracksLivingInstances));
            }

            // Sort, take top
            return(new WinningSet(name,
                                  retVal.OrderByDescending(o => o.Item2.Max(p => p.Score)).
                                  Take(maxLineages).
                                  ToArray()));
        }
Beispiel #11
0
        //TODO: Make this a ThreadLocal
        private Model3D GetModel(Color?color = null)
        {
            var ball = UtilityWPF.GetTruncatedIcosidodecahedron(1, null);

            Model3DGroup retVal = new Model3DGroup();

            // Black
            MaterialGroup materials = new MaterialGroup();

            materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("141414"))));
            materials.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("08FF0000")), 20));

            GeometryModel3D geometry = new GeometryModel3D();

            geometry.Material     = materials;
            geometry.BackMaterial = materials;

            geometry.Geometry = UtilityWPF.GetMeshFromTriangles(UtilityCore.Iterate(ball.Hexagons, ball.Squares).SelectMany(o => o));

            retVal.Children.Add(geometry);

            // White
            materials = new MaterialGroup();
            if (color == null)
            {
                materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("F8F8F8"))));
                //materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("222"))));
                //materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(Colors.Chartreuse)));
            }
            else
            {
                materials.Children.Add(new DiffuseMaterial(new SolidColorBrush(color.Value)));
            }
            materials.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("A0FF0000")), 30));

            geometry              = new GeometryModel3D();
            geometry.Material     = materials;
            geometry.BackMaterial = materials;

            geometry.Geometry = UtilityWPF.GetMeshFromTriangles_IndependentFaces(ball.Decagons.SelectMany(o => o));

            retVal.Children.Add(geometry);

            return(retVal);
        }
Beispiel #12
0
        public static Tuple <FlagBackType, FlagOverlayType?, FlagOverlayType?> GetRandomEnums()
        {
            Random rand = StaticRandom.GetRandomForThread();

            double overlayProb = rand.NextDouble();

            // Choose a background
            FlagBackType backType = UtilityCore.GetRandomEnum <FlagBackType>();

            FlagOverlayType[] backTypeFilter = _similarOptions.Value.
                                               Where(o => o.Item2.Any(p => p == backType)).
                                               SelectMany(o => o.Item1).
                                               ToArray();

            // Choose overlay one
            FlagOverlayType?overlayType1 = null;

            if (overlayProb > .33)
            {
                overlayType1 = UtilityCore.GetRandomEnum <FlagOverlayType>(backTypeFilter);
            }

            // Choose overlay two
            FlagOverlayType?overlayType2 = null;

            if (overlayProb > .66)
            {
                var test = _notAbove.Value.
                           Where(o => o.Item2.Any(p => p == overlayType1.Value)).
                           SelectMany(o => o.Item1).
                           ToArray();


                IEnumerable <FlagOverlayType> filter2 = UtilityCore.Iterate(
                    new[] { overlayType1.Value },
                    backTypeFilter,
                    _similarOptions.Value.Where(o => o.Item1.Any(p => p == overlayType1.Value)).SelectMany(o => o.Item1),
                    _notAbove.Value.Where(o => o.Item2.Any(p => p == overlayType1.Value)).SelectMany(o => o.Item1)
                    );

                overlayType2 = UtilityCore.GetRandomEnum <FlagOverlayType>(filter2);
            }

            return(Tuple.Create(backType, overlayType1, overlayType2));
        }
Beispiel #13
0
        /// <summary>
        /// This looks long direction until a spot large enough to hold size is available
        /// </summary>
        /// <param name="size">The size of the rectangle to return</param>
        /// <param name="start">The point that the rectangle would like to be centered over</param>
        /// <param name="direction">
        /// The direction to slide the rectangle until an empty space is found
        /// NOTE: Set dir.Y to be negative to match screen coords
        /// </param>
        public static Rect GetFreeSpot(Size size, Point desiredPos, Vector direction, List <Rect> existing)
        {
            double halfWidth  = size.Width / 2d;
            double halfHeight = size.Height / 2d;

            if (existing.Count == 0)
            {
                // There is nothing blocking this, center the rectangle over the position
                return(new Rect(desiredPos.X - halfWidth, desiredPos.Y - halfHeight, size.Width, size.Height));
            }

            // Direction unit
            Vector dirUnit = direction.ToUnit(true);

            if (Math2D.IsInvalid(dirUnit))
            {
                dirUnit = Math3D.GetRandomVector_Circular_Shell(1).ToVector2D();
            }

            // Calculate step distance (5% of the average of all the sizes)
            double stepDist = UtilityCore.Iterate <Size>(size, existing.Select(o => o.Size)).
                              SelectMany(o => new[] { o.Width, o.Height }).
                              Average();

            stepDist *= .05;

            // Keep walking along direction until the rectangle doesn't intersect any existing rectangles
            Point point = new Point();
            Rect  rect  = new Rect();

            for (int cntr = 0; cntr < 5000; cntr++)
            {
                point = desiredPos + (dirUnit * (stepDist * cntr));
                rect  = new Rect(point.X - halfWidth, point.Y - halfHeight, size.Width, size.Height);

                if (!existing.Any(o => o.IntersectsWith(rect)))
                {
                    break;
                }
            }

            return(rect);
        }
Beispiel #14
0
        private static TriangleIndexed[] GetModel_Composite_SquareSides(Rhombicuboctahedron ball, double depth)
        {
            List <TriangleIndexed> retVal = new List <TriangleIndexed>();

            foreach (int[] square in UtilityCore.Iterate(ball.SquarePolys_Orth, ball.SquarePolys_Diag))
            {
                Point3D[] initialPoints = square.Select(o => ball.AllPoints[o]).ToArray();

                Vector3D offset = Math2D.GetPolygonNormal(initialPoints, PolygonNormalLength.Unit) * -depth;

                for (int cntr = 0; cntr < square.Length - 1; cntr++)
                {
                    retVal.AddRange(GetModel_Composite_SquareSides_Side(initialPoints[cntr], initialPoints[cntr + 1], offset, depth));
                }

                retVal.AddRange(GetModel_Composite_SquareSides_Side(initialPoints[square.Length - 1], initialPoints[0], offset, depth));
            }

            return(retVal.ToArray());
        }
Beispiel #15
0
        public MotionController2(EditorOptions options, ItemOptionsArco itemOptions, ShipPartDNA dna, AIMousePlate mousePlate)
            : base(options, dna, itemOptions.MotionController_Damage.HitpointMin, itemOptions.MotionController_Damage.HitpointSlope, itemOptions.MotionController_Damage.Damage)
        {
            _itemOptions = itemOptions;
            _mousePlate  = mousePlate;

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

            GetMass(out _mass, out double volume, out double radius, out _scaleActual, dna, itemOptions);

            this.Radius = radius;

            var neurons = CreateNeurons(dna, itemOptions);

            _neuron_rotate_direction_speed = neurons.rot_dirspeed;
            _neuron_rotate_radius          = neurons.rot_radius;
            _neurons_linear = neurons.linear;
            _neurons_all    = UtilityCore.Iterate <Neuron_SensorPosition>(_neuron_rotate_direction_speed, _neuron_rotate_radius, _neurons_linear).ToArray();
        }
Beispiel #16
0
        private static NeuronBackPointer[] BuildBackLinks(Neuron[] inputs, Neuron[] neurons, Neuron[] outputs, NeuronLink[] links)
        {
            List <NeuronBackPointer> retVal = new List <NeuronBackPointer>();

            // Split the list apart by To (and get all links by each To neuron)
            var neuronLinks = links.Where(o => !o.To_IsOutput).GroupBy(o => o.To_Index).ToArray();
            var outputLinks = links.Where(o => o.To_IsOutput).GroupBy(o => o.To_Index).ToArray();

            // Build return items
            foreach (var link in UtilityCore.Iterate(neuronLinks, outputLinks))
            {
                retVal.Add(new NeuronBackPointer(
                               link.First().To_IsOutput ? outputs[link.Key] : neurons[link.Key],
                               link.Select(o => o.From_IsInput ? inputs[o.From_Index] : neurons[o.From_Index]).ToArray(),
                               link.ToArray()));
            }

            // Exit Function
            return(retVal.ToArray());
        }
Beispiel #17
0
        public void ShowInventories(Shop shop, ArcBot bot)
        {
            _shop = shop;
            _bot  = bot;
            _animationRotates.Clear();

            if (bot.Weapon == null)
            {
                this.AttachedWeaponID = null;
            }
            else
            {
                this.AttachedWeaponID = bot.Weapon.DNA.UniqueID;
                bot.AttachWeapon(null, ItemToFrom.Nowhere, ItemToFrom.Inventory);
            }

            //TODO: When the user can create weapons in the shop, this will need to be recalculated, and all item cameras need to be adjusted
            double maxWeaponRadius = UtilityCore.Iterate(shop.Inventory.Weapons, bot.Inventory.Weapons).Max(o => o.Radius);

            LoadInventory(lstShopInventory, shop.Inventory, _animationRotates, maxWeaponRadius);
            LoadInventory(lstBotInventory, bot.Inventory, _animationRotates, maxWeaponRadius);
        }
Beispiel #18
0
        private string GetUniqueName(string name)
        {
            string[] existingNames = UtilityCore.Iterate(_options.DefaultBeanList.Keys, _options.NewBeanList.Keys).ToArray();

            int suffix = 0;

            while (true)
            {
                string retVal = name;
                if (suffix > 0)
                {
                    retVal += " (" + suffix.ToString() + ")";
                }

                if (!existingNames.Any(o => o.Equals(retVal, StringComparison.OrdinalIgnoreCase)))
                {
                    return(retVal);
                }

                suffix++;
            }
        }
Beispiel #19
0
        private static BezierSegment3D[] GetModel_Second_Segments(AxeSecondProps arg)
        {
            Point3D[] points = arg.GetAllPoints();

            // Top
            BezierSegment3D top = new BezierSegment3D(arg.IndexTL, arg.IndexTR, null, points);

            // Edge
            Point3D         controlTR = BezierUtil.GetControlPoint_End(arg.EndTR, arg.EndBR, arg.EndBL_1, true, arg.EdgeAngleT, arg.EdgePercentT);
            Point3D         controlBR = BezierUtil.GetControlPoint_End(arg.EndBR, arg.EndTR, arg.EndTL, true, arg.EdgeAngleB, arg.EdgePercentB);
            BezierSegment3D edge      = new BezierSegment3D(arg.IndexTR, arg.IndexBR, new[] { controlTR, controlBR }, points);

            // Bottom (right portion)
            BezierSegment3D bottomRight = null;

            if (arg.EndBL_2 == null)
            {
                Point3D controlR = BezierUtil.GetControlPoint_End(arg.EndBR, arg.EndBL_1, arg.EndTR, false, arg.B1AngleR, arg.B1PercentR);
                Point3D controlL = BezierUtil.GetControlPoint_End(arg.EndBL_1, arg.EndBR, arg.EndTR, false, arg.B1AngleL, arg.B1PercentL);
                bottomRight = new BezierSegment3D(arg.IndexBR, arg.IndexBL_1, new[] { controlR, controlL }, points);
            }
            else
            {
                bottomRight = new BezierSegment3D(arg.IndexBR, arg.IndexBL_1, null, points);
            }

            // Bottom (left portion)
            BezierSegment3D bottomLeft = null;

            if (arg.EndBL_2 != null)
            {
                Point3D controlR = BezierUtil.GetControlPoint_End(arg.EndBL_1, arg.EndBL_2.Value, arg.EndTR, false, arg.B2AngleR, arg.B2PercentR);
                Point3D controlL = BezierUtil.GetControlPoint_End(arg.EndBL_2.Value, arg.EndBL_1, arg.EndTR, false, arg.B2AngleL, arg.B2PercentL);
                bottomLeft = new BezierSegment3D(arg.IndexBL_1, arg.IndexBL_2, new[] { controlR, controlL }, points);
            }

            return(UtilityCore.Iterate <BezierSegment3D>(top, edge, bottomRight, bottomLeft).ToArray());
        }
Beispiel #20
0
        public static (NeuralBucket bucket, Task <NeuralBucket> addTask, NeuralPool_ManualTick manualPool) AddToNeuralPool(NeuralUtility.ContainerOutput[] links, NeuralPool_ManualTick manualPool)
        {
            // Create the bucket
            NeuralBucket bucket = new NeuralBucket(links.SelectMany(o => UtilityCore.Iterate(o.InternalLinks, o.ExternalLinks)).ToArray());

            Task <NeuralBucket> task = null;

            if (manualPool != null)
            {
                manualPool.Add(bucket);
            }
            else
            {
                // Add to the pool from another thread.  This way the lock while waiting to add won't tie up this thread
                task = Task.Run(() =>
                {
                    NeuralPool.Instance.Add(bucket);
                    return(bucket);
                });
            }

            return(bucket, task, manualPool);
        }
Beispiel #21
0
        private static Point3D[] GetPlacements(int count, double minDistanceSquared, Point3D[] existing, Func <Vector3D> getRandVector)
        {
            Vector3D[] existingCast = existing == null ? new Vector3D[0] : existing.Select(o => o.ToVector()).ToArray();

            List <Vector3D> retVal = new List <Vector3D>();

            for (int cntr = 0; cntr < count; cntr++)
            {
                while (true)
                {
                    // Ask the delegate for a random vector
                    Vector3D test = getRandVector();

                    // Make sure this isn't too close to the other items
                    bool wasTooClose = false;

                    foreach (Vector3D prev in UtilityCore.Iterate(existingCast, retVal))
                    {
                        double distance = (test - prev).LengthSquared;
                        if (distance < minDistanceSquared)
                        {
                            wasTooClose = true;
                            break;
                        }
                    }

                    if (!wasTooClose)
                    {
                        retVal.Add(test);
                        break;
                    }
                }
            }

            // Exit Function
            return(retVal.Select(o => o.ToPoint()).ToArray());
        }
Beispiel #22
0
        private void BuildTerrain()
        {
            // Figure out where the extra ring of points should go
            double radius = BuildTerrainSprtRadius(_neurons.Select(o => o.Position.ToPoint2D()).ToArray());

            // Figure out how many extra points to make
            int numExtra = BuildTerrainSprtNumExtra(_neurons.Length);

            // Lay down all the points into a single array
            _terrainPoints = UtilityCore.Iterate(
                _neurons.Select(o => o.Position),                                                         // first points are the neuron's locations (don't worry about Z right now, they will change each update)
                Math2D.GetCircle_Cached(numExtra).Select(o => new Point3D(o.X * radius, o.Y * radius, 0)) // tack on a bunch of points around the edge
                ).ToArray();

            // Get the delaunay of these points
            TriangleIndexed[] triangles = Math2D.GetDelaunayTriangulation(_terrainPoints.Select(o => o.ToPoint2D()).ToArray(), _terrainPoints);

            // Convert into linked triangles
            List <TriangleIndexedLinked> trianglesLinked = triangles.Select(o => new TriangleIndexedLinked(o.Index0, o.Index1, o.Index2, o.AllPoints)).ToList();

            TriangleIndexedLinked.LinkTriangles_Edges(trianglesLinked, true);

            _terrainTriangles = trianglesLinked.ToArray();
        }
Beispiel #23
0
        private Model3D GetModel()
        {
            const double SIZE = 4;

            Model3DGroup    retVal = new Model3DGroup();
            GeometryModel3D geometry;
            MaterialGroup   material;

            var rhomb = UtilityWPF.GetRhombicuboctahedron(SIZE, SIZE, SIZE);

            TriangleIndexed[] triangles;

            #region X,Y,Z spikes

            double thickness = .2;
            double length    = SIZE * 1.5;

            retVal.Children.Add(new BillboardLine3D()
            {
                Color             = UtilityWPF.ColorFromHex("80" + ChaseColors.X),
                IsReflectiveColor = false,
                Thickness         = thickness,
                FromPoint         = new Point3D(0, 0, 0),
                ToPoint           = new Point3D(length, 0, 0)
            }.Model);

            retVal.Children.Add(new BillboardLine3D()
            {
                Color             = UtilityWPF.ColorFromHex("80" + ChaseColors.Y),
                IsReflectiveColor = false,
                Thickness         = thickness,
                FromPoint         = new Point3D(0, 0, 0),
                ToPoint           = new Point3D(0, length, 0)
            }.Model);

            retVal.Children.Add(new BillboardLine3D()
            {
                Color             = UtilityWPF.ColorFromHex("80" + ChaseColors.Z),
                IsReflectiveColor = false,
                Thickness         = thickness,
                FromPoint         = new Point3D(0, 0, 0),
                ToPoint           = new Point3D(0, 0, length)
            }.Model);

            #endregion

            #region X plates

            geometry = new GeometryModel3D();

            material = new MaterialGroup();
            material.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("80" + ChaseColors.X))));
            material.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("70DCE01D")), 5));

            geometry.Material     = material;
            geometry.BackMaterial = material;

            triangles = rhomb.Squares_Orth.
                        SelectMany(o => o).
                        Where(o => o.IndexArray.All(p => Math1D.IsNearValue(Math.Abs(o.AllPoints[p].X * 2), SIZE))).
                        ToArray();

            geometry.Geometry = UtilityWPF.GetMeshFromTriangles_IndependentFaces(triangles);

            retVal.Children.Add(geometry);

            #endregion
            #region Y plates

            geometry = new GeometryModel3D();

            material = new MaterialGroup();
            material.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("80" + ChaseColors.Y))));
            material.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("702892BF")), 3));

            geometry.Material     = material;
            geometry.BackMaterial = material;

            triangles = rhomb.Squares_Orth.
                        SelectMany(o => o).
                        Where(o => o.IndexArray.All(p => Math1D.IsNearValue(Math.Abs(o.AllPoints[p].Y * 2), SIZE))).
                        ToArray();

            geometry.Geometry = UtilityWPF.GetMeshFromTriangles_IndependentFaces(triangles);

            retVal.Children.Add(geometry);

            #endregion
            #region Z plates

            geometry = new GeometryModel3D();

            material = new MaterialGroup();
            material.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("80" + ChaseColors.Z))));
            material.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("B0CF1919")), 17));

            geometry.Material     = material;
            geometry.BackMaterial = material;

            triangles = rhomb.Squares_Orth.
                        SelectMany(o => o).
                        Where(o => o.IndexArray.All(p => Math1D.IsNearValue(Math.Abs(o.AllPoints[p].Z * 2), SIZE))).
                        ToArray();

            geometry.Geometry = UtilityWPF.GetMeshFromTriangles_IndependentFaces(triangles);

            retVal.Children.Add(geometry);

            #endregion
            #region Base

            geometry = new GeometryModel3D();

            material = new MaterialGroup();
            material.Children.Add(new DiffuseMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("305B687A"))));
            material.Children.Add(new SpecularMaterial(new SolidColorBrush(UtilityWPF.ColorFromHex("507E827A")), 12));

            geometry.Material     = material;
            geometry.BackMaterial = material;

            triangles = UtilityCore.Iterate(
                rhomb.Squares_Diag.SelectMany(o => o),
                rhomb.Triangles
                ).ToArray();

            geometry.Geometry = UtilityWPF.GetMeshFromTriangles_IndependentFaces(triangles);

            retVal.Children.Add(geometry);

            #endregion

            return(retVal);
        }
Beispiel #24
0
 public Point3D[] GetAllPoints()
 {
     return(UtilityCore.Iterate <Point3D>(this.EndTL, this.EndTR, this.EndBR, this.EndBL_1, this.EndBL_2).ToArray());
 }
Beispiel #25
0
        private void btnPlaceIO_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region Wipe Existing

                foreach (Neuron node in UtilityCore.Iterate(_inputs, _outputs, _neurons))               // the iterate method will skip null arrays
                {
                    _viewport.Children.Remove(node.Visual);
                }

                if (_links != null)
                {
                    foreach (NeuronLink link in _links)
                    {
                        _viewport.Children.Remove(link.Visual);
                    }
                }

                _inputs    = null;
                _outputs   = null;
                _neurons   = null;
                _links     = null;
                _backLinks = null;

                #endregion

                #region Calculate Positions

                Point3D[] inputPos, outputPos;

                if (radPlates.IsChecked.Value)
                {
                    inputPos  = GetPlatePlacement(4, RADIUS_IO, RADIUS_IO, FACTOR_IO);
                    outputPos = GetPlatePlacement(3, RADIUS_IO, -RADIUS_IO, FACTOR_IO);
                }
                else if (radRandom.IsChecked.Value)
                {
                    Point3D[] positions = GetSpherePlacement(7, RADIUS_IO, FACTOR_IO, null);

                    inputPos  = Enumerable.Range(0, 4).Select(o => positions[o]).ToArray();
                    outputPos = Enumerable.Range(4, 3).Select(o => positions[o]).ToArray();
                }
                else
                {
                    MessageBox.Show("Unknown Placement Type", this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                #endregion

                _inputs  = BuildIO(inputPos, true);
                _outputs = BuildIO(outputPos, false);

                TransferInputValues();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Beispiel #26
0
 private static Point3D[] CombineNeuronPositions(Point3D rotationLeft, Point3D rotationRight, Point3D[] linear)
 {
     return(UtilityCore.Iterate <Point3D>(rotationLeft, rotationRight, linear).
            ToArray());
 }
Beispiel #27
0
        private static Model3DGroup GetModel_Composite(WeaponSpikeBallDNA dna, WeaponSpikeBallDNA finalDNA, WeaponMaterialCache materials)
        {
            Model3DGroup retVal = new Model3DGroup();

            Random rand = StaticRandom.GetRandomForThread();

            var from = dna.KeyValues;
            var to   = finalDNA.KeyValues;

            double spikeOrthLength = WeaponDNA.GetKeyValue("spikeOrthLength", from, to, rand.NextPercent(dna.Radius * 1.4d, .1));
            double spikeDiagLength = WeaponDNA.GetKeyValue("spikeDiagLength", from, to, rand.NextPercent(dna.Radius * 1.15d, .05));
            double ballRadius      = dna.Radius;

            double spikeOrthRadius = WeaponDNA.GetKeyValue("spikeOrthRadius", from, to, rand.NextPercent(dna.Radius * .5, .1));
            double spikeDiagRadius = WeaponDNA.GetKeyValue("spikeDiagRadius", from, to, rand.NextPercent(dna.Radius * .5, .1));

            double ballRadiusDepth = ballRadius * .1;       //this is how far the triangle parts of the ball sink in

            var color = WeaponMaterialCache.GetComposite(dna.MaterialsForCustomizable);

            finalDNA.MaterialsForCustomizable = color.Item4;

            GeometryModel3D geometry;

            #region Ball - outer

            geometry = new GeometryModel3D();

            geometry.Material     = color.Item1;
            geometry.BackMaterial = color.Item1;

            Rhombicuboctahedron ball = UtilityWPF.GetRhombicuboctahedron(ballRadius * 2, ballRadius * 2, ballRadius * 2);

            TriangleIndexed[] usedTriangles = UtilityCore.Iterate(
                ball.Squares_Orth.SelectMany(o => o),
                ball.Squares_Diag.SelectMany(o => o),
                GetModel_Composite_SquareSides(ball, ballRadiusDepth * 1.1)       // this builds plates that go toward the center of the ball, because the triangles are indented
                ).ToArray();

            geometry.Geometry = UtilityWPF.GetMeshFromTriangles_IndependentFaces(usedTriangles);

            retVal.Children.Add(geometry);

            #endregion
            #region Ball - inner

            geometry = new GeometryModel3D();

            geometry.Material     = color.Item2;
            geometry.BackMaterial = color.Item2;

            // Use the triangles, but suck them in a bit
            geometry.Geometry = UtilityWPF.GetMeshFromTriangles_IndependentFaces(GetModel_Composite_IndentedTriangles(ball, ballRadiusDepth));

            retVal.Children.Add(geometry);

            #endregion

            #region Spikes

            var spikeLocations = UtilityCore.Iterate(ball.SquarePolys_Orth.Select(o => Tuple.Create(true, o)), ball.SquarePolys_Diag.Select(o => Tuple.Create(false, o))).
                                 Select(o => new { IsOrth = o.Item1, Center = Math3D.GetCenter(o.Item2.Select(p => ball.AllPoints[p])).ToVector() });

            // Put a spike through the center of each square
            foreach (var spikeLocation in spikeLocations)
            {
                geometry = new GeometryModel3D();

                geometry.Material     = color.Item3;
                geometry.BackMaterial = color.Item3;

                RotateTransform3D transform = new RotateTransform3D(new QuaternionRotation3D(Math3D.GetRotation(new Vector3D(0, 0, 1), spikeLocation.Center)));       // the tube builds along z

                List <TubeRingBase> rings = new List <TubeRingBase>();

                double spikeLengthActual = spikeLocation.IsOrth ? spikeOrthLength : spikeDiagLength;
                double spikeRadiusActual = spikeLocation.IsOrth ? spikeOrthRadius : spikeDiagRadius;

                rings.Add(new TubeRingRegularPolygon(0, false, spikeRadiusActual, spikeRadiusActual, false));
                rings.Add(new TubeRingPoint(spikeLengthActual, false));

                geometry.Geometry = UtilityWPF.GetMultiRingedTube(9, rings, true, false, transform);

                retVal.Children.Add(geometry);
            }

            #endregion

            return(retVal);
        }
Beispiel #28
0
        private void btnPlaceNet_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                #region Cast Ints

                int neuronCount;
                if (!int.TryParse(txtNumNeurons.Text, out neuronCount))
                {
                    MessageBox.Show("Couldn't cast neuron count as an integer", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                int inputLinkCount;
                if (!int.TryParse(txtNumLinksInput.Text, out inputLinkCount))
                {
                    MessageBox.Show("Couldn't cast number of input links as an integer", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                int internalLinkCount;
                if (!int.TryParse(txtNumLinksInternal.Text, out internalLinkCount))
                {
                    MessageBox.Show("Couldn't cast number of internal links as an integer", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                int outputLinkCount;
                if (!int.TryParse(txtNumLinksOutput.Text, out outputLinkCount))
                {
                    MessageBox.Show("Couldn't cast number of output links as an integer", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                #endregion

                #region Wipe Existing

                if (_neurons != null)
                {
                    foreach (Neuron node in _neurons)
                    {
                        _viewport.Children.Remove(node.Visual);
                    }
                }

                if (_links != null)
                {
                    foreach (NeuronLink link in _links)
                    {
                        _viewport.Children.Remove(link.Visual);
                    }
                }

                _neurons   = null;
                _links     = null;
                _backLinks = null;

                #endregion

                // Make sure the inputs/outputs are placed
                if (_inputs == null)
                {
                    btnPlaceIO_Click(this, new RoutedEventArgs());
                }

                #region Calculate Positions

                Point3D[] positions = null;
                Point3D[] existing  = UtilityCore.Iterate(_inputs, _outputs).Select(o => o.Position).ToArray();

                if (radInsideBall.IsChecked.Value)
                {
                    positions = GetSpherePlacement(neuronCount, RADIUS_INNER, FACTOR_NEURON, radRandom.IsChecked.Value ? existing : null);
                }
                else if (radInsideShell.IsChecked.Value)
                {
                    positions = GetShellPlacement(neuronCount, RADIUS_INNER, FACTOR_NEURON);
                }
                else if (radOutsideBall.IsChecked.Value)
                {
                    positions = GetSpherePlacement(neuronCount, RADIUS_OUTER, FACTOR_NEURON, existing);
                }
                else if (radOutsideShell.IsChecked.Value)
                {
                    positions = GetShellPlacement(neuronCount, RADIUS_OUTER, FACTOR_NEURON);
                }
                else
                {
                    MessageBox.Show("Unknown neuron placement type", this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                #endregion

                _neurons = BuildNeurons(positions);

                if (radLinkRandom.IsChecked.Value)
                {
                    _links = BuildLinksRandom(_neurons, _inputs, _outputs, inputLinkCount, internalLinkCount, outputLinkCount);
                }
                else if (radLinkProximity.IsChecked.Value)
                {
                    MessageBox.Show("finish proximity placement", this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
                else
                {
                    MessageBox.Show("Unknown link placement type", this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }