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); }
private void PhysicsBody_ApplyForceAndTorque(object sender, BodyApplyForceAndTorqueArgs e) { //TODO: Gravity (see Asteroid Field) #region Boundry Force Vector3D position = e.Body.Position.ToVector(); //NOTE: Even though the boundry is square, this turns it into a circle (so the corners of the map are even harder //to get to - which is good, the map feel circular) if (position.LengthSquared > _boundryForceBeginSquared) { // See how far into the boundry the item is double distaceInto = position.Length - _boundryForceBegin; // I want an acceleration of zero when distFromMax is 1, but an accel of 10 when it's boundryMax //NOTE: _boundryMax.X is to the edge of the box. If they are in the corner the distance will be greater, so the accel will be greater double accel = UtilityCore.GetScaledValue(0, 30, 0, _boundryWidth, distaceInto); // Apply a force toward the center Vector3D force = position.ToUnit(); force *= accel * e.Body.Mass * -1d; e.Body.AddForce(force); } #endregion }
private void PropsChangedSprtExisting() { switch (_type) { case ShipTypeQual.None: break; case ShipTypeQual.Ball: _ship.Ball.Radius = _shipSize; _ship.Ball.Mass = UtilityCore.GetMassForRadius(_shipSize, 1d); _thrustForce = GetThrustForce(_ship.Ball.Mass); _torqueballLeftRightThrusterForce = _thrustForce; break; case ShipTypeQual.SolidBall: _ship.Ball.Radius = _shipSize; _ship.Ball.Mass = UtilityCore.GetMassForRadius(_shipSize, 1d); _thrustForce = GetThrustForce(_ship.Ball.Mass); _torqueballLeftRightThrusterForce = GetLeftRightThrusterMagnitude(_ship.TorqueBall.InertialTensorBody); break; default: throw new ApplicationException("Unknown ShipTypeQual: " + _type.ToString()); } }
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)); }
//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]); } } }
private void SaveBell3Map_Click(object sender, RoutedEventArgs e) { try { Point[] points = GetBellPoints(txtBell3.Text); if (points == null) { MessageBox.Show("Invalid control points", this.Title, MessageBoxButton.OK, MessageBoxImage.Warning); return; } //C:\Users\<username>\AppData\Roaming\Asteroid Miner\NonlinearRandom\ string foldername = UtilityCore.GetOptionsFolder(); foldername = System.IO.Path.Combine(foldername, FOLDER); Directory.CreateDirectory(foldername); string filename = DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss.fff - "); filename += BELL3; filename = System.IO.Path.Combine(foldername, filename); UtilityCore.SerializeToFile(filename, points); RebuildBell3Combo(); } catch (Exception ex) { MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error); } }
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(); } }
public static double[] GetExpectedOutput_OLD1(Tuple <TrackedItemBase, Point, Vector> prevPos, Tuple <TrackedItemBase, Point, Vector> currentPos, TrackedItemHarness harness, EvaluatorArgs evaluatorArgs) { // This is too complicated double[] retVal = null; if (prevPos == null) { //If prev is null, then output should be zeros retVal = GetExpectedOutput_Zeros(harness); } else if (currentPos == null || currentPos.Item1.Token != prevPos.Item1.Token) { //If prev and current tokens don't match, then???? //desiredOutput = GetError_Unmatched(outputArr); // might not even want to add to the error } else if (harness.Time - prevPos.Item1.CreateTime < evaluatorArgs.NewItem_Duration_Multiplier * evaluatorArgs.Delay_Seconds) { //If prev is new, then error size gradient double aliveTime = harness.Time - prevPos.Item1.CreateTime; // figure out how long it's been alive double percent = aliveTime / (evaluatorArgs.NewItem_Duration_Multiplier * evaluatorArgs.Delay_Seconds); // get the percent of the range percent = UtilityCore.Cap(1 - percent, 0, 1); // invert the percent so that an old percent of zero will now be the full error mult double newItemMult = percent * evaluatorArgs.NewItem_ErrorMultiplier; retVal = GetExpectedOutput_Matched(currentPos, harness, evaluatorArgs, newItemMult); } else { //otherwise, standard scoring retVal = GetExpectedOutput_Matched(currentPos, harness, evaluatorArgs); } return(retVal); }
public static void SaveShip(ShipDNA ship) { // Make sure the folder exists string foldername = System.IO.Path.Combine(UtilityCore.GetOptionsFolder(), SHIPFOLDER); if (!Directory.Exists(foldername)) { Directory.CreateDirectory(foldername); } int infiniteLoopDetector = 0; while (true) { char[] illegalChars = System.IO.Path.GetInvalidFileNameChars(); string filename = new string(ship.ShipName.Select(o => illegalChars.Contains(o) ? '_' : o).ToArray()); filename = DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss.fff") + " - " + filename + ".xml"; filename = System.IO.Path.Combine(foldername, filename); try { UtilityCore.SerializeToFile(filename, ship); break; } catch (IOException ex) { infiniteLoopDetector++; if (infiniteLoopDetector > 100) { throw new ApplicationException("Couldn't create the file\r\n" + filename, ex); } } } }
private void Window_Loaded(object sender, RoutedEventArgs e) { try { HopfieldNetworkOptions options = UtilityCore.ReadOptions <HopfieldNetworkOptions>(FILE); if (options != null && options.ImageFolders != null && options.ImageFolders.Length > 0) { foreach (string folder in options.ImageFolders) { if (AddFolder(folder)) { _imageFolders.Add(folder); } } ResetTraining(); } else { expanderFolder.IsExpanded = true; } SetInkColor(); } catch (Exception ex) { MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error); } }
public double[][] Recognize(double[] item) { if (_storedItems.Count == 0) { return(null); } double[] retVal = ConvertToLocal(item, _midValue); bool hadChange = false; do { hadChange = false; foreach (int index in UtilityCore.RandomRange(0, item.Length)) { double newValue = GetValueAtIndex(index, retVal, _weights); if (newValue != retVal[index]) { hadChange = true; retVal[index] = newValue; } } } while (hadChange); retVal = ConvertToExternal(retVal, _lowValue, _highValue); return(new[] { retVal }); }
/// <summary> /// This will save the state of a game/tester /// </summary> /// <remarks> /// Folder Structure: /// baseFolder /// "C:\Users\charlie.rix\AppData\Roaming\Asteroid Miner" /// Only one file per tester here. Each file is "testername Options.xml" /// Each tester gets one child folder off of base /// /// Game Folder /// "C:\Users\charlie.rix\AppData\Roaming\Asteroid Miner\Flying Beans" /// This folder holds custom files for this game. It will also hold session subfolders (each session would be a different state) /// /// Session Folders /// "C:\Users\charlie.rix\AppData\Roaming\Asteroid Miner\Flying Beans\Session 2016-10-09 09.11.35.247" /// /// Save Folders /// "C:\Users\charlie.rix\AppData\Roaming\Asteroid Miner\Flying Beans\Session 2016-10-09 09.11.35.247\Save 2016-10-09 09.11.35.247 (auto)" /// This is where all the save folders go. Each save folder is for the parent session (there are many because backups should occur often) /// When saving, it shouldn't overwrite an existing save, it should create a new save folder, then delete old ones as needed /// If zipped is true, this will be a zip file instead of a folder /// </remarks> /// <param name="baseFolder"> /// Use UtilityCore.GetOptionsFolder() /// "C:\Users\charlie.rix\AppData\Roaming\Asteroid Miner" /// </param> /// <param name="name"> /// This is the name of the tester/game /// </param> /// <param name="session"> /// This is the class that goes in the root folder /// NOTE: This method will set the LatestSessionFolder property /// </param> /// <param name="saveFiles"> /// A set of files to put into the save folder (or zip file) /// Item1=Name of file (this method will ensure it ends in .xml) /// Item2=Object to serialize /// </param> /// <param name="zipped"> /// This only affects the leaf save folder /// True: The save folder will be a zip file instead /// False: The save folder will be a standard folder containing files /// </param> public static void Save(string baseFolder, string name, ISessionOptions session, IEnumerable <Tuple <string, object> > saveFiles, bool zipped) { if (string.IsNullOrEmpty(session.LatestSessionFolder) || !Directory.Exists(session.LatestSessionFolder)) { session.LatestSessionFolder = GetNewSessionFolderName(baseFolder, name); } #region root session file string rootSessionFilename = GetRootOptionsFilename(baseFolder, name); UtilityCore.SerializeToFile(rootSessionFilename, session); #endregion // Session Folder //NOTE: This will also create the game folder if it doesn't exist Directory.CreateDirectory(session.LatestSessionFolder); // Save Folder (or zip file) string saveFolder = GetNewSaveFolderName(session.LatestSessionFolder); if (zipped) { // Just tack on a .zip to the save folder name to turn it into a zip filename throw new ApplicationException("finish saving to zip file"); } else { Save_Folder(saveFolder, saveFiles); } }
/// <summary> /// This fires in an arbitrary thread. It looks at what's in the map, and builds instructions that will be run in the main thread /// (adds/removes) /// </summary> public void Update_AnyThread(double elapsedTime) { MapOctree snapshot = _map.LatestSnapshot; if (snapshot == null) { return; } IEnumerable <MapObjectInfo> allItems = snapshot.GetItems(); //_map.GetAllItems(true) //TODO: May want to use this to get disposed items // Look for too few/many ChangeInstruction[] asteroids = ExamineAsteroids(allItems, _boundry); ChangeInstruction[] minerals = ExamineMinerals(allItems, _boundry, _mineralTypesByValue); // Store these instructions for the main thread to do if (asteroids != null || minerals != null) { ChangeInstruction[] instructions = UtilityCore.ArrayAdd(asteroids, minerals); if (instructions.Length > MAXCHANGES) { instructions = UtilityCore.RandomOrder(instructions, MAXCHANGES).ToArray(); } _instructions = instructions; } }
private void UpdateNeurons_progressiveRadius(Vector3D gravity, double magnitude) { if (Math3D.IsNearZero(gravity)) { // There is no gravity to report for (int cntr = 0; cntr < _neurons.Length; cntr++) { _neurons[cntr].Value = 0d; } return; } for (int cntr = 0; cntr < _neurons.Length; cntr++) { if (_neurons[cntr].PositionUnit == null) { // This neuron is sitting at 0,0,0 _neurons[cntr].Value = magnitude; } else { // Scale minDot double radiusPercent = _neurons[cntr].PositionLength / _neuronMaxRadius; _neurons[cntr].Value = UtilityCore.GetScaledValue_Capped(0d, 1d, 0d, 1d, 1d - radiusPercent); } } }
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); }
private void trkVectorFieldForce_Scroll(object sender, EventArgs e) { const double MINFORCE = 1; const double MAXFORCE = 750; _vectorField.Strength = UtilityCore.GetScaledValue(MINFORCE, MAXFORCE, trkVectorFieldForce.Minimum, trkVectorFieldForce.Maximum, trkVectorFieldForce.Value); }
/// <summary> /// This returns a random ball, with some optional fixed values /// </summary> public static WeaponSpikeBallDNA GetRandomDNA(WeaponSpikeBallMaterial?material = null, double?radius = null) { WeaponSpikeBallDNA retVal = new WeaponSpikeBallDNA(); Random rand = StaticRandom.GetRandomForThread(); // Radius if (radius != null) { retVal.Radius = radius.Value; } else { retVal.Radius = rand.NextDouble(.2, .5); } // Material if (material == null) { retVal.Material = UtilityCore.GetRandomEnum <WeaponSpikeBallMaterial>(); } else { retVal.Material = material.Value; } return(retVal); }
private void trkGravityForce_Scroll(object sender, EventArgs e) { const double MINGRAVITY = 0d; const double MAXGRAVITY = 50d; _gravityMultiplier = UtilityCore.GetScaledValue(MINGRAVITY, MAXGRAVITY, trkGravityForce.Minimum, trkGravityForce.Maximum, trkGravityForce.Value); }
private void RebuildBell3Combo() { string foldername = UtilityCore.GetOptionsFolder(); foldername = System.IO.Path.Combine(foldername, FOLDER); string[] filenames = Directory.GetFiles(foldername, "*" + BELL3); try { _isProgramaticallyChanging = true; cboBell3.Items.Clear(); foreach (string filename in filenames) { Point[] points = UtilityCore.DeserializeFromFile <Point[]>(filename); string pointText = string.Join("\r\n", points.Select(o => string.Format("{0} {1}", o.X, o.Y))); TextBlock text = new TextBlock() { Text = string.Format("preset {0}", cboBell3.Items.Count + 1), Tag = pointText, }; cboBell3.Items.Add(text); } } finally { _isProgramaticallyChanging = false; } }
public void Update_MULTISAME() { //const double SIZE = 800; const double SIZE = 3000; const double HALF = SIZE / 2; if (_visuals1 == null) { #region Create _visuals1 = new Tuple <StarfieldVisual1, double> [5]; for (int cntr = 0; cntr < _visuals1.Length; cntr++) { double starSizeMult = UtilityCore.GetScaledValue(.7, 1.1, 0, _visuals1.Length, cntr); double slideSpeed = UtilityCore.GetScaledValue(.75, 5, 0, _visuals1.Length, cntr); _visuals1[cntr] = Tuple.Create(new StarfieldVisual1(SIZE, 10, _visuals1.Length, starSizeMult), slideSpeed); Canvas.SetLeft(_visuals1[cntr].Item1, (_canvas.ActualWidth / 2) - HALF); Canvas.SetTop(_visuals1[cntr].Item1, (_canvas.ActualHeight / 2) - HALF); // This kills the framerate //_visuals[cntr].Item1.Effect = new BlurEffect() //{ // Radius = 2, //}; _canvas.Children.Add(_visuals1[cntr].Item1); } #endregion } // Figure out angle Vector3D desiredUp = new Vector3D(0, -1, 0); Vector3D up = _player.Ship.PhysicsBody.DirectionToWorld(desiredUp); double angle = Vector.AngleBetween(desiredUp.ToVector2D(), up.ToVector2D()); for (int cntr = 0; cntr < _visuals1.Length; cntr++) { TransformGroup transform = new TransformGroup(); #region Translate Point3D position = _player.Ship.PositionWorld; transform.Children.Add(new TranslateTransform(-position.X * _visuals1[cntr].Item2, position.Y * _visuals1[cntr].Item2)); // don't need to negate Y, because it's already backward #endregion #region Rotate transform.Children.Add(new RotateTransform(angle, HALF, HALF)); #endregion _visuals1[cntr].Item1.RenderTransform = transform; } }
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); }
private void GetRatiosMass(out double radius, out double height, out double mass, CollisionShapeType shape) { #region Ratios if (chkRandomRatios.IsChecked.Value) { height = UtilityCore.GetScaledValue(MINRATIO, MAXRATIO, 0d, 1d, _rand.NextDouble()); switch (shape) { case CollisionShapeType.Cone: case CollisionShapeType.Capsule: // height must be greater or equal to diameter radius = UtilityCore.GetScaledValue(MINRATIO * 2d, height, 0d, 1d, _rand.NextDouble()); break; default: radius = UtilityCore.GetScaledValue(MINRATIO * 2d, MAXRATIO, 0d, 1d, _rand.NextDouble()); break; } } else { //NOTE: I'm not going to error out if they have invalid values - this is a tester, and I want to test what happens radius = UtilityCore.GetScaledValue(MINRATIO * 2d, MAXRATIO * 2d, trkX.Minimum, trkX.Maximum, trkX.Value); radius /= 2d; // the slider is diameter height = UtilityCore.GetScaledValue(MINRATIO * 2d, MAXRATIO * 2d, trkY.Minimum, trkY.Maximum, trkY.Value); } #endregion switch (shape) { case CollisionShapeType.Capsule: // This looks like a pill. I'm guessing since the height is capped to the diameter that the rounded parts cut into the height // I'm also guessing that the rounded parts are spherical double cylinderHeight = height - (2d * radius); mass = Math.PI * radius * radius * cylinderHeight; // cylinder portion mass += (4d / 3d) * Math.PI * radius * radius * radius; // end caps (adds up to a sphere) break; case CollisionShapeType.Cylinder: mass = Math.PI * radius * radius * height; break; case CollisionShapeType.Cone: mass = (1d / 3d) * Math.PI * radius * radius * height; break; case CollisionShapeType.ChamferCylinder: mass = Math.PI * radius * radius * height; // I can't find any examples of what this looks like when the height is large. It looks like it turns into a capsule if the height exceeds diameter? break; default: throw new ApplicationException("Unexpected CollisionShapeType: " + shape.ToString()); } // If I try to be realistic, then it's boring, so I'll scale the result. (density shrinks a bit as things get larger) mass = UtilityCore.GetScaledValue(MINMASS, MAXMASS, Math.Pow(MINRATIO, 3), Math.Pow(MAXRATIO, 3), mass); }
public void ResetLabels(int[] trueValues) { if (trueValues == null) { trueValues = new int[0]; } if (trueValues.Any(o => o > 7)) { throw new ArgumentOutOfRangeException(""); } while (_viewport.Children.Count > _viewportOffset_Init) { _viewport.Children.RemoveAt(_viewport.Children.Count - 1); } VectorND center = new VectorND(.5, .5, .5); // Add the numbers for (int cntr = 0; cntr < 8; cntr++) { VectorND position = new VectorND(UtilityCore.ConvertToBase2(cntr, 3).Select(o => o ? 1d : 0d).ToArray()); position = position - center; position = center + (position * 1.2); Color color = trueValues.Contains(cntr) ? TrueColor : FalseColor; AddText3D(cntr.ToString(), position.ToPoint3D(), position.ToVector3D().ToUnit(), .1, color, false); } _viewportOffset_Labels = _viewport.Children.Count; }
private void btnSaveSession_Click(object sender, RoutedEventArgs e) { try { EncogOCR_Session session = new EncogOCR_Session() { ImageSize = _pixels, Sketches = _prevSketches.ToArray(), }; //C:\Users\<username>\AppData\Roaming\Asteroid Miner\EncogOCR\ string foldername = UtilityCore.GetOptionsFolder(); foldername = System.IO.Path.Combine(foldername, FOLDER); Directory.CreateDirectory(foldername); string filename = DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss.fff - "); filename += cboSession.Text + ".xml"; //TODO: convert illegal chars filename = System.IO.Path.Combine(foldername, filename); UtilityCore.SerializeToFile(filename, session); LoadSessionsCombobox(); } catch (Exception ex) { MessageBox.Show(ex.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Error); } }
private static Tuple <string, ShipDNA>[] ScanFolder(string foldername, CancellationToken cancel) { //NOTE: This method is running in an arbitrary thread try { List <Tuple <string, ShipDNA> > retVal = new List <Tuple <string, ShipDNA> >(); foreach (string filename in Directory.EnumerateFiles(foldername, "*.xml")) { if (cancel.IsCancellationRequested) { return(null); } try { // Try to deserialize this file as shipdna ShipDNA dna = UtilityCore.DeserializeFromFile <ShipDNA>(filename); // Success, add it retVal.Add(Tuple.Create(filename, dna)); } catch (Exception) { } } return(retVal.ToArray()); } catch (Exception) { return(null); } }
/// <summary> /// This should only be called if _newBallProps.SizeMode is Draw /// </summary> private void ResizeDrawingObject() { // Find the vector from the mousedown point to the current point MyVector fromToLine = _curMousePoint - _mouseDownPoint; // Adjust the radius and mass switch (_mode) { case AddingMode.AddBall: case AddingMode.AddSolidBall: double newValue = fromToLine.GetMagnitude(); if (newValue < MINRADIUS) { newValue = MINRADIUS; } _drawingBall.Radius = newValue; _drawingBall.Mass = UtilityCore.GetMassForRadius(newValue, 1d); break; //case AddingMode.AddRigidBody: // //TODO: I will need to pull all the point masses out proportionatly, as well as change their masses // break; default: throw new ApplicationException("Unknown AddingMode: " + _mode.ToString()); } }
private void trkSize_Scroll(object sender, EventArgs e) { _sizeActual = UtilityCore.GetScaledValue(100, _sizeMax, trkSize.Minimum, trkSize.Maximum, trkSize.Value); toolTip1.SetToolTip(trkSize, _sizeActual.ToString()); bool changeOffset = false; // Apply to tractor beams foreach (TractorBeamCone tractor in _shipController.TractorBeams) { if (cboType.Text == TYPE_DISTANTCIRCLE || cboType.Text == TYPE_DISTANTCIRCLESOFT) { changeOffset = true; tractor.MaxDistance = _sizeActual / 3d; } else { tractor.MaxDistance = _sizeActual; } } // Distant circle needs the offset changed if (changeOffset) { ShipController_RecalcTractorBeamOffsets(this, new EventArgs()); } }
private void StoreAngularVelocity(Ball ball) { if (!(ball is TorqueBall)) { return; } MyVector angularVelocity; #region Calculate Angular Velocity switch (_newBallProps.AngularVelocityMode) { case BallProps.AngularVelocityModes.Fixed: angularVelocity = new MyVector(0, 0, _newBallProps.AngularVelocityIfFixed); break; case BallProps.AngularVelocityModes.Random: angularVelocity = new MyVector(0, 0, UtilityCore.GetScaledValue(_newBallProps.MinRandAngularVelocity, _newBallProps.MaxRandAngularVelocity, 0, 1, _rand.NextDouble())); break; default: throw new ApplicationException("Unknown BallProps.AngularVelocityModes: " + _newBallProps.AngularVelocityMode.ToString()); } #endregion // Apply Angular Velocity ((TorqueBall)ball).SetAngularVelocity(angularVelocity); }
private static int[] GetNeuronPositionsInitial_InitialPlateBreakdown(int count, int numPlates) { int[] retVal = new int[numPlates]; int average = count / numPlates; int remaining = count; for (int cntr = 0; cntr < numPlates; cntr++) { // Figure out how many to make if (remaining == 0) { retVal[cntr] = 0; continue; } retVal[cntr] = average; if (remaining % numPlates > 0) { // Count isn't evenly distributable by numPlates, and there's enough room for a remainder, so give it to this one retVal[cntr]++; } remaining -= retVal[cntr]; } // Some of the plates may have remainders, and the above loop always puts them in the first plates, so shuffle it retVal = UtilityCore.RandomRange(0, numPlates).Select(o => retVal[o]).ToArray(); return(retVal); }
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); }