public void TestDictance() { Position pos1 = new Position(0, 0); Position pos2 = new Position(2, 4); Assert.AreEqual(20, DistanceHelper.FindDistance(pos1, pos2)); }
public void TestPointToPoint(object row1, object col1, object row2, object col2, double expectedValue) { //assign var pointA = new MeasureViewModel(); if (row1 != null) { pointA.Row1 = new HTuple(row1); } if (col1 != null) { pointA.Col1 = new HTuple(col1); } pointA.GeoType = MeasureType.Point; var pointB = new MeasureViewModel(); if (row2 != null) { pointB.Row1 = new HTuple(row2); } if (col2 != null) { pointB.Col1 = new HTuple(col2); } pointB.GeoType = MeasureType.Point; //act double distance = DistanceHelper.PointToPoint(pointA, pointB); //assert Assert.True(distance >= expectedValue); }
public static List <String> Searching(Dictionary <String, List <String> > dicVisualWords, List <Dot_RGB> listDot, Size input) { if (listDot == null || listDot.Count == 0) { return(null); } float cellWidth = input.Width / (float)ConfigPCT.PCT_NUMBER_OF_HORIZONTAL_REGION; float cellHeight = input.Height / (float)ConfigPCT.PCT_NUMBER_OF_VERTICAL_REGION; Dot_RGB dot = listDot[0]; int xIndex = (int)(listDot[0].location.X / cellWidth); int yIndex = (int)(listDot[0].location.Y / cellHeight); List <Color> colorVisualWord = ColorHelper.GenerateColorVisualWord_Rgb(); Color color = colorVisualWord[DistanceHelper.ColorKNN_RGB(dot.color, colorVisualWord)]; String key = color.R + "_" + color.G + "_" + color.B + "_" + xIndex + "_" + yIndex; if (dicVisualWords.ContainsKey(key)) { return(dicVisualWords[key]); } return(null); }
void panel1_Paint(object sender, PaintEventArgs e) { // Doc PCT Data PCTFeature_RGB data = PCTReadingFeature.ReadingFeatureFromFile_RGB(currentPctFilePath); _bitmap = ImageHelper.GetBitmapFromFile(currentImgFilePath); // Load data panel1.Width = data.Width * 2 + 30; panel1.Height = data.Height * 2 + 15; panel2.Location = new Point(5, panel1.Location.Y + panel1.Height + 25); Graphics g = e.Graphics; g.DrawImage(_bitmap, new Point(0, 0)); g.DrawImage(_bitmap, new Point(15 + data.Width, 15 + data.Height)); g.DrawImage(_bitmap, new Point(0, 15 + data.Height)); foreach (Dot_RGB dot in data.ListColorPoint) { // draw pct dots DrawDotWithBorder(g, new Dot_RGB(new Point(dot.location.X, dot.location.Y + data.Height + 15), dot.radius, dot.color)); // draw visual dots Color c = listVisualWords[DistanceHelper.ColorKNN(dot.color, listVisualWords, currentColorSpaceForFormula, currentDistanceFormulaRGB, currentDistanceFormulaLab)]; if (dot.radius >= 10) { DrawDotWithBorder(g, new Dot_RGB(new Point(dot.location.X + data.Width + 15, dot.location.Y + data.Height + 15), dot.radius, c)); } } }
public MeasureResult Action() { #region 輸出結果 DistanceResult mResult = null; #endregion var fMidLine = new SDMS_FirstFingerMidLine(); var image = new HImage(ho_Image); fMidLine.Initialize(image, hv_AllModelRow, hv_AllModelColumn, hv_AllModelAngle); var fMidLineModel = fMidLine.GetMidLine() as IMeasureGeoModel; var sMidLine = new SecondFingerMidLine(); sMidLine.Initialize(image, hv_AllModelRow, hv_AllModelColumn, hv_AllModelAngle); var sMidLineModel = sMidLine.GetMidLine() as IMeasureGeoModel; var distance = DistanceHelper.LineToLine(fMidLineModel, sMidLineModel); mResult = new DistanceResult() { FirstRowBegin = fMidLineModel.Row1, FirstColBegin = fMidLineModel.Col1, FirstRowEnd = fMidLineModel.Row2, FirstColEnd = fMidLineModel.Col2, SecondRowBegin = sMidLineModel.Row1, SecondColBegin = sMidLineModel.Col1, SecondRowEnd = sMidLineModel.Row2, SecondColEnd = sMidLineModel.Col2, Angle = hv_AllModelAngle, Direction = LineDirection.Horizontal, Distance = distance, }; return(mResult); }
public ActionResult <PlaceResponse> GetPlace(int zipcode) { PlaceResponse result = null; var place = _context.Places .Where(place => place.Zipcode == zipcode) .FirstOrDefault(); // if entered zipcode is valid, then calculate the distance from mindgrub if (place != null) { result = new PlaceResponse(); result.City = place.City; result.State = place.State; result.Zipcode = place.Zipcode; result.Longitude = place.Longitude; result.Latitude = place.Latitude; // get latitude and longitute of mindgrub's location var mindGrub = _context.Places .Where(place => place.Zipcode == MINDGRUB_ZIP) .FirstOrDefault(); result.DistanceFromMindGrub = DistanceHelper.haversine(mindGrub.Latitude, mindGrub.Longitude, place.Latitude, place.Longitude); } return(result); }
public static Individual[] GetRandomPopulation() { Individual[] population = new Individual[ENVIRONMENT.PopulationSize]; for (int i = 0; i < ENVIRONMENT.PopulationSize; i++) { ENVIRONMENT.cities = DataReader.ReadData(); population[i] = new Individual(); population[i].Order = new int[ENVIRONMENT.IndividualSize]; population[i].Cities = new City[ENVIRONMENT.IndividualSize]; int currentlyPossibleSize = ENVIRONMENT.IndividualSize; population[i].RemainingCities = ENVIRONMENT.cities; for (int j = 0; j < ENVIRONMENT.IndividualSize; j++) { City randomCity = population[i].GetRandomCity(currentlyPossibleSize); //wylosuj jedno miasto population[i].Cities[j] = randomCity; //zapisz jego Index w Individual.Order population[i].Order[j] = randomCity.Index; //dodaj odległość do całkowitego dystansu population[i].TotalDistance += DistanceHelper.FindDistance(randomCity, j > 0 ? population[i].Cities[j - 1] : randomCity); //usuń to miasto z możliwych do wylosowania population[i].RemoveFromPossible(population[i].RemainingCities, randomCity); //zmniejsz tablicę możliwości currentlyPossibleSize--; } population[i].TotalDistance += DistanceHelper.FindDistance(population[i].Cities[0], population[i].Cities[ENVIRONMENT.IndividualSize - 1]); Console.WriteLine(population[i].ToString()); } return(population); }
public IEnumerable <SongDistance> GetNearSongs(double latitude, double longitude, int styleId) { var songsFromAmbassadors = _context.Historics .Include(x => x.User) .Include(x => x.Song).ThenInclude(x => x.Artist) .Where(x => x.LikeType == LikeType.Ambassador && x.Song.StyleSongs.Any(y => y.StyleID == styleId)) .Select(x => new SongDistance { Song = x.Song, Distance = Math.Round(DistanceHelper.CalculateDistance(latitude, longitude, x.User.LastGeoCoordinate.Latitude, x.User.LastGeoCoordinate.Longitude), 1) }) .ToList(); var nearSongs = _context.Songs .Include(x => x.Artist).ThenInclude(x => x.GeoCoordinate) .Include(x => x.Historics) .Include(x => x.StyleSongs) .Where(x => x.StyleSongs.Any(y => y.StyleID == styleId)) .Select(x => new SongDistance { Song = x, Distance = Math.Round(DistanceHelper.CalculateDistance(latitude, longitude, x.Artist.GeoCoordinate.Latitude, x.Artist.GeoCoordinate.Longitude), 1) }) .ToList(); var result = nearSongs .Concat(songsFromAmbassadors) .OrderBy(x => x.Distance) .GroupBy(x => x.Song.ID) .Select(g => g.First()) .ToList(); return(result); }
private StoreSDTO MongoToDto3(StoreMgDTO entity, decimal lat, decimal lon) { StoreSDTO store = MongoToDto(entity); store.Distance = (decimal)DistanceHelper.GetGreatCircleDistance((double)lat, (double)lon, entity.Location[1], entity.Location[0]); return(store); }
public void TestCaculateDistance(string testData) { //Assign var xDoc = XDocument.Load(testData); var testCases = xDoc.Root.Elements("Case") .Select(p => new { Models = p.Elements("MeasureModel").Select(model => new MeasureViewModel() { Row1 = model.Element("Row1").Value, Col1 = model.Element("Col1").Value, Row2 = model.Element("Row2").Value, Col2 = model.Element("Col2").Value, GeoType = (MeasureType)Enum.Parse(typeof(MeasureType), model.Element("GeoType").Value), }).ToList(), ExpectedValue = p.Element("Expected").Value }).ToList(); foreach (var testCase in testCases) { var f1 = translateToDoubleValue(testCase.Models[0]); var f2 = translateToDoubleValue(testCase.Models[1]); //Act var result = DistanceHelper.CaculateDistance(f1, f2); //Assert Assert.Equal(testCase.ExpectedValue, result.Distance.ToString()); } }
private async void GetPostion() { try { var locator = CrossGeolocator.Current; locator.DesiredAccuracy = 50; var position = await locator.GetPositionAsync(10000); Debug.WriteLine("Position Status: {0}", position.Timestamp); Debug.WriteLine("Position Latitude: {0}", position.Latitude); Debug.WriteLine("Position Longitude: {0}", position.Longitude); for (int i = 0; viewModel.stops != null && i < viewModel.stops.Count; i++) { viewModel.stops[i].stop_distance = DistanceHelper.DistanceTo(viewModel.stops[i].stop_lat , viewModel.stops[i].stop_lon , position.Latitude , position.Longitude); } } catch (Exception pException) { System.Diagnostics.Debug.WriteLine("GetPostion : " + pException.Message); } finally { GC.Collect(); } }
public void ReturnCorrectDistanceInMiles(double lat1, double lon1, double lat2, double lon2, double expected) { //Arrange var miles = DistanceHelper.GetDistanceInMiles(lat1, lon1, lat2, lon2); Assert.Equal(miles, expected); }
public double Distance(double lat, double lng, XLocation b) { var xloca = new XLocation { Latitude = lat, Longitude = lng }; return(DistanceHelper.DistanceBetween(xloca, b, DistanceType.Kilometers)); }
public async Task <double> GetDistanceBetweenAirportsAsync(string iataFrom, string iataTo) { Airport airportFrom = await _airportService.GetAirportAsync(iataFrom); Airport airportTo = await _airportService.GetAirportAsync(iataTo); return(DistanceHelper.GetDistanceInMiles(airportFrom.Location.Lat, airportFrom.Location.Lon, airportTo.Location.Lat, airportTo.Location.Lon)); }
public override void AppendFeatures(HostnameSplitterResult parsedHostname, GeonamesCityEntity cityEntity, Features features) { if (parsedHostname == null || parsedHostname.DomainInfo?.RegistrableDomain == null || parsedHostname.SubdomainParts == null || parsedHostname.SubdomainParts.Count == 0 || cityEntity == null) { return; } var domain = parsedHostname.DomainInfo.RegistrableDomain; Dictionary <PatternRule, PatternMiningCoordinates> rulesToCoordinates; if (!this.hostnamePatternRules.TryGetValue(domain, out rulesToCoordinates)) { return; } var subdomainParts = parsedHostname.SubdomainParts; if (subdomainParts == null || subdomainParts.Count == 0) { return; } var ruleAtoms = this.miner.CreateRuleAtoms(subdomainParts); if (ruleAtoms == null || ruleAtoms.Count == 0) { return; } var rules = this.miner.GeneratePossibleRules(ruleAtoms); if (rules == null || rules.Count == 0) { return; } foreach (var rule in rules) { PatternMiningCoordinates coordinates; if (rulesToCoordinates.TryGetValue(rule, out coordinates)) { var distance = DistanceHelper.Distance(cityEntity.Latitude, cityEntity.Longitude, coordinates.Latitude, coordinates.Longitude, DistanceUnit.Kilometer); // TODO: Make this configurable // TODO: Distance should vary depending on geohash length? if (distance <= 100) { features[CityFeatureType.HostnamePatternMatch] = true; } } } }
public void AssignRide(Ride r, int curStep) { Ride = r; int distanceToStart = DistanceHelper.GetDistance(Location, r.Start); int stepsAtStart = Math.Max(curStep + distanceToStart, r.EarliestStart); int stepAtEnd = stepsAtStart + DistanceHelper.GetDistance(r.Start, r.End); NextEndTime = stepAtEnd; }
public static Truthness GetLessThanTruthness(long a, long b) { var distance = DistanceHelper.GetDistanceToEquality(a, b); return(new Truthness( a < b ? 1d : 1d / (1.1d + distance), a >= b ? 1d : 1d / (1.1d + distance) )); }
public static Truthness GetEqualityTruthness(double a, double b) { var distance = DistanceHelper.GetDistanceToEquality(a, b); var normalizedDistance = NormalizeValue(distance); return(new Truthness( 1d - normalizedDistance, a != b ? 1d : 0d )); }
public bool DoIHaveToWaitIfILeaveNow(int curStep, Location currentLocation) { var distStart = DistanceHelper.GetDistance(currentLocation, Start); if ((curStep + distStart) >= EarliestStart) { return(true); } return(false); }
public void MillionKilometersToAstronomicalUnits() { double expected = 1; var actual = DistanceHelper.MillionKilometersToAstronomicalUnits(149.59787069); Assert.Equal(expected, actual); actual = DistanceHelper.MillionKilometersToAstronomicalUnits(149.59787069 * 2); Assert.Equal(expected * 2, actual); }
public void AstronomicalUnitsToKilometers() { double expected = 149597870.69; var actual = DistanceHelper.AstronomicalUnitsToKilometers(1); Assert.Equal(expected, actual); actual = DistanceHelper.AstronomicalUnitsToKilometers(2); Assert.Equal(expected * 2, actual); }
static void Main() { DistanceHelper.InitPCT(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new IndexProcessing()); //Application.Run(new ViewPCTImage()); //Application.Run(new ImageIndexing()); Application.Run(new VideoBrowsingForm()); //Application.Run(new EvaluationForm()); }
public void GetDistanceBetweenCoordinates_SimpleTest() { double distanceCalculated = DistanceHelper.GetDistanceBetweenCoordinates(new List <double>() { 0.00D, 0.00D }, new List <double>() { 0.00D, 0.00D }); Assert.AreEqual(0.00D, distanceCalculated); }
public static double GetDistanceToEquality(DateTime a, DateTime b) { if (a.Equals(null)) { throw new ArgumentNullException(nameof(a)); } if (b.Equals(null)) { throw new ArgumentNullException(nameof(b)); } return(DistanceHelper.GetDistanceToEquality(ConvertToTimestamp(a), ConvertToTimestamp(b))); }
public void SetupTheRightDistanceWhenCitiesAreAtMediumDistance() { // Arrange var distanceHelper = new DistanceHelper(); // Act var distance1 = distanceHelper.GetDistance(City.Barcelona, City.London); var distance2 = distanceHelper.GetDistance(City.London, City.Barcelona); // Assert Assert.AreEqual(Distance.Medium, distance1); Assert.AreEqual(Distance.Medium, distance2); }
public Ride GetNextRide(int curStep, Cart cart) { List <Ride> rides = new List <Ride>(); List <RidesByDistance> toSort = new List <RidesByDistance>(); foreach (Ride r in Rides) { if (r.IsCurrentlyPossibleFromLocation(curStep, cart.Location) && !r.IsDone && !r.IsInUse) { rides.Add(r); if (rides.Count > 50) { break; } } } if (!rides.Any()) { return(null); } foreach (Ride ride in rides) { var distStart = DistanceHelper.GetDistance(cart.Location, ride.Start); //if (distStart >= (curStep - ride.EarliestStart)) //{ toSort.Add(new RidesByDistance() { Ride = ride, DistanceFromStart = distStart, DistanceToEnd = DistanceHelper.GetDistance(cart.Location, ride.End), TimeToWait = ride.TimeToWaitIfILeaveNow(curStep, cart.Location) //DistanceToEnd = distStart + ride.StepsRequired }); //} } if (toSort.Count == 0) { return(null); } return(toSort.OrderBy(r => r.DistanceFromStart).ThenBy(cur => cur.TimeToWait).FirstOrDefault().Ride); return(toSort.OrderBy(cur => cur.DistanceFromStart).ThenBy(cur => cur.DistanceToEnd).FirstOrDefault().Ride); return(rides.OrderBy(r => r.DistanceFromStart).ThenBy(r => r.LatestFinish).FirstOrDefault()); return(rides.OrderBy(r => r.LatestStart).FirstOrDefault()); }
public void TestLineToLine(object line1RowBegin, object line1ColBegin, object line1RowEnd, object line1ColEnd , object line2RowBegin, object line2ColBegin, object line2RowEnd, object line2ColEnd , double expectedValue) { //assign var line1Model = new MeasureViewModel(); if (line1RowBegin != null) { line1Model.Row1 = new HTuple(line1RowBegin); } if (line1ColBegin != null) { line1Model.Col1 = new HTuple(line1ColBegin); } if (line1RowEnd != null) { line1Model.Row2 = new HTuple(line1RowEnd); } if (line1ColEnd != null) { line1Model.Col2 = new HTuple(line1ColEnd); } line1Model.GeoType = MeasureType.Line; var line2Model = new MeasureViewModel(); if (line2RowBegin != null) { line2Model.Row1 = new HTuple(line2RowBegin); } if (line2ColBegin != null) { line2Model.Col1 = new HTuple(line2ColBegin); } if (line2RowEnd != null) { line2Model.Row2 = new HTuple(line2RowEnd); } if (line2ColEnd != null) { line2Model.Col2 = new HTuple(line2ColEnd); } line2Model.GeoType = MeasureType.Line; //act var distance = DistanceHelper.LineToLine(line1Model, line2Model); //assert Assert.True(distance >= expectedValue); }
public static List <String> SearchingV3_RGB(Dictionary <string, string> dicVisualWords, List <Dot_RGB> listDotDrawn, Size paperDrawingSize) { if (listDotDrawn == null || listDotDrawn.Count == 0) { return(null); } // init bool SEARCH_MULTI_REGION_FOR_INPUT_DOTS = true; List <Color> colorsVisualWord = ColorHelper.GenerateColorVisualWord_Rgb(); // Get list visual-words match the list input colors >> dicMatched Dictionary <string, List <string> > dicInputColorsMatchedTheIndex = new Dictionary <string, List <string> >(); List <string> listKeyMatchTheInputDot = new List <string>(); foreach (Dot_RGB dot in listDotDrawn) { Color color = colorsVisualWord[DistanceHelper.ColorKNN_RGB(dot.color, colorsVisualWord)]; List <RegionOfFrame> listRegionsDotBelongTo = Utils.RegionOfFrameHelper.GetListRegionDotBelongTo(dot.location, dot.radius, paperDrawingSize.Width, paperDrawingSize.Height); foreach (RegionOfFrame region in listRegionsDotBelongTo) { string key = color.R + "_" + color.G + "_" + color.B + "_" + region.X + "_" + region.Y; //if (!dicInputColorsMatchedTheIndex.ContainsKey(key)) //{ // dicInputColorsMatchedTheIndex.Add(key, dicVisualWords[key]); //} if (!listKeyMatchTheInputDot.Contains(key)) { listKeyMatchTheInputDot.Add(key); } if (!SEARCH_MULTI_REGION_FOR_INPUT_DOTS) { break; } } } // Intersect all item in dicMatched (để lọc bỏ frame trùng ở kết quả) //List<string> listFramesResult = dicInputColorsMatchedTheIndex.ElementAt(0).Value; List <string> listFramesResult = FileManager.GetInstance().GetAllLinesFromFile(dicVisualWords[listKeyMatchTheInputDot[0]].Replace("D:", ConfigCommon.PCT_INDEX_STORAGE[0] + ":")); for (int i = 1; i < listKeyMatchTheInputDot.Count; i++) { //listFramesResult = dicInputColorsMatchedTheIndex.ElementAt(i).Value.Intersect(listFramesResult).ToList(); List <string> listFrame = FileManager.GetInstance().GetAllLinesFromFile(dicVisualWords[listKeyMatchTheInputDot[i]].Replace("D:", ConfigCommon.PCT_INDEX_STORAGE[0] + ":")); listFramesResult = listFramesResult.Intersect(listFrame).ToList(); } return(listFramesResult); }
public static CelestialDrawModel ToCelestialOrbitDrawModel( this CelestialObjectPositionViewModel celestialObjectPosition, CelestialObjectViewModel celestialObject) { return(new CelestialDrawModel( celestialObject.Id, celestialObject.Description, //celestialObjectPosition?.Model.Location.GetOrbitRadius() ?? DistanceHelper.MillionKilometersToAstronomicalUnits(celestialObject.Model.SemiMajorAxis), celestialObjectPosition?.Model.Location, celestialObject.Color, 3, 70)); }
private static void ProcessFrame() { var stopWatch = new Stopwatch(); stopWatch.Start(); Frame = Capture.QueryFrame(); Processor.ProcessImage(Frame); foreach (var found in Processor.FoundTemplates) { var foundRect = found.Sample.Contour.GetBoundsRect(); Console.WriteLine("Distanse: {0}", DistanceHelper.DistanceByRelation(foundRect.Height / CamHeight)); } Console.WriteLine(stopWatch.Elapsed); }
//will Generate the mesh thats under the water //you can Display the mesh, but it will float without it, we just need the data public void GenerateUnderwaterMesh() { //These sore the final data we need to creat the mesh thats underwater underwaterVertices = new List<Vector3> (); underwaterTriangles = new List<int> (); //Loop through all the traingles (3 traingles at a time) int i = 0; while (i < originalTrianglesArray.Length) { //Find the distance from each vertice in the current traingle to the water //Negetive distance means below the water //That position of the vertice in Vector3 format (need to save this position for later) Vector3 vertice_1_pos = originalVerticesArray [originalTrianglesArray [i]]; float? distance1 = DistanceToWater (vertice_1_pos); i++; Vector3 vertice_2_pos = originalVerticesArray [originalTrianglesArray [i]]; float? distance2 = DistanceToWater (vertice_2_pos); i++; Vector3 vertice_3_pos = originalVerticesArray [originalTrianglesArray [i]]; float? distance3 = DistanceToWater (vertice_3_pos); i++; //Continue to the next triangle if all the traingles are above the water if (distance1 > 0f && distance2 > 0f && distance3 > 0f) { continue; } //Continue to the next traingle if there is no water if (distance1 == null || distance2 == null || distance3 == null) { continue; } DistanceHelper distance1OBJ = new DistanceHelper (); DistanceHelper distance2OBJ = new DistanceHelper (); DistanceHelper distance3OBJ = new DistanceHelper (); distance1OBJ.distance = (float)distance1; //from float? to float distance1OBJ.name = "one"; distance1OBJ.verticePos = vertice_1_pos; distance2OBJ.distance = (float)distance2; //from float? to float distance2OBJ.name = "two"; distance2OBJ.verticePos = vertice_2_pos; distance3OBJ.distance = (float)distance3; //from float? to float distance3OBJ.name = "three"; distance3OBJ.verticePos = vertice_3_pos; //Add the objects to a list so we can sort them List<DistanceHelper> allDistancesHelperList = new List<DistanceHelper> (); allDistancesHelperList.Add (distance1OBJ); allDistancesHelperList.Add (distance2OBJ); allDistancesHelperList.Add (distance3OBJ); allDistancesHelperList.Sort (); allDistancesHelperList.Reverse (); //All vertices are underwater if (allDistancesHelperList [0].distance < 0f && allDistancesHelperList [1].distance < 0f && allDistancesHelperList [2].distance < 0f) { //Make sure these coordinates are unsorted AddCoordinateToMesh (distance1OBJ.verticePos); AddCoordinateToMesh (distance2OBJ.verticePos); AddCoordinateToMesh (distance3OBJ.verticePos); } //Just Adds one Coordinate to the new mesh //One Vertice is above the water, the rest is below else if (allDistancesHelperList [0].distance > 0f && allDistancesHelperList [1].distance < 0f && allDistancesHelperList [2].distance < 0f) { //H is always at position 0 Vector3 H = allDistancesHelperList [0].verticePos; //left of H is M //Right of H is L //Find the name of M string M_name = "temp"; if (allDistancesHelperList [0].name == "one") { M_name = "three"; } else if (allDistancesHelperList [0].name == "two") { M_name = "one"; } else { M_name = "two"; } //We also need the hights to the water float h_H = allDistancesHelperList [0].distance; float h_M = 0f; float h_L = 0f; Vector3 M = Vector3.zero; Vector3 L = Vector3.zero; //This means M is at the position 1 in the Lust if (allDistancesHelperList [1].name == M_name) { M = allDistancesHelperList [1].verticePos; L = allDistancesHelperList [2].verticePos; h_M = allDistancesHelperList [1].distance; h_L = allDistancesHelperList [2].distance; } else { M = allDistancesHelperList [2].verticePos; L = allDistancesHelperList [1].verticePos; h_M = allDistancesHelperList [2].distance; h_L = allDistancesHelperList [1].distance; } //Now we can calculate where we should cut the traingle to form 2 new traingles //becuase to the resulting area will always form a square //Point I_M Vector3 MH = H - M; float t_M = -h_M / (h_H - h_M); Vector3 MI_M = t_M * MH; Vector3 I_M = MI_M + M; //Point I_L Vector3 LH = H - L; float t_L = -h_L / (h_H - h_L); Vector3 LI_L = t_L * LH; Vector3 I_L = LI_L + L; //Building the 2 new triangles AddCoordinateToMesh (M); AddCoordinateToMesh (I_M); AddCoordinateToMesh (I_L); AddCoordinateToMesh (M); AddCoordinateToMesh (I_L); AddCoordinateToMesh (L); } //Two vertices are above the water, the other is below else if (allDistancesHelperList [0].distance > 0f && allDistancesHelperList [1].distance > 0f && allDistancesHelperList [2].distance < 0f) { //H and M are aboe the water //H is after the verice that's below water, which is L //So we know which one is L becuase it is the last in the sorted list Vector3 L = allDistancesHelperList [2].verticePos; //Find the name of H string H_name = "temp"; if (allDistancesHelperList [2].name == "one") { H_name = "two"; } else if (allDistancesHelperList [2].name == "two") { H_name = "three"; } else { H_name = "one"; } //We also need the hights to the water float h_L = allDistancesHelperList [2].distance; float h_H = 0f; float h_M = 0f; Vector3 H = Vector3.zero; Vector3 M = Vector3.zero; //This means M is at the position 1 in the List if (allDistancesHelperList [1].name == H_name) { H = allDistancesHelperList [1].verticePos; M = allDistancesHelperList [0].verticePos; h_H = allDistancesHelperList [1].distance; h_M = allDistancesHelperList [0].distance; } else { H = allDistancesHelperList [0].verticePos; M = allDistancesHelperList [1].verticePos; h_H = allDistancesHelperList [0].distance; h_M = allDistancesHelperList [1].distance; } //Now we can find where to cut the traingle //Point J_M Vector3 LM = M - L; float t_M = -h_L / (h_M - h_L); Vector3 LJ_M = t_M * LM; Vector3 J_M = LJ_M + L; //Point J_H Vector3 LH = H - L; float t_H = -h_L / (h_H - h_L); Vector3 LJ_H = t_H * LH; Vector3 J_H = LJ_H + L; //Create the triangle AddCoordinateToMesh (L); AddCoordinateToMesh (J_H); AddCoordinateToMesh (J_M); } UnderWaterMesh.Clear (); UnderWaterMesh.name = "UnderWaterMesh"; UnderWaterMesh.vertices = underwaterVertices.ToArray (); //underwatermesh uv = uvs.toArray(); UnderWaterMesh.triangles = underwaterTriangles.ToArray (); //Ensure that the bounding volume is correct UnderWaterMesh.RecalculateBounds (); //Update the normals to reflect the change UnderWaterMesh.RecalculateNormals (); } }