public int InsertCropData(Crop crop) { int id = 0; using (SqlConnection con = DBConnection.GetConnection()) { SqlCommand cmd = new SqlCommand("InsertCrop", con); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@name", crop.Name)); cmd.Parameters.Add(new SqlParameter("@crop_type", crop.CropType)); cmd.Parameters.Add(new SqlParameter("@time_of_planting", crop.timeOfPlanting)); cmd.Parameters.Add(new SqlParameter("@avatar_image", crop.AvatarImage)); cmd.Parameters.Add(new SqlParameter("@watering_frequency", crop.WateringFrequency)); cmd.Parameters.Add(new SqlParameter("@watering_period", crop.WateringPeriod)); cmd.Parameters.Add(new SqlParameter("@harvest_time", crop.HarvestTime)); cmd.Parameters.Add(new SqlParameter("@hilling_time", crop.HillingTime)); cmd.Parameters.Add(new SqlParameter("@fertillizing_time", crop.FertilizingTime)); cmd.Parameters.Add(new SqlParameter("@field_coverage", crop.FieldCoverage)); cmd.Parameters.Add(new SqlParameter("@field_fk_id", crop.FieldId)); con.Open(); //cmd.ExecuteNonQuery(); SqlDataAdapter ad = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); ad.Fill(ds); DataTable result = ds.Tables[0]; foreach (DataRow row in result.Rows) { id = Int16.Parse(row[0].ToString()); } con.Close(); } return id; }
public void CropInsertTest() { CropServiceClient client = null; try { //GetData test client = new CropServiceClient(); Crop expected = new Crop(); expected.name = "Psenica"; expected.croptype = "MN98"; expected.fertilizingtime = new DateTime(2013, 04, 16); expected.fieldfk = 2; expected.harvesttime = new DateTime(2013, 05, 05); expected.hillingtime = new DateTime(2013, 03, 03); expected.illnessfk = 1; expected.journalfk = 1; expected.timeofplanting = new DateTime(2013, 02, 20); expected.wateringfrequency = 2; expected.wateringperiod = "mjesec"; int expectedid = client.InsertCropData(expected); Crop actual = client.SelectCropById(expectedid); Assert.AreEqual(expectedid, actual.cropid); }catch(Exception e){ Console.WriteLine("Exception encounter: {0}", e.Message); } }
public FarmLandUnitOnTheList(bool _isTheSpotPurchased,int _indexOfTheLandOnTheList,Farmland _farmlandInfoOfTheSpot) { isTheSpotPurchased = _isTheSpotPurchased; indexOfTheLandOnTheList = _indexOfTheLandOnTheList; farmlandInfoOfTheSpot = _farmlandInfoOfTheSpot; if (!isTheSpotPurchased) { isTheSpotEmpty=false; } else { isTheSpotEmpty=true; } if (isTheSpotEmpty) { landStatus="<Empty>"; } else{ landStatus= "Cost $"+_farmlandInfoOfTheSpot.costToPurchase+" to unlock"; } cropInfoOfTheSpot = null; currentLevelOfTheCrop = maxLevelOfTheCrop = 0; theFarmLandCost = _farmlandInfoOfTheSpot.costToPurchase; }
// Use this for initialization void Start() { crop = new Crop(); if(PlayerPrefs.GetString("FieldName") == ""){ crop.setType(PlayerPrefs.GetInt("CropType")); FieldName = PlayerPrefs.GetString("NFName"); alphatext = new float[terrain.GetComponent<Terrain>().terrainData.alphamapWidth,terrain.GetComponent<Terrain>().terrainData.alphamapHeight,2]; for(int i = 0; i < terrain.GetComponent<Terrain>().terrainData.alphamapWidth; i++){ for(int j = 0; j < terrain.GetComponent<Terrain>().terrainData.alphamapHeight; j++){ alphatext[i,j,0] = 1; alphatext[i,j,1] = 0; } } Vector3 localPos = new Vector3(50,0,50) - terrain.transform.position; Vector3 normalPos = new Vector3((localPos.x/terrain.GetComponent<Terrain>().terrainData.size.x) * terrain.GetComponent<Terrain>().terrainData.alphamapWidth, 0, (localPos.z/terrain.GetComponent<Terrain>().terrainData.size.z) * terrain.GetComponent<Terrain>().terrainData.alphamapHeight); alphatext[(int)normalPos.z,(int)normalPos.x,0] = 0; alphatext[(int)normalPos.z,(int)normalPos.x,1] = 1; terrain.GetComponent<Terrain>().terrainData.SetAlphamaps(0,0,alphatext); } else{ FieldName = PlayerPrefs.GetString("FieldName"); byte[] load = sf.Load (PlayerPrefs.GetString("FieldName")); UnitySerializer.DeserializeInto(load,sf); crop.setField(sf.getCrops()); terrain.GetComponent<Terrain>().terrainData.SetHeights(0,0,sf.getHM ()); terrain.GetComponent<Terrain>().terrainData.SetAlphamaps(0,0,sf.getAM()); alphatext = sf.getAM(); terrain.GetComponent<Terrain>().terrainData.SetAlphamaps(0,0,alphatext); loaded = true; } }
public ActionResult Create(FormCollection collection) { try { Crop newCrop = new Crop(); newCrop.Name = collection["name"]; newCrop.Description = collection["desc"]; newCrop.Organic = collection["organic"] != null ? true : false; newCrop.AddedDate = DateTime.Now; this.cropRepo.EnsurePersistent(newCrop); return Json( new { alert = "<div id='add_crop_alert' class='alert alert-success'>" + "<button type='button' class='close' data-dismiss='alert'>×</button>" + "<strong>Crop Added Successfully!</strong>" + "</div>", id = newCrop.Id } ); } catch { return RedirectToAction("Index"); } }
static void Main(string[] args) { CropServiceClient client = null; try { //GetData test client = new CropServiceClient(); Crop c = client.SelectCropById(1); Console.WriteLine("Result: "); Console.WriteLine("name = {0}", c.name); Crop crop = new Crop(); crop.name = "Hmelj"; crop.croptype = "MN98"; crop.fertilizingtime = new DateTime(2013, 04, 16); crop.fieldfk = 2; crop.harvesttime = new DateTime(2013, 05, 05); crop.hillingtime = new DateTime(2013, 03, 03); crop.illnessfk = 1; crop.journalfk = 1; crop.timeofplanting = new DateTime(2013, 02, 20); crop.wateringfrequency = 2; crop.wateringperiod = "mjesec"; int id = client.InsertCropData(crop); Console.WriteLine("The WCF service called returned: "); //GetDataUsingDataContract test //CompositeType compositeType = new CompositeType(); //compositeType.BoolValue = true; //compositeType.StringValue = "test"; //CompositeType responseComposit = client.GetDataUsingDataContract(compositeType); //Console.WriteLine("The WCF service called returned: '{0}' '{1}'", // responseComposit.BoolValue, responseComposit.StringValue); Console.WriteLine("Press any key to close"); Console.ReadKey(); } catch (Exception e) { Console.WriteLine("Exception encounter: {0}", e.Message); Console.WriteLine("Press any key to close"); Console.ReadKey(); } finally { if (null != client) { client.Close(); } } }
public Crop SelectCropById(int crop_id) { Crop crop = new Crop(); try { using (SqlConnection con = DBConnection.GetConnection()) { SqlCommand cmd = new SqlCommand("SelectCropById", con); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@id_crop", crop_id)); con.Open(); SqlDataAdapter ad = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); ad.Fill(ds); DataTable cropsTable = ds.Tables[0]; if (cropsTable == null) { return null; } else { foreach (DataRow row in cropsTable.Rows) { crop.CropId = Int16.Parse(row[0].ToString()); crop.Name = row[1].ToString(); crop.CropType = row[2].ToString(); crop.timeOfPlanting = DateTime.Parse(row[3].ToString()); crop.AvatarImage = row[4] as byte[]; crop.WateringFrequency = Int16.Parse(row[5].ToString()); crop.WateringPeriod = row[6].ToString(); crop.HarvestTime = DateTime.Parse(row[7].ToString()); crop.HillingTime = DateTime.Parse(row[8].ToString()); crop.FertilizingTime = DateTime.Parse(row[9].ToString()); crop.FieldCoverage = Double.Parse(row[10].ToString()); crop.FieldId = Int16.Parse(row[11].ToString()); } } con.Close(); } } catch (Exception e) { Console.WriteLine(e.StackTrace); } return crop; }
/* * This is ran during the start up of the scene. * This set the terrain to dug up when driven over. * */ void Start() { crop = new Crop(); waypoints = new WaypointFPT(terrain); waypoints.genPointsStr(new Vector3(50,0,50),true); tractorAI = (GameObject)Instantiate(objPre,new Vector3(50,.3f,50),Quaternion.identity); tractorAI.name = "AI Tractor FP"; if(PlayerPrefs.GetString("FieldName") == ""){ crop.setType(PlayerPrefs.GetInt("CropType")); FieldName = PlayerPrefs.GetString("NFName"); alphatext = new float[terrain.GetComponent<Terrain>().terrainData.alphamapWidth,terrain.GetComponent<Terrain>().terrainData.alphamapHeight,2]; for(int i = 0; i < terrain.GetComponent<Terrain>().terrainData.alphamapWidth; i++){ for(int j = 0; j < terrain.GetComponent<Terrain>().terrainData.alphamapHeight; j++){ alphatext[i,j,0] = 1; alphatext[i,j,1] = 0; } } Vector3 localPos = new Vector3(50,0,50) - terrain.transform.position; Vector3 normalPos = new Vector3((localPos.x/terrain.GetComponent<Terrain>().terrainData.size.x) * terrain.GetComponent<Terrain>().terrainData.alphamapWidth, 0, (localPos.z/terrain.GetComponent<Terrain>().terrainData.size.z) * terrain.GetComponent<Terrain>().terrainData.alphamapHeight); alphatext[(int)normalPos.z,(int)normalPos.x,0] = 0; alphatext[(int)normalPos.z,(int)normalPos.x,1] = 1; terrain.GetComponent<Terrain>().terrainData.SetAlphamaps(0,0,alphatext); // fieldData = new SFFD(terrain.GetComponent<Terrain>().terrainData.alphamapWidth,terrain.GetComponent<Terrain>().terrainData.alphamapHeight,2, // terrain.GetComponent<Terrain>().terrainData.detailWidth,terrain.GetComponent<Terrain>().terrainData.detailHeight,terrain.GetComponent<Terrain>().terrainData.detailPrototypes.Length, // terrain.GetComponent<Terrain>().terrainData.heightmapWidth,terrain.GetComponent<Terrain>().terrainData.heightmapHeight); // fieldData.setHM (terrain.GetComponent<Terrain>().terrainData.GetHeights(0,0,terrain.GetComponent<Terrain>().terrainData.heightmapWidth,terrain.GetComponent<Terrain>().terrainData.heightmapHeight)); // fieldData.setAM (terrain.GetComponent<Terrain>().terrainData.GetAlphamaps(0,0,terrain.GetComponent<Terrain>().terrainData.alphamapWidth,terrain.GetComponent<Terrain>().terrainData.alphamapHeight)); // fieldData.setDM (terrain.GetComponent<Terrain>().terrainData.GetDetailLayer(0,0,terrain.GetComponent<Terrain>().terrainData.detailWidth,terrain.GetComponent<Terrain>().terrainData.detailHeight,1)); // fieldData.save(); } else{ FieldName = PlayerPrefs.GetString("FieldName"); byte[] load = sf.Load (PlayerPrefs.GetString("FieldName")); UnitySerializer.DeserializeInto(load,sf); crop.setField(sf.getCrops()); tractorAI.transform.position += new Vector3(0,15,0); terrain.GetComponent<Terrain>().terrainData.SetHeights(0,0,sf.getHM ()); terrain.GetComponent<Terrain>().terrainData.SetAlphamaps(0,0,sf.getAM()); alphatext = sf.getAM(); terrain.GetComponent<Terrain>().terrainData.SetAlphamaps(0,0,alphatext); loaded = true; } }
private CTP Map(Crop crop, Dictionary<int, string> keyToIsoId, int cropIndex, Catalog setupCatalog) { var ctp = new CTP { B = crop.Name }; ctp.A = ctp.GetIsoId(cropIndex); var cvts = setupCatalog.Products.Where(x => x is CropVariety).Cast<CropVariety>().Where(v => v.CropId == crop.Id.ReferenceId).Select(Map); var cvtArray = cvts as CVT[] ?? cvts.ToArray(); if (cvtArray.Any()) { ctp.Items = cvtArray.ToArray(); } keyToIsoId.Add(crop.Id.ReferenceId, ctp.A); return ctp; }
/// <summary> /// Crops an image to the given width and height with the given source rectangle. /// <remarks> /// If the source rectangle is smaller than the target dimensions then the /// area within the source is resized performing a zoomed crop. /// </remarks> /// </summary> /// <param name="source">The image to crop.</param> /// <param name="width">The target image width.</param> /// <param name="height">The target image height.</param> /// <param name="sourceRectangle"> /// The <see cref="Rectangle"/> structure that specifies the portion of the image object to draw. /// </param> /// <param name="progressHandler">A delegate which is called as progress is made processing the image.</param> /// <returns>The <see cref="Image"/></returns> public static Image Crop(this Image source, int width, int height, Rectangle sourceRectangle, ProgressEventHandler progressHandler = null) { if (sourceRectangle.Width < width || sourceRectangle.Height < height) { // If the source rectangle is smaller than the target perform a // cropped zoom. source = source.Resize(sourceRectangle.Width, sourceRectangle.Height); } Crop processor = new Crop(); processor.OnProgress += progressHandler; try { return source.Process(width, height, sourceRectangle, new Rectangle(0, 0, width, height), processor); } finally { processor.OnProgress -= progressHandler; } }
public void init() { //Insert Test data CropServiceClient client = new CropServiceClient(); List<Crop> testCrops = new List<Crop>(); Crop crop1 = new Crop(); crop1.name = "Repica"; crop1.croptype = "MN98"; crop1.fertilizingtime = new DateTime(2013, 04, 16); crop1.fieldfk = 2; crop1.harvesttime = new DateTime(2013, 05, 05); crop1.hillingtime = new DateTime(2013, 03, 03); crop1.illnessfk = 1; crop1.journalfk = 1; crop1.timeofplanting = new DateTime(2013, 02, 20); crop1.wateringfrequency = 2; crop1.wateringperiod = "mjesec"; Crop crop2 = new Crop(); crop2.name = "Lubenica"; crop2.croptype = "MN98"; crop2.fertilizingtime = new DateTime(2013, 04, 16); crop2.fieldfk = 2; crop2.harvesttime = new DateTime(2013, 05, 05); crop2.hillingtime = new DateTime(2013, 03, 03); crop2.illnessfk = 1; crop2.journalfk = 1; crop2.timeofplanting = new DateTime(2013, 02, 20); crop2.wateringfrequency = 2; crop2.wateringperiod = "mjesec"; testCrops.Add(crop1); testCrops.Add(crop2); foreach (Crop c in testCrops) { client.InsertCropData(c); } }
public void Example1() { Bitmap image = Properties.Resources.lena512; // Create a new Haar Wavelet transform filter var wavelet = new WaveletTransform(new Haar(1)); // Apply the Wavelet transformation Bitmap result = wavelet.Apply(image); // Show on the screen //ImageBox.Show(result); Assert.IsNotNull(result); // Extract only one of the resulting images var crop = new Crop(new Rectangle(0, 0, image.Width / 2, image.Height / 2)); Bitmap quarter = crop.Apply(result); // Show on the screen //ImageBox.Show(quarter); Assert.IsNotNull(quarter); }
public List<Crop> SelectCrops() { List<Crop> crops = new List<Crop>(); using (SqlConnection con = DBConnection.GetConnection()) { SqlCommand cmd = new SqlCommand("SelectCrops", con); cmd.CommandType = System.Data.CommandType.StoredProcedure; con.Open(); SqlDataAdapter ad = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); ad.Fill(ds); DataTable cropsTable = ds.Tables[0]; if (cropsTable == null) { return null; } else { foreach (DataRow row in cropsTable.Rows) { Crop crop = new Crop(); crop.CropId = Int16.Parse(row[0].ToString()); crop.Name = row[1].ToString(); crop.CropType = row[2].ToString(); crop.timeOfPlanting = DateTime.Parse(row[3].ToString()); crop.HarvestTime = DateTime.Parse(row[4].ToString()); crop.HillingTime = DateTime.Parse(row[5].ToString()); crop.FertilizingTime = DateTime.Parse(row[6].ToString()); crops.Add(crop); } } con.Close(); } return crops; }
// Maps ViewModel with service DataContract private Crop mapCropModelToCrop(CropModel cm) { Crop crop = new Crop(); crop.name = cm.Name; crop.croptype = cm.Type; crop.timeofplanting = cm.TimeOfPlanting; crop.avatarimage = cm.AvatarImage; crop.fieldcoverage = cm.CoverageValue; crop.wateringfrequency = cm.WateringFrequency; crop.wateringperiod = (Int16.Parse(cm.WateringPeriod)+1).ToString(); crop.harvesttime = cm.HarvestTime; crop.hillingtime = cm.HillingTime; crop.fertilizingtime = cm.FertilizingTime; crop.fieldid = cm.FieldId; return crop; }
public TerrainFeature getTerrainFeature(string type, Vector2 pos) { switch (type.ToLower()) { case "wood-floor": return(new Flooring(0)); case "stone-floor": return(new Flooring(1)); case "weathered-floor": return(new Flooring(2)); case "crystal-floor": return(new Flooring(3)); case "straw-floor": return(new Flooring(4)); case "gravel-path": return(new Flooring(5)); case "wood-path": return(new Flooring(6)); case "crystal-path": return(new Flooring(7)); case "steppingstone-path": return(new Flooring(8)); case "road": return(new Flooring(9)); case "cherry-tree": return(new FruitTree(628, 5)); case "apricot": return(new FruitTree(629, 5)); case "orange-tree": return(new FruitTree(630, 5)); case "peach": return(new FruitTree(631, 5)); case "pomegranate": return(new FruitTree(632, 5)); case "apple": return(new FruitTree(633, 5)); case "oak-tree": return(new Tree(1, 5)); case "pine-tree": return(new Tree(3, 5)); case "maple-tree": return(new Tree(2, 5)); case "tree": Tree tree = new Tree(1, 5); tree.stump.Value = true; tree.health.Value = 5f; return(tree); case "large-rock": return(new ResourceClump(672, 2, 2, pos)); case "large-log": return(new ResourceClump(600, 2, 2, pos)); case "large-stump": return(new ResourceClump(602, 2, 2, pos)); case "tulips": Crop tulips = new Crop(427, (int)pos.X, (int)pos.Y); tulips.growCompletely(); return(new HoeDirt(0, tulips)); case "tulip": Crop tulip = new Crop(427, (int)pos.X, (int)pos.Y); tulip.growCompletely(); return(new HoeDirt(0, tulip)); case "summer-spangle": Crop summerspangle = new Crop(455, (int)pos.X, (int)pos.Y); summerspangle.growCompletely(); return(new HoeDirt(0, summerspangle)); case "blue-jazz": Crop bluejazz = new Crop(429, (int)pos.X, (int)pos.Y); bluejazz.growCompletely(); return(new HoeDirt(0, bluejazz)); case "fairy-rose": Crop fairyrose = new Crop(425, (int)pos.X, (int)pos.Y); fairyrose.growCompletely(); return(new HoeDirt(0, fairyrose)); case "poppy": Crop poppy = new Crop(453, (int)pos.X, (int)pos.Y); poppy.growCompletely(); return(new HoeDirt(0, poppy)); case "grape": Crop grape = new Crop(301, (int)pos.X, (int)pos.Y); grape.growCompletely(); return(new HoeDirt(0, grape)); case "trellis": Crop trellis = new Crop(301, (int)pos.X, (int)pos.Y); trellis.growCompletely(); return(new HoeDirt(0, trellis)); case "cauliflower": Crop cauliflower = new Crop(474, (int)pos.X, (int)pos.Y); cauliflower.growCompletely(); return(new HoeDirt(0, cauliflower)); case "garlic": Crop garlic = new Crop(476, (int)pos.X, (int)pos.Y); garlic.growCompletely(); return(new HoeDirt(0, garlic)); case "green-bean": Crop greenbean = new Crop(473, (int)pos.X, (int)pos.Y); greenbean.growCompletely(); return(new HoeDirt(0, greenbean)); case "kale": Crop kale = new Crop(477, (int)pos.X, (int)pos.Y); kale.growCompletely(); return(new HoeDirt(0, kale)); case "parsnip": Crop parsnip = new Crop(472, (int)pos.X, (int)pos.Y); parsnip.growCompletely(); return(new HoeDirt(0, parsnip)); case "potato": Crop potato = new Crop(475, (int)pos.X, (int)pos.Y); potato.growCompletely(); return(new HoeDirt(0, potato)); case "rhubarb": Crop rhubarb = new Crop(478, (int)pos.X, (int)pos.Y); rhubarb.growCompletely(); return(new HoeDirt(0, rhubarb)); case "strawberry": Crop strawberry = new Crop(745, (int)pos.X, (int)pos.Y); strawberry.growCompletely(); return(new HoeDirt(0, strawberry)); case "blueberry": Crop blueberry = new Crop(481, (int)pos.X, (int)pos.Y); blueberry.growCompletely(); return(new HoeDirt(0, blueberry)); case "corn": Crop corn = new Crop(487, (int)pos.X, (int)pos.Y); corn.growCompletely(); return(new HoeDirt(0, corn)); case "hops": Crop hops = new Crop(302, (int)pos.X, (int)pos.Y); hops.growCompletely(); return(new HoeDirt(0, hops)); case "hot-pepper": Crop hotpepper = new Crop(482, (int)pos.X, (int)pos.Y); hotpepper.growCompletely(); return(new HoeDirt(0, hotpepper)); case "melon": Crop melon = new Crop(479, (int)pos.X, (int)pos.Y); melon.growCompletely(); return(new HoeDirt(0, melon)); case "radish": Crop radish = new Crop(484, (int)pos.X, (int)pos.Y); radish.growCompletely(); return(new HoeDirt(0, radish)); case "red-cabbage": Crop redcabbage = new Crop(485, (int)pos.X, (int)pos.Y); redcabbage.growCompletely(); return(new HoeDirt(0, redcabbage)); case "starfruit": Crop starfruit = new Crop(486, (int)pos.X, (int)pos.Y); starfruit.growCompletely(); return(new HoeDirt(0, starfruit)); case "tomato": Crop tomato = new Crop(480, (int)pos.X, (int)pos.Y); tomato.growCompletely(); return(new HoeDirt(0, tomato)); case "wheat": Crop wheat = new Crop(483, (int)pos.X, (int)pos.Y); wheat.growCompletely(); return(new HoeDirt(0, wheat)); case "amaranth": Crop amaranth = new Crop(299, (int)pos.X, (int)pos.Y); amaranth.growCompletely(); return(new HoeDirt(0, amaranth)); case "ancient-fruit": Crop ancientfruit = new Crop(499, (int)pos.X, (int)pos.Y); ancientfruit.growCompletely(); return(new HoeDirt(0, ancientfruit)); case "artichoke": Crop artichoke = new Crop(489, (int)pos.X, (int)pos.Y); artichoke.growCompletely(); return(new HoeDirt(0, artichoke)); case "beet": Crop beet = new Crop(494, (int)pos.X, (int)pos.Y); beet.growCompletely(); return(new HoeDirt(0, beet)); case "bokchoy": Crop bokchoy = new Crop(491, (int)pos.X, (int)pos.Y); bokchoy.growCompletely(); return(new HoeDirt(0, bokchoy)); case "cranberry": Crop cranberry = new Crop(493, (int)pos.X, (int)pos.Y); cranberry.growCompletely(); return(new HoeDirt(0, cranberry)); case "pumpkin": Crop pumpkin = new Crop(490, (int)pos.X, (int)pos.Y); pumpkin.growCompletely(); return(new HoeDirt(0, pumpkin)); case "eggplant": Crop eggplant = new Crop(488, (int)pos.X, (int)pos.Y); eggplant.growCompletely(); return(new HoeDirt(0, eggplant)); case "sunflower": Crop sunflower = new Crop(431, (int)pos.X, (int)pos.Y); sunflower.growCompletely(); return(new HoeDirt(0, sunflower)); case "yam": Crop yam = new Crop(492, (int)pos.X, (int)pos.Y); yam.growCompletely(); return(new HoeDirt(0, yam)); case "grass": return(new Grass(1, 4)); case "farmland": return(new HoeDirt(0)); case "mushroom-tree": return(new Tree(7, 5)); case "palm-tree": return(new Tree(6, 5)); default: return(null); } }
private Object GetHarvest(HoeDirt dirt, Vector2 tile, GameLocation location) { Crop crop = dirt.crop; Object harvest; int stack = 0; if (crop is null) { return(null); } if (!Config.DoHarvestFlowers) { switch (crop.indexOfHarvest.Value) { case 421: return(null); // sunflower case 593: return(null); // summer spangle case 595: return(null); // fairy rose case 591: return(null); // tulip case 597: return(null); // blue jazz case 376: return(null); // poppy } } if (crop != null && crop.currentPhase.Value >= crop.phaseDays.Count - 1 && (!crop.fullyGrown.Value || crop.dayOfCurrentPhase.Value <= 0)) { int num1 = 1; int num2 = 0; int num3 = 0; if (crop.indexOfHarvest.Value == 0) { return(null); } System.Random random = new System.Random((int)tile.X * 7 + (int)tile.Y * 11 + (int)Game1.stats.DaysPlayed + (int)Game1.uniqueIDForThisGame); switch ((dirt.fertilizer.Value)) { case 368: num3 = 1; break; case 369: num3 = 2; break; } double num4 = 0.2 * (Game1.player.FarmingLevel / 10.0) + 0.2 * num3 * ((Game1.player.FarmingLevel + 2.0) / 12.0) + 0.01; double num5 = System.Math.Min(0.75, num4 * 2.0); if (random.NextDouble() < num4) { num2 = 2; } else if (random.NextDouble() < num5) { num2 = 1; } if ((crop.minHarvest.Value) > 1 || (crop.maxHarvest.Value) > 1) { num1 = random.Next(crop.minHarvest.Value, System.Math.Min(crop.minHarvest.Value + 1, crop.maxHarvest.Value + 1 + Game1.player.FarmingLevel / crop.maxHarvestIncreasePerFarmingLevel.Value)); } if (crop.chanceForExtraCrops.Value > 0.0) { while (random.NextDouble() < System.Math.Min(0.9, crop.chanceForExtraCrops.Value)) { ++num1; } } if (crop.harvestMethod.Value == 1) { for (int i = 0; i < num1; i++) { stack += 1; } if (crop.regrowAfterHarvest.Value != -1) { crop.dayOfCurrentPhase.Value = crop.regrowAfterHarvest.Value; crop.fullyGrown.Value = true; } else { dirt.crop = null; } return(new Object(crop.indexOfHarvest.Value, stack, false, -1, num2)); } else { if (!crop.programColored.Value) { harvest = new Object(crop.indexOfHarvest.Value, 1, false, -1, num2); } else { harvest = new ColoredObject(crop.indexOfHarvest.Value, 1, crop.tintColor.Value) { Quality = num2 }; } if (crop.regrowAfterHarvest.Value != -1) { crop.dayOfCurrentPhase.Value = crop.regrowAfterHarvest.Value; crop.fullyGrown.Value = true; } else { dirt.crop = null; } return(harvest); } } return(null); }
/********* ** Private methods *********/ /// <summary>Get the crop's source rectangle in the sprite sheet.</summary> /// <param name="crop">The crop.</param> private Rectangle GetSourceRectangle(Crop crop) { return(this.Reflection.GetPrivateMethod(crop, "getSourceRect").Invoke <Rectangle>(crop.rowInSpriteSheet)); }
private void SearchForGroundCrops(GameLocation location) { // Search for crops foreach (KeyValuePair <Vector2, TerrainFeature> tileToHoeDirt in location.terrainFeatures.Pairs.Where(p => p.Value is HoeDirt && (p.Value as HoeDirt).crop != null)) { if (!HasRoomForHarvest()) { isFull = true; return; } Vector2 tile = tileToHoeDirt.Key; HoeDirt hoeDirt = (tileToHoeDirt.Value as HoeDirt); Crop crop = hoeDirt.crop; if (!hoeDirt.readyForHarvest()) { // Crop is either not fully grown or it has not regrown since last harvest //monitor.Log($"Crop at ({tile.X}, {tile.Y}) is not ready for harvesting: {crop.forageCrop} | {crop.regrowAfterHarvest} | {crop.dayOfCurrentPhase}, {crop.currentPhase}", LogLevel.Debug); continue; } //monitor.Log($"Harvesting crop ({tile.X}, {tile.Y}): {crop.forageCrop} | {crop.regrowAfterHarvest} | {crop.dayOfCurrentPhase}, {crop.currentPhase}", LogLevel.Debug); if (!doJunimosHarvestFromFlowers && new Object(tile, crop.indexOfHarvest, 0).Category == -80) { // Crop is flower and config has been set to skip them continue; } // Crop exists and is fully grown, attempt to harvest it crop.harvest((int)tile.X, (int)tile.Y, hoeDirt, null); harvestedToday = true; harvestedTiles.Add(tile); // Clear any non-renewing crop if (crop.regrowAfterHarvest == -1) { int seedIndex = crop.netSeedIndex; hoeDirt.crop = null; // Attempt to replant, if it is enabled and has valid seed if (doJunimosSowSeedsAfterHarvest) { AttemptSowSeed(seedIndex, hoeDirt, tile); } } } // Search for forage products List <Vector2> tilesToRemove = new List <Vector2>(); foreach (KeyValuePair <Vector2, Object> tileToForage in location.objects.Pairs.Where(p => p.Value.isForage(location))) { if (!HasRoomForHarvest()) { isFull = true; return; } Vector2 tile = tileToForage.Key; if (chest.addItem(tileToForage.Value.getOne()) != null) { chest.modData[ModEntry.ateCropsFlag] = true.ToString(); } tilesToRemove.Add(tile); harvestedToday = true; harvestedTiles.Add(tile); } // Clean up the harvested forage products tilesToRemove.ForEach(t => location.removeObject(t, false)); }
//Constructor that stores previously passed in crops, so that all crops can be present at once public Crop(Crop previousCrop) { UniqueId = previousCrop.UniqueId; TimeToMature = previousCrop.TimeToMature; DeathChance = previousCrop.DeathChance; MaturityPercentage = previousCrop.MaturityPercentage; IntervalBetweenDeathChecks = previousCrop.IntervalBetweenDeathChecks; IsDead = previousCrop.IsDead; Name = previousCrop.Name; Cost = previousCrop.Cost; MaxValue = previousCrop.MaxValue; }
private FaceConcepts(string id, Crop crop, List <Concept> concepts) { ID = id; Crop = crop; Concepts = concepts; }
public Bitmap ProcessImage(ImageProcessorSettings settings) { Bitmap output = Image.Clone() as Bitmap; if (settings.RemoveBorder > 0) { int x = settings.RemoveBorder; output = new Crop(new Rectangle(x, x, Image.Width - (2 * x), Image.Height - (2 * x))).Apply(Image); } if (settings.RemovePixelNoise > 0) { for (int i = 0; i < settings.RemovePixelNoise; i++) { // Use a copy for iteration Bitmap bitmap = new Bitmap(output); for (int j = 1; j < (output.Height - 1); j++) { for (int k = 1; k < (output.Width - 1); k++) { if (output.GetPixel(k, j).GetBrightness() < 0.5) { // Top left float tl = output.GetPixel(k - 1, j).GetBrightness(); // Top right float tr = output.GetPixel(k + 1, j).GetBrightness(); // Bottom left float bl = output.GetPixel(k, j - 1).GetBrightness(); // Bottom right float br = output.GetPixel(k, j + 1).GetBrightness(); // Test the edges if (tl > 0.5 && tr > 0.5) { bitmap.SetPixel(k, j, Color.White); } if (bl > 0.5 && br > 0.5) { bitmap.SetPixel(k, j, Color.White); } } } } output = bitmap; } } if (settings.LinearizeColors) { ImageStatistics statistics = new ImageStatistics(output); output = new LevelsLinear { InRed = new Range(statistics.Red.Min, statistics.Red.Max), InGreen = new Range(statistics.Green.Min, statistics.Green.Max), InBlue = new Range(statistics.Blue.Min, statistics.Blue.Max) }.Apply(output); } if (settings.InvertColors) { output = new Invert().Apply(output); } if (settings.ImageBlur) { output = new Blur().Apply(output); } if (settings.BrightnessThreshold > 0) { // Brightness threshold is in percent.. decimal threshold = (decimal)settings.BrightnessThreshold / 100M; output = new Threshold(Convert.ToByte((decimal)(threshold * 255M)), 255).Apply(output); } return(output); }
/// <summary>The method to call after <see cref="Crop.harvest"/>.</summary> private static void After_Harvest(Crop __instance, int xTile, int yTile, HoeDirt soil, JunimoHarvester junimoHarvester) { soil.fertilizer.Value = 0; }
private SKData GetImageData(string imagePath, ResizeParams resizeParams, DateTime lastWriteTimeUtc) { // check cache and return if cached long cacheKey; unchecked { cacheKey = imagePath.GetHashCode() + lastWriteTimeUtc.ToBinary() + resizeParams.ToString().GetHashCode(); } SKData imageData; byte[] imageBytes; bool isCached = _memoryCache.TryGetValue <byte[]>(cacheKey, out imageBytes); if (isCached) { _logger.LogInformation("Serving from cache"); return(SKData.CreateCopy(imageBytes)); } SKEncodedOrigin origin; // this represents the EXIF orientation var bitmap = LoadBitmap(File.OpenRead(imagePath), out origin); // always load as 32bit (to overcome issues with indexed color) if (resizeParams.w == 0) { resizeParams.w = bitmap.Width; } if (resizeParams.h == 0) { resizeParams.h = bitmap.Height; } // if autorotate = true, and origin isn't correct for the rotation, rotate it if (resizeParams.autorotate && origin != SKEncodedOrigin.TopLeft) { bitmap = RotateAndFlip.RotateAndFlipImage(bitmap, origin); } // if either w or h is 0, set it based on ratio of original image if (resizeParams.h == 0) { resizeParams.h = (int)Math.Round(bitmap.Height * (float)resizeParams.w / bitmap.Width); } else if (resizeParams.w == 0) { resizeParams.w = (int)Math.Round(bitmap.Width * (float)resizeParams.h / bitmap.Height); } // if we need to crop, crop the original before resizing if (resizeParams.mode == "crop") { bitmap = Crop.CropImage(bitmap, resizeParams); } // store padded height and width var paddedHeight = resizeParams.h; var paddedWidth = resizeParams.w; // if we need to pad, or max, set the height or width according to ratio if (resizeParams.mode == "pad" || resizeParams.mode == "max") { var bitmapRatio = (float)bitmap.Width / bitmap.Height; var resizeRatio = (float)resizeParams.w / resizeParams.h; if (bitmapRatio > resizeRatio) // original is more "landscape" { resizeParams.h = (int)Math.Round(bitmap.Height * ((float)resizeParams.w / bitmap.Width)); } else { resizeParams.w = (int)Math.Round(bitmap.Width * ((float)resizeParams.h / bitmap.Height)); } } // resize var resizedImageInfo = new SKImageInfo(resizeParams.w, resizeParams.h, SKImageInfo.PlatformColorType, bitmap.AlphaType); var resizedBitmap = bitmap.Resize(resizedImageInfo, SKFilterQuality.High); // optionally pad if (resizeParams.mode == "pad") { resizedBitmap = Padding.PaddingImage(resizedBitmap, paddedWidth, paddedHeight, resizeParams.format != "png"); } // watermarkText if (resizeParams.wmtext != 0) { if (watermarkText != null) { resizedBitmap = Watermark.WatermarkText(resizedBitmap, resizeParams, watermarkText); } } // watermarkImage if (resizeParams.wmimage != 0) { if (watermarkImage != null) { resizedBitmap = Watermark.WatermarkImage(resizedBitmap, resizeParams, watermarkImage); } } // encode var resizedImage = SKImage.FromBitmap(resizedBitmap); var encodeFormat = resizeParams.format == "png" ? SKEncodedImageFormat.Png : SKEncodedImageFormat.Jpeg; imageData = resizedImage.Encode(encodeFormat, resizeParams.quality); // cache the result _memoryCache.Set <byte[]>(cacheKey, imageData.ToArray()); // cleanup resizedImage.Dispose(); bitmap.Dispose(); resizedBitmap.Dispose(); return(imageData); }
//private double _dRealFrameCounter = 1; //private double _dPresentationFrameCounter = 1; private void VideoNewFrame(object sender, NewFrameEventArgs e) { if (_requestedToStop || NewFrame == null) { return; } if (_lastframeEvent > DateTime.MinValue) { //discard this frame to limit framerate? - this is a hack, not the best method but adaptive framerate limiting is intensive if ((DateTime.Now - _lastframeProcessed).TotalMilliseconds < Mininterval) { //Console.WriteLine("skipped: " + (DateTime.Now - _lastframeProcessed).TotalMilliseconds); return; } TimeSpan tsFr = DateTime.Now - _lastframeProcessed; _framerates.Enqueue(1000d / tsFr.TotalMilliseconds); if (_framerates.Count >= 10) { _framerates.Dequeue(); } Framerate = _framerates.Average(); //framerate of live stream //var tsFr = DateTime.Now - _lastframeEvent; //_realframerates.Enqueue(1000d / tsFr.TotalMilliseconds); //while (_realframerates.Count >30) // _realframerates.Dequeue(); //RealFramerate = _realframerates.Average(); //_lastframeEvent = DateTime.Now; ////15 fps //_dRealFrameCounter++; //if (_dRealFrameCounter > RealFramerate) // _dRealFrameCounter = 1; //if (_dRealFrameCounter / RealFramerate < _dPresentationFrameCounter / MaxFramerate) //{ // return; //} //_dPresentationFrameCounter++; //if (_dPresentationFrameCounter >= 1000d / Mininterval) // _dPresentationFrameCounter = 1d; //tsFr = DateTime.Now - _lastframeProcessed; //_framerates.Enqueue(1000d / tsFr.TotalMilliseconds); //while (_framerates.Count > 30) // _framerates.Dequeue(); //Framerate = _framerates.Average(); } else { _lastframeEvent = DateTime.Now; } lock (_sync) { _lastframeProcessed = DateTime.Now; var tsBrush = new SolidBrush(MainForm.Conf.TimestampColor.ToColor()); var sbTs = new SolidBrush(Color.FromArgb(128, 0, 0, 0)); Bitmap bmOrig = null, bmp = null; Graphics g = null, gCam = null; bool err = false; try { // motionLevel = 0; if (e.Frame != null) { if (LastFrameUnmanaged != null) { LastFrameUnmanaged.Dispose(); } //resize? if (CW.Camobject.settings.resize && (CW.Camobject.settings.desktopresizewidth != e.Frame.Width || CW.Camobject.settings.desktopresizeheight != e.Frame.Height)) { var result = new Bitmap(CW.Camobject.settings.desktopresizewidth, CW.Camobject.settings.desktopresizeheight, PixelFormat.Format24bppRgb); using (Graphics g2 = Graphics.FromImage(result)) g2.DrawImage(e.Frame, 0, 0, result.Width, result.Height); e.Frame.Dispose(); bmOrig = result; } else { bmOrig = e.Frame; } if (CW.Camobject.rotate90) { bmOrig.RotateFlip(RotateFlipType.Rotate90FlipNone); } if (CW.Camobject.flipx) { bmOrig.RotateFlip(RotateFlipType.RotateNoneFlipX); } if (CW.Camobject.flipy) { bmOrig.RotateFlip(RotateFlipType.RotateNoneFlipY); } _width = bmOrig.Width; _height = bmOrig.Height; if (CW.NeedMotionZones) { CW.NeedMotionZones = !SetMotionZones(CW.Camobject.detector.motionzones); } if (Mask != null) { g = Graphics.FromImage(bmOrig); g.DrawImage(Mask, 0, 0, _width, _height); } if (Plugin != null) { bool runplugin = true; if (CW.Camobject.alerts.processmode == "motion") { //run plugin if motion detected in last 5 seconds runplugin = _motionlastdetected > DateTime.Now.AddSeconds(-5); } if (runplugin) { bmOrig = (Bitmap) Plugin.GetType().GetMethod("ProcessFrame").Invoke(Plugin, new object[] { bmOrig }); var pluginAlert = (String)Plugin.GetType().GetField("Alert").GetValue(Plugin); if (pluginAlert != "") { Alarm(pluginAlert, EventArgs.Empty); } } } LastFrameUnmanaged = UnmanagedImage.FromManagedImage(bmOrig); if (_motionDetector != null) { if (Alarm != null) { _processFrameCount++; if (_processFrameCount >= CW.Camobject.detector.processeveryframe || CW.Calibrating) { _processFrameCount = 0; MotionLevel = _motionDetector.ProcessFrame(LastFrameUnmanaged, Filter); if (MotionLevel >= _alarmLevel) { MotionDetected = true; _motionlastdetected = DateTime.Now; Alarm(this, new EventArgs()); } else { MotionDetected = false; } } } else { MotionDetected = false; } } else { MotionDetected = false; } if (ZFactor > 1) { var f1 = new ResizeNearestNeighbor(LastFrameUnmanaged.Width, LastFrameUnmanaged.Height); var f2 = new Crop(ViewRectangle); LastFrameUnmanaged = f2.Apply(LastFrameUnmanaged); LastFrameUnmanaged = f1.Apply(LastFrameUnmanaged); } if (CW.Camobject.settings.timestamplocation != 0 && CW.Camobject.settings.timestampformatter != "") { bmp = LastFrameUnmanaged.ToManagedImage(); gCam = Graphics.FromImage(bmp); var ts = CW.Camobject.settings.timestampformatter.Replace("{FPS}", string.Format("{0:F2}", Framerate)); ts = ts.Replace("{CAMERA}", CW.Camobject.name); ts = ts.Replace("{REC}", CW.Recording ? "REC" : ""); var timestamp = "Invalid Timestamp"; try { timestamp = String.Format(ts, DateTime.Now.AddHours( Convert.ToDouble(CW.Camobject.settings.timestampoffset))).Trim(); } catch { } var rs = gCam.MeasureString(timestamp, Drawfont).ToSize(); var p = new Point(0, 0); switch (CW.Camobject.settings.timestamplocation) { case 2: p.X = _width / 2 - (rs.Width / 2); break; case 3: p.X = _width - rs.Width; break; case 4: p.Y = _height - rs.Height; break; case 5: p.Y = _height - rs.Height; p.X = _width / 2 - (rs.Width / 2); break; case 6: p.Y = _height - rs.Height; p.X = _width - rs.Width; break; } var rect = new Rectangle(p, rs); gCam.FillRectangle(sbTs, rect); gCam.DrawString(timestamp, Drawfont, tsBrush, p); LastFrameUnmanaged.Dispose(); LastFrameUnmanaged = UnmanagedImage.FromManagedImage(bmp); } } } catch (UnsupportedImageFormatException ex) { CW.VideoSourceErrorState = true; CW.VideoSourceErrorMessage = ex.Message; if (LastFrameUnmanaged != null) { try { lock (_sync) { LastFrameUnmanaged.Dispose(); LastFrameUnmanaged = null; } } catch { } } err = true; } catch (Exception ex) { if (LastFrameUnmanaged != null) { try { lock (_sync) { LastFrameUnmanaged.Dispose(); LastFrameUnmanaged = null; } } catch { } } MainForm.LogExceptionToFile(ex); err = true; } if (gCam != null) { gCam.Dispose(); } if (bmp != null) { bmp.Dispose(); } if (g != null) { g.Dispose(); } if (bmOrig != null) { bmOrig.Dispose(); } tsBrush.Dispose(); sbTs.Dispose(); if (err) { return; } if (MotionDetector != null && !CW.Calibrating && MotionDetector.MotionProcessingAlgorithm is BlobCountingObjectsProcessing) { try { var blobcounter = (BlobCountingObjectsProcessing)MotionDetector.MotionProcessingAlgorithm; //tracking var pCenter = new Point(Width / 2, Height / 2); if (!CW.PTZNavigate && CW.Camobject.settings.ptzautotrack && blobcounter.ObjectsCount > 0 && blobcounter.ObjectsCount < 4 && !CW.Ptzneedsstop) { List <Rectangle> recs = blobcounter.ObjectRectangles.OrderByDescending(p => p.Width * p.Height).ToList(); Rectangle rec = recs.First(); //get center point var prec = new Point(rec.X + rec.Width / 2, rec.Y + rec.Height / 2); double dratiomin = 0.6; prec.X = prec.X - pCenter.X; prec.Y = prec.Y - pCenter.Y; if (CW.Camobject.settings.ptzautotrackmode == 1) //vert only { prec.X = 0; dratiomin = 0.3; } if (CW.Camobject.settings.ptzautotrackmode == 2) //horiz only { prec.Y = 0; dratiomin = 0.3; } double angle = Math.Atan2(-prec.Y, -prec.X); if (CW.Camobject.settings.ptzautotrackreverse) { angle = angle - Math.PI; if (angle < 0 - Math.PI) { angle += 2 * Math.PI; } } double dist = Math.Sqrt(Math.Pow(prec.X, 2.0d) + Math.Pow(prec.Y, 2.0d)); double maxdist = Math.Sqrt(Math.Pow(Width / 2, 2.0d) + Math.Pow(Height / 2, 2.0d)); double dratio = dist / maxdist; if (dratio > dratiomin) { CW.PTZ.SendPTZDirection(angle, 1); CW.LastAutoTrackSent = DateTime.Now; CW.Ptzneedsstop = true; } } } catch (Exception ex) { MainForm.LogExceptionToFile(ex); } } if (NewFrame != null && LastFrameUnmanaged != null) { LastFrameNull = false; NewFrame(this, new EventArgs()); } } }
private void Awake() { crop = GetComponent <Crop>(); }
private void captureHand(UnmanagedImage mask, Rectangle rect, PictureBox pbArm, PictureBox pbHand) { Crop c = new Crop(rect); var handImage = c.Apply(mask); var ps = handImage.Collect16bppPixelValues(handImage.CollectActivePixels()); if (ps.Length > 0) { ushort max = Matrix.Max(ps); LevelsLinear16bpp levels = new LevelsLinear16bpp(); levels.InGray = new IntRange(0, max); levels.OutGray = new IntRange(0, 65535); levels.ApplyInPlace(handImage); // pbArm.Image = handImage.ToManagedImage(); double cutoff = 30000; Threshold th = new Threshold((int)cutoff); var handMask = th.Apply(handImage); var handMask8bit = AForge.Imaging.Image.Convert16bppTo8bpp(handMask.ToManagedImage()); BlobCounter bch = new BlobCounter(); bch.ObjectsOrder = ObjectsOrder.Area; bch.ProcessImage(handMask8bit); var blob = bch.GetObjectsInformation(); if (blob.Length > 0) { Intersect inters = new Intersect(); inters.UnmanagedOverlayImage = handMask; inters.ApplyInPlace(handImage); Crop ch = new Crop(blob[0].Rectangle); handImage = ch.Apply(handImage); ResizeNearestNeighbor res = new ResizeNearestNeighbor(25, 25); handImage = res.Apply(handImage); var leftHand = AForge.Imaging.Image.Convert16bppTo8bpp(handImage.ToManagedImage()); pbHand.Image = leftHand; } } }
public void SaveResizedCrop(Crop crop, Size size, byte[] fileBytes, string fileUrl) { Size newSize = CalculateDimensions(crop.Size, size); SaveFile(fileBytes, fileUrl, newSize, crop.ContentType); }
/// <summary> /// Constructs a new <see cref="MatchingTracker"/> object tracker. /// </summary> /// public MatchingTracker() { matcher = new ExhaustiveTemplateMatching(0); crop = new Crop(Rectangle.Empty); trackingObject = new TrackingObject(); }
// Clears a slot public void Clear() { item = null; count = 0; }
// Sets up the item in the item slot public void Set(Crop item, int count) { this.item = item; this.count = count; }
public static void cropNewDay(PlanterBox p, Crop c, int state, int fertilizer, int xTile, int yTile, GameLocation environment) { if (p.greenHouseEffect == false) { if ((c.dead.Value || !c.seasonsToGrowIn.Contains(Game1.currentSeason))) { c.dead.Value = true; } } if (state == 1) { c.dayOfCurrentPhase.Value++; // Log.AsyncG("DaY OF CURRRENT PHASE BISCUITS!"+c.dayOfCurrentPhase); // Log.AsyncC(c.currentPhase); if (c.dayOfCurrentPhase.Value >= c.phaseDays[c.currentPhase.Value]) { c.currentPhase.Value++; c.dayOfCurrentPhase.Value = 0; } //c.dayOfCurrentPhase = c.fullyGrown ? c.dayOfCurrentPhase - 1 : Math.Min(c.dayOfCurrentPhase + 1, c.phaseDays.Count > 0 ? c.phaseDays[Math.Min(c.phaseDays.Count - 1, c.currentPhase)] : 0); if (c.dayOfCurrentPhase.Value >= (c.phaseDays.Count > 0 ? c.phaseDays[Math.Min(c.phaseDays.Count - 1, c.currentPhase.Value)] : 0) && c.currentPhase.Value < c.phaseDays.Count - 1) { c.currentPhase.Value = c.currentPhase.Value + 1; c.dayOfCurrentPhase.Value = 0; } while (c.currentPhase.Value < c.phaseDays.Count - 1 && c.phaseDays.Count > 0 && c.phaseDays[c.currentPhase.Value] <= 0) { c.currentPhase.Value = c.currentPhase.Value + 1; } if (c.rowInSpriteSheet.Value == 23 && c.phaseToShow.Value == -1 && c.currentPhase.Value > 0) { c.phaseToShow.Value = Game1.random.Next(1, 7); } if (c.currentPhase.Value == c.phaseDays.Count - 1 && (c.indexOfHarvest.Value == 276 || c.indexOfHarvest.Value == 190 || c.indexOfHarvest.Value == 254) && new Random((int)Game1.uniqueIDForThisGame + (int)Game1.stats.DaysPlayed + xTile * 2000 + yTile).NextDouble() < 0.01) { for (int index1 = xTile - 1; index1 <= xTile + 1; ++index1) { for (int index2 = yTile - 1; index2 <= yTile + 1; ++index2) { Vector2 key = new Vector2((float)index1, (float)index2); if (!environment.terrainFeatures.ContainsKey(key) || !(environment.terrainFeatures[key] is HoeDirt) || ((environment.terrainFeatures[key] as HoeDirt).crop == null || (environment.terrainFeatures[key] as HoeDirt).crop.indexOfHarvest != c.indexOfHarvest)) { return; } } } for (int index1 = xTile - 1; index1 <= xTile + 1; ++index1) { for (int index2 = yTile - 1; index2 <= yTile + 1; ++index2) { Vector2 index3 = new Vector2((float)index1, (float)index2); (environment.terrainFeatures[index3] as HoeDirt).crop = (Crop)null; } } // (environment as Farm).resourceClumps.Add((ResourceClump)new GiantCrop(c.indexOfHarvest, new Vector2((float)(xTile - 1), (float)(yTile - 1)))); } } if (c.fullyGrown.Value && c.dayOfCurrentPhase.Value > 0 || (c.currentPhase.Value < c.phaseDays.Count - 1 || c.rowInSpriteSheet.Value != 23)) { return; } Vector2 index = new Vector2((float)xTile, (float)yTile); environment.objects.Remove(index); string season = Game1.currentSeason; switch (c.whichForageCrop.Value) { case 495: season = "spring"; break; case 496: season = "summer"; break; case 497: season = "fall"; break; case 498: season = "winter"; break; } StardewValley.Object o = new StardewValley.Object(index, c.getRandomWildCropForSeason(season), 1); o.IsSpawnedObject = true; o.CanBeGrabbed = true; environment.objects.Add(index, o); if (environment.terrainFeatures[index] == null || !(environment.terrainFeatures[index] is HoeDirt)) { return; } (environment.terrainFeatures[index] as HoeDirt).crop = (Crop)null; }
/********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="obj">The underlying in-game object.</param> /// <param name="tilePosition">The object's tile position in the current location (if applicable).</param> /// <param name="reflectionHelper">Simplifies access to private game code.</param> public CropTarget(TerrainFeature obj, Vector2?tilePosition, IReflectionHelper reflectionHelper) : base(TargetType.Crop, obj, tilePosition) { this.Crop = ((HoeDirt)obj).crop; this.Reflection = reflectionHelper; }
/// <summary>Get the custom fields for a crop.</summary> /// <param name="crop">The crop to represent.</param> /// <param name="isSeed">Whether the crop being displayed is for an unplanted seed.</param> private IEnumerable <ICustomField> GetCropFields(Crop crop, bool isSeed) { if (crop == null) { yield break; } var data = new CropDataParser(crop, isPlanted: !isSeed); // add next-harvest field if (!isSeed) { // get next harvest SDate nextHarvest = data.GetNextHarvest(); // generate field string summary; if (data.CanHarvestNow) { summary = I18n.Generic_Now(); } else if (!Game1.currentLocation.IsGreenhouse && !data.Seasons.Contains(nextHarvest.Season)) { summary = I18n.Crop_Harvest_TooLate(date: this.Stringify(nextHarvest)); } else { summary = $"{this.Stringify(nextHarvest)} ({this.GetRelativeDateStr(nextHarvest)})"; } yield return(new GenericField(I18n.Crop_Harvest(), summary)); } // crop summary { List <string> summary = new List <string>(); // harvest summary.Add(data.HasMultipleHarvests ? I18n.Crop_Summary_HarvestOnce(daysToFirstHarvest: data.DaysToFirstHarvest) : I18n.Crop_Summary_HarvestMulti(daysToFirstHarvest: data.DaysToFirstHarvest, daysToNextHarvests: data.DaysToSubsequentHarvest) ); // seasons summary.Add(I18n.Crop_Summary_Seasons(seasons: string.Join(", ", I18n.GetSeasonNames(data.Seasons)))); // drops if (crop.minHarvest != crop.maxHarvest && crop.chanceForExtraCrops.Value > 0) { summary.Add(I18n.Crop_Summary_DropsXToY(min: crop.minHarvest.Value, max: crop.maxHarvest.Value, percent: (int)Math.Round(crop.chanceForExtraCrops.Value * 100, 2))); } else if (crop.minHarvest.Value > 1) { summary.Add(I18n.Crop_Summary_DropsX(count: crop.minHarvest.Value)); } // crop sale price Item drop = data.GetSampleDrop(); summary.Add(I18n.Crop_Summary_SellsFor(price: GenericField.GetSaleValueString(this.GetSaleValue(drop, false), 1))); // generate field yield return(new GenericField(I18n.Crop_Summary(), "-" + string.Join($"{Environment.NewLine}-", summary))); } }
/*CannyEdgeDetector Edgeimage = new CannyEdgeDetector(); * Bitmap edge = Edgeimage.Apply(boundedimage); * pictureBox2.Image = edge;*/ //for(i=1;i<graycolor.Height;i++) //{ // Console.WriteLine(tempy[i]); //} public List <Bitmap> Segment(Bitmap boundedimage) { /*---------------------SEGMENTATION--------------------------*/ xmax = boundedimage.Width; ymax = boundedimage.Height; int[] xaxis = new int[xmax]; int[] yaxis = new int[ymax]; int[] tempx = new int[xmax]; int[] tempy = new int[ymax]; int y, x; int iy = 1; int ix = 1; yaxis[0] = 0; //for (y = 1; y < ymax; y++) //{ // for (x = 1; x < xmax; x++) // { // if (boundedimage.GetPixel(x, y).Name == "ff000000") // { // tempy[iy++] = y; // break; // } // } //} //i = 1; //for (int p = 1; p < ymax - 1 ; p++) //{ // if ((tempy[p - 1] != tempy[p] - 1) || (tempy[p] + 1 != tempy[p + 1])) // { // yaxis[i++] = tempy[p] + 1; // } //} yaxis[0] = 0; yaxis[1] = boundedimage.Height; for (x = 1; x < xmax; x++) { for (y = 1; y < ymax; y++) { if (boundedimage.GetPixel(x, y).Name == "ff000000") { tempx[ix++] = x; break; } } } i = 1; for (int p = 1; p < xmax; p++) { if ((tempx[p - 1] != tempx[p] - 1) || (tempx[p] + 1 != tempx[p + 1])) { xaxis[i] = tempx[p] + 1; i++; } } Console.WriteLine("helllooooo_check xaxis"); Console.WriteLine(xaxis.Length); Console.WriteLine("helllooooo"); for (i = 0; i < ymax; i++) { Console.WriteLine(yaxis[i] + " " + xaxis[i]); } // Console.WriteLine(xaxis[2]+" "+ yaxis[2] + " " + (xaxis[3] - xaxis[2] )+ " " + (yaxis[3] - yaxis[2])); int k; List <Bitmap> croppedImg = new List <Bitmap>(); Bitmap temp; Console.WriteLine("helllooooo-check"); Console.WriteLine(xaxis.Length); for (i = 0, j = 1, k = 0; xaxis[j] < xaxis.Length + 1; k++, i = i + 2, j = j + 2) { Console.WriteLine(xaxis[i] + " " + yaxis[0] + " " + (xaxis[j] - xaxis[i]) + " " + (yaxis[1] - yaxis[0])); try { Crop filter1 = new Crop(new Rectangle(xaxis[i], yaxis[0], (xaxis[j] - xaxis[i]), (yaxis[1] - yaxis[0]))); temp = filter1.Apply(boundedimage); croppedImg.Add(temp); croppedImg[k].Save(@"E:\Works\Machine Learning - OCR\Samples\Sample" + k + ".jpg"); }catch { break; } } pictureBox3.Image = croppedImg[0]; pictureBox4.Image = croppedImg[1]; //pictureBox5.Image = croppedImg[2]; // pictureBox6.Image = croppedImg[3]; //pictureBox6.Image = croppedImg[4]; return(croppedImg); }
/********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="gameHelper">Provides utility methods for interacting with the game code.</param> /// <param name="progressionMode">Whether to only show content once the player discovers it.</param> /// <param name="highlightUnrevealedGiftTastes">Whether to highlight item gift tastes which haven't been revealed in the NPC profile.</param> /// <param name="item">The underlying target.</param> /// <param name="context">The context of the object being looked up.</param> /// <param name="knownQuality">Whether the item quality is known. This is <c>true</c> for an inventory item, <c>false</c> for a map object.</param> /// <param name="getCropSubject">Get a lookup subject for a crop.</param> /// <param name="fromCrop">The crop associated with the item (if applicable).</param> public ItemSubject(GameHelper gameHelper, bool progressionMode, bool highlightUnrevealedGiftTastes, Item item, ObjectContext context, bool knownQuality, Func <Crop, ObjectContext, ISubject> getCropSubject, Crop fromCrop = null) : base(gameHelper) { this.ProgressionMode = progressionMode; this.HighlightUnrevealedGiftTastes = highlightUnrevealedGiftTastes; this.Target = item; this.DisplayItem = this.GetMenuItem(item); this.FromCrop = fromCrop; if ((item as SObject)?.Type == "Seeds" && fromCrop == null) // fromCrop == null to exclude planted coffee beans { this.SeedForCrop = new Crop(item.ParentSheetIndex, 0, 0); } this.Context = context; this.KnownQuality = knownQuality; this.GetCropSubject = getCropSubject; this.Initialize(this.DisplayItem.DisplayName, this.GetDescription(this.DisplayItem), this.GetTypeValue(this.DisplayItem)); }
/// <summary> /// directly crop original image without scaling it /// final image aspect ratio is equal to given new width/height /// </summary> /// <param name="img"></param> /// <param name="newWidth"></param> /// <param name="newHeight"></param> /// <param name="spot">target spot to crop and save</param> /// <returns></returns> public static Image Crop(Image img, int newWidth, int newHeight, TargetSpot spot = TargetSpot.Center) { var resize = new Crop(img.Size, new Size(newWidth, newHeight), spot); return(Resize(img, resize.SourceRect, resize.TargetRect)); }
/// <summary>Get the data to display for this subject.</summary> public override IEnumerable <ICustomField> GetData() { // get data Item item = this.Target; ItemType itemType = item.GetItemType(); SObject obj = item as SObject; bool isCrop = this.FromCrop != null; bool isSeed = this.SeedForCrop != null; bool isDeadCrop = this.FromCrop?.dead.Value == true; bool canSell = obj?.canBeShipped() == true || this.Metadata.Shops.Any(shop => shop.BuysCategories.Contains(item.Category)); // get overrides bool showInventoryFields = !this.IsSpawnedStoneNode(); { ObjectData objData = this.Metadata.GetObject(item, this.Context); if (objData != null) { this.Name = objData.NameKey != null?I18n.GetByKey(objData.NameKey) : this.Name; this.Description = objData.DescriptionKey != null?I18n.GetByKey(objData.DescriptionKey) : this.Description; this.Type = objData.TypeKey != null?I18n.GetByKey(objData.TypeKey) : this.Type; showInventoryFields = objData.ShowInventoryFields ?? showInventoryFields; } } // don't show data for dead crop if (isDeadCrop) { yield return(new GenericField(I18n.Crop_Summary(), I18n.Crop_Summary_Dead())); yield break; } // crop fields foreach (ICustomField field in this.GetCropFields(this.FromCrop ?? this.SeedForCrop, isSeed)) { yield return(field); } // indoor pot crop if (obj is IndoorPot pot) { Crop potCrop = pot.hoeDirt.Value.crop; if (potCrop != null) { Item drop = this.GameHelper.GetObjectBySpriteIndex(potCrop.indexOfHarvest.Value); yield return(new LinkField(I18n.Item_Contents(), drop.DisplayName, () => this.GetCropSubject(potCrop, ObjectContext.World))); } } // machine output foreach (ICustomField field in this.GetMachineOutputFields(obj)) { yield return(field); } // music blocks if (obj?.Name == "Flute Block") { yield return(new GenericField(I18n.Item_MusicBlock_Pitch(), I18n.Generic_Ratio(value: obj.preservedParentSheetIndex.Value, max: 2300))); } else if (obj?.Name == "Drum Block") { yield return(new GenericField(I18n.Item_MusicBlock_DrumType(), I18n.Generic_Ratio(value: obj.preservedParentSheetIndex.Value, max: 6))); } // item if (showInventoryFields) { // needed for foreach (ICustomField field in this.GetNeededForFields(obj)) { yield return(field); } // sale data if (canSell && !isCrop) { // sale price string saleValueSummary = GenericField.GetSaleValueString(this.GetSaleValue(item, this.KnownQuality), item.Stack); yield return(new GenericField(I18n.Item_SellsFor(), saleValueSummary)); // sell to List <string> buyers = new List <string>(); if (obj?.canBeShipped() == true) { buyers.Add(I18n.Item_SellsTo_ShippingBox()); } buyers.AddRange( from shop in this.Metadata.Shops where shop.BuysCategories.Contains(item.Category) let name = I18n.GetByKey(shop.DisplayKey).ToString() orderby name select name ); yield return(new GenericField(I18n.Item_SellsTo(), string.Join(", ", buyers))); } // clothing if (item is Clothing clothing) { yield return(new GenericField(I18n.Item_CanBeDyed(), this.Stringify(clothing.dyeable.Value))); } // gift tastes IDictionary <GiftTaste, GiftTasteModel[]> giftTastes = this.GetGiftTastes(item); yield return(new ItemGiftTastesField(I18n.Item_LovesThis(), giftTastes, GiftTaste.Love, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes)); yield return(new ItemGiftTastesField(I18n.Item_LikesThis(), giftTastes, GiftTaste.Like, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes)); if (this.ProgressionMode || this.HighlightUnrevealedGiftTastes) { yield return(new ItemGiftTastesField(I18n.Item_NeutralAboutThis(), giftTastes, GiftTaste.Neutral, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes)); yield return(new ItemGiftTastesField(I18n.Item_DislikesThis(), giftTastes, GiftTaste.Dislike, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes)); yield return(new ItemGiftTastesField(I18n.Item_HatesThis(), giftTastes, GiftTaste.Hate, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes)); } } // recipes if (showInventoryFields) { switch (itemType) { // for ingredient case ItemType.Object: { RecipeModel[] recipes = this.GameHelper.GetRecipesForIngredient(this.DisplayItem).ToArray(); if (recipes.Any()) { yield return(new RecipesForIngredientField(this.GameHelper, I18n.Item_Recipes(), item, recipes)); } } break; // for machine case ItemType.BigCraftable: { RecipeModel[] recipes = this.GameHelper.GetRecipesForMachine(this.DisplayItem as SObject).ToArray(); if (recipes.Any()) { yield return(new RecipesForMachineField(this.GameHelper, I18n.Item_Recipes(), recipes)); } } break; } } // fish if (item.Category == SObject.FishCategory) { // spawn rules yield return(new FishSpawnRulesField(this.GameHelper, I18n.Item_FishSpawnRules(), item.ParentSheetIndex)); // fish pond data foreach (FishPondData fishPondData in Game1.content.Load <List <FishPondData> >("Data\\FishPondData")) { if (!fishPondData.RequiredTags.All(item.HasContextTag)) { continue; } int minChanceOfAnyDrop = (int)Math.Round(Utility.Lerp(0.15f, 0.95f, 1 / 10f) * 100); int maxChanceOfAnyDrop = (int)Math.Round(Utility.Lerp(0.15f, 0.95f, FishPond.MAXIMUM_OCCUPANCY / 10f) * 100); string preface = I18n.Building_FishPond_Drops_Preface(chance: I18n.Generic_Range(min: minChanceOfAnyDrop, max: maxChanceOfAnyDrop)); yield return(new FishPondDropsField(this.GameHelper, I18n.Item_FishPondDrops(), -1, fishPondData, preface)); break; } } // fence if (item is Fence fence) { string healthLabel = I18n.Item_FenceHealth(); // health if (Game1.getFarm().isBuildingConstructed(Constant.BuildingNames.GoldClock)) { yield return(new GenericField(healthLabel, I18n.Item_FenceHealth_GoldClock())); } else { float maxHealth = fence.isGate.Value ? fence.maxHealth.Value * 2 : fence.maxHealth.Value; float health = fence.health.Value / maxHealth; double daysLeft = Math.Round(fence.health.Value * this.Constants.FenceDecayRate / 60 / 24); double percent = Math.Round(health * 100); yield return(new PercentageBarField(healthLabel, (int)fence.health.Value, (int)maxHealth, Color.Green, Color.Red, I18n.Item_FenceHealth_Summary(percent: (int)percent, count: (int)daysLeft))); } } // movie ticket if (obj?.ParentSheetIndex == 809 && !obj.bigCraftable.Value) { MovieData movie = MovieTheater.GetMovieForDate(Game1.Date); if (movie == null) { yield return(new GenericField(I18n.Item_MovieTicket_MovieThisWeek(), I18n.Item_MovieTicket_MovieThisWeek_None())); } else { // movie this week yield return(new GenericField(I18n.Item_MovieTicket_MovieThisWeek(), new IFormattedText[] { new FormattedText(movie.Title, bold: true), new FormattedText(Environment.NewLine), new FormattedText(movie.Description) })); // movie tastes IDictionary <GiftTaste, string[]> tastes = this.GameHelper.GetMovieTastes() .GroupBy(entry => entry.Value) .ToDictionary(group => group.Key, group => group.Select(p => p.Key.Name).OrderBy(p => p).ToArray()); yield return(new MovieTastesField(I18n.Item_MovieTicket_LovesMovie(), tastes, GiftTaste.Love)); yield return(new MovieTastesField(I18n.Item_MovieTicket_LikesMovie(), tastes, GiftTaste.Like)); yield return(new MovieTastesField(I18n.Item_MovieTicket_DislikesMovie(), tastes, GiftTaste.Dislike)); } } // dyes if (showInventoryFields) { yield return(new ColorField(I18n.Item_ProducesDye(), item)); } // owned and times cooked/crafted if (showInventoryFields && !isCrop) { // owned yield return(new GenericField(I18n.Item_NumberOwned(), I18n.Item_NumberOwned_Summary(count: this.GameHelper.CountOwnedItems(item)))); // times crafted RecipeModel[] recipes = this.GameHelper .GetRecipes() .Where(recipe => recipe.OutputItemIndex == this.Target.ParentSheetIndex && recipe.OutputItemType == this.Target.GetItemType()) .ToArray(); if (recipes.Any()) { string label = recipes.First().Type == RecipeType.Cooking ? I18n.Item_NumberCooked() : I18n.Item_NumberCrafted(); int timesCrafted = recipes.Sum(recipe => recipe.GetTimesCrafted(Game1.player)); if (timesCrafted >= 0) // negative value means not available for this recipe type { yield return(new GenericField(label, I18n.Item_NumberCrafted_Summary(count: timesCrafted))); } } } // see also crop bool seeAlsoCrop = isSeed && item.ParentSheetIndex != this.SeedForCrop.indexOfHarvest.Value && // skip seeds which produce themselves (e.g. coffee beans) !(item.ParentSheetIndex >= 495 && item.ParentSheetIndex <= 497) && // skip random seasonal seeds item.ParentSheetIndex != 770; // skip mixed seeds if (seeAlsoCrop) { Item drop = this.GameHelper.GetObjectBySpriteIndex(this.SeedForCrop.indexOfHarvest.Value); yield return(new LinkField(I18n.Item_SeeAlso(), drop.DisplayName, () => this.GetCropSubject(this.SeedForCrop, ObjectContext.Inventory))); } }
/// <summary> /// Draw it! /// </summary> private void drawAdvancedToolip(object sender, EventArgs e) { if (hoverItem == null) { return; } string sellForAmount = ""; string harvestPrice = ""; int truePrice = getTruePrice(hoverItem); if (truePrice > 0 && hoverItem.Name != "Scythe") { sellForAmount = "\n " + truePrice / 2; if (hoverItem.canStackWith(hoverItem) && hoverItem.getStack() > 1) { sellForAmount += $" ({ truePrice / 2 * hoverItem.getStack() })"; } } bool isDrawingHarvestPrice = false; // Adds the price of the fully grown crop to the display text only if it is a seed if (hoverItem is StardewValley.Object && ((StardewValley.Object)hoverItem).type == "Seeds" && sellForAmount != "") { if (hoverItem.Name != "Mixed Seeds" || hoverItem.Name != "Winter Seeds") { var crop = new Crop(hoverItem.parentSheetIndex, 0, 0); var debris = new Debris(crop.indexOfHarvest, Game1.player.position, Game1.player.position); var item = new StardewValley.Object(debris.chunkType, 1); harvestPrice += $" { item.price }"; isDrawingHarvestPrice = true; } } string advancedTitle = hoverItem.Name + sellForAmount + harvestPrice; // Draw tooltip Vector2 iconPosition = drawToolTip(Game1.spriteBatch, hoverItem.getDescription(), advancedTitle, hoverItem, false, -1, 0, -1, -1, null, -1); float iconPositionX = iconPosition.X; float iconPositionY = iconPosition.Y; // Reposition coin and harvest icon iconPositionX += 30; iconPositionY -= 10; // Draw icons inside description text if (sellForAmount != "") { // Draw coin icon Game1.spriteBatch.Draw(Game1.debrisSpriteSheet, new Vector2(iconPositionX, iconPositionY), new Rectangle?(Game1.getSourceRectForStandardTileSheet(Game1.debrisSpriteSheet, 8, 16, 16)), Color.White, 0f, new Vector2(8f, 8f), ( float )Game1.pixelZoom, SpriteEffects.None, 0.95f); // Draw harvest icon if (isDrawingHarvestPrice) { var spriteRectangle = new Rectangle(60, 428, 10, 10); Game1.spriteBatch.Draw(Game1.mouseCursors, new Vector2(iconPositionX + Game1.dialogueFont.MeasureString(sellForAmount).X - 10, iconPositionY - 20), spriteRectangle, Color.White, 0.0f, Vector2.Zero, ( float )Game1.pixelZoom, SpriteEffects.None, 0.85f); } } // Draw bundle info foreach (var bundleType in prunedRequiredBundles) { if (bundleType.Value.Contains(hoverItem.parentSheetIndex)) { int xPos = ( int )iconPositionX - 64; int yPos = ( int )iconPositionY - 110; int bgPositionX = xPos + 52; int bgPositionY = yPos - 2; int totalWidth = 288; int height = 36; int amountOfSections = 36; int sectionWidth = totalWidth / amountOfSections; int amountOfSectionsWithoutAlpha = 6; for (int i = 0; i < amountOfSections; i++) { float alpha; if (i < amountOfSectionsWithoutAlpha) { alpha = 0.92f; } else { alpha = 0.92f - (i - amountOfSectionsWithoutAlpha) * (1f / (amountOfSections - amountOfSectionsWithoutAlpha)); } Game1.spriteBatch.Draw(Game1.staminaRect, new Rectangle(bgPositionX + (sectionWidth * i), bgPositionY, sectionWidth, height), Color.Crimson * alpha); } Game1.spriteBatch.DrawString(Game1.dialogueFont, bundleType.Key, new Vector2(xPos + 72, yPos), Color.White); bundleIcon.bounds.X = xPos + 16; bundleIcon.bounds.Y = yPos; bundleIcon.scale = 3f; bundleIcon.draw(Game1.spriteBatch); break; } } restoreMenuState(); }
public static void Prefix(StardewValley.Objects.IndoorPot __instance) { crop = __instance.hoeDirt.Value?.crop; }
public HoeDirt(int startingState, Crop crop) : this() { state.Value = startingState; this.crop = crop; }
private void DrawCrop(SpriteBatch spriteBatch, Crop crop) { spriteBatch.Begin(); Vector2 v = new Vector2(OffsetX, OffsetY); if (crop.Dimensions.Y > 32) v.Y -= (crop.Dimensions.Y - 32); if (crop.Dimensions.X > 32) v.X -= (crop.Dimensions.X - 32) / 2; spriteBatch.Draw(crop.Texture, crop.Coordinates + v, new Rectangle((crop.CurrentStage - 1) * crop.Dimensions.X, 0, crop.Dimensions.X, crop.Dimensions.Y), Color.White); spriteBatch.End(); }
void searchSolution(Bitmap rgb) { long start = DateTime.Now.Ticks / 10000; Globals.FRAMES_PROCESSED_TRIANGULAR++; int com_x_sum = 0, com_y_sum = 0, com_x_y_point_count = 0; Globals.HARVEST_SIGN_ID++; //if (redTestPoints == null) // calculateRedTestPoints(); Bitmap bmp = sf.Apply(rgb); GeoTransChromosome sampleChromosome = new GeoTransChromosome(bmp, sf, this, null); Population tmpPopulation = new Population(Constants.GA_POPULATION_SIZE, sampleChromosome, sampleChromosome, new EliteSelection() ); tmpPopulation.MutationRate = Constants.GA_MUTATION_RATE; tmpPopulation.CrossoverRate = Constants.GA_CROSSOVER_RATE; if (population == null || population.BestChromosome == null || population.BestChromosome.Fitness < RS_THRESHOLD / 4) { // fresh population } else { // half from previous for (int j = 0; j < tmpPopulation.Size / 2; j++) { ((GeoTransChromosome)tmpPopulation[j]).copyContent((GeoTransChromosome)population[j]); } } population = tmpPopulation; Graphics gg = null; /* Bitmap bmp_x = null; if (1!=1) { bmp_x = new Bitmap(Constants.IMAGE_WIDTH, Constants.IMAGE_HEIGHT * 2, PixelFormat.Format24bppRgb); gg = Graphics.FromImage(bmp_x); gg.DrawImage(bmp, 0, 0); gg.DrawImage(rgb, 0, Constants.IMAGE_HEIGHT); for (int x = 0; x < population.Size; x++) { GeoTransChromosome chromo = (GeoTransChromosome)population[x]; gg.DrawRectangle(Pens.Cyan, chromo.X, chromo.Y, 1, 1); } } */ int i = 0; do { long start_epoch = DateTime.Now.Ticks / 10000; Globals.FRAMES_PROCESSED_GA_RUNEPOCH++; // run one epoch of genetic algorithm population.RunEpoch(); if (Constants.EVALUATE_TIME_ENABLED) { int x = (int)(DateTime.Now.Ticks / 10000 - start_epoch); if (x >= 0) { Globals.TIME_GA_RUNEPOCH_MIN = x < Globals.TIME_GA_RUNEPOCH_MIN ? x : Globals.TIME_GA_RUNEPOCH_MIN; Globals.TIME_GA_RUNEPOCH_MAX = x > Globals.TIME_GA_RUNEPOCH_MAX ? x : Globals.TIME_GA_RUNEPOCH_MAX; Globals.TIME_GA_RUNEPOCH_TOTAL += x; } } i++; } while (i < Constants.GA_NUMBER_ITERATIONS); GeoTransChromosome bestChromo = null; float rs = 0; if (population.BestChromosome != null && population.BestChromosome.Fitness > RS_THRESHOLD) { bestChromo = (GeoTransChromosome)population.BestChromosome; int rx = bestChromo.X, ry = bestChromo.Y, rr = bestChromo.Width; rs = (float)bestChromo.Fitness; if (Constants.HARVEST_TYPE == Constants.HarvestType.harvestAll || Constants.HARVEST_TYPE == Constants.HarvestType.harvestMisses) { rgb.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_0.bmp"); bmp.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_1.bmp"); } // findTriangle(bestChromo.X, bestChromo.Y, bmp, ref rx, ref ry, ref rr, ref rs); if (rs < RS_THRESHOLD || rr==0) { if (gg != null) { gg.DrawRectangle(Pens.Red, bestChromo.X - 1, bestChromo.Y - 1, 3, 3); gg.DrawRectangle(Pens.Red, bestChromo.X - bestChromo.Width / 2, bestChromo.Y - bestChromo.Width / 2, bestChromo.Width, bestChromo.Width); } bestChromo = null; } else { rr = (int)(Constants.CAPTURE_RESIZE_TRIANGLE * rr); int xx = (int)(rr * Math.Cos(Math.PI * 30 / 180)); // üçgenin kenarı: 2 . xx int yy = (int)(rr * Math.Sin(Math.PI * 30 / 180)); // üçgenin yüksekliği: 3 . yy int x_left = rx - xx; int y_top = ry - (2 * yy) - ((3*yy)/10); rgb = new Crop(new Rectangle(x_left, y_top, (x_left + 2 * xx > rgb.Width - 1 ? rgb.Width - 1 - x_left : 2 * xx), (y_top + 2 * xx > rgb.Height - 1 ? rgb.Height - 1 - y_top : 2 * xx))).Apply(rgb); if (gg != null) { gg.DrawImage(rgb, 1, Constants.IMAGE_HEIGHT + 1); gg.DrawRectangle(Pens.DarkOrchid, rx - 1, ry - 1, 3, 3); gg.DrawRectangle(Pens.Green, x_left, y_top, rgb.Width, rgb.Height); } rgb = new ResizeBicubic(Constants.SIGN_WIDTH, Constants.SIGN_HEIGHT).Apply(rgb); if (panel != null) { Graphics g = panel.getPanelGraphics(); g.DrawRectangle(Pens.Silver, 5, 4, Constants.SIGN_WIDTH, Constants.SIGN_HEIGHT); g.DrawImage(rgb, new Point(5, 4)); } if (Constants.HARVEST_TYPE == Constants.HarvestType.harvestAll || Constants.HARVEST_TYPE == Constants.HarvestType.harvestMisses) rgb.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_3_" +rs+ ".bmp"); rgb = AutoBrightnessProcessor.autoBrightness(rgb, Rectangle.Empty, Constants.AUTOBRIGHTNESS_BASE_LUM); if (Constants.HARVEST_TYPE == Constants.HarvestType.harvestAll || Constants.HARVEST_TYPE == Constants.HarvestType.harvestMisses) rgb.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_4.bmp"); int dynamic_gray = 0; if (Constants.LABELING_TYPE == Constants.LabelingType.redBlackWhite) rgb = new ColorLabelFilter(new Color[] { Color.FromArgb(255, 0, 0), Color.White, Color.Black }, true).Apply(rgb); else if (Constants.LABELING_TYPE == Constants.LabelingType.blackAndWhite) { rgb = new ColorLabelFilter(new Color[] { Color.White, Color.FromArgb(dynamic_gray, dynamic_gray, dynamic_gray) }, true).Apply(rgb); } if (Constants.HARVEST_TYPE == Constants.HarvestType.harvestAll || Constants.HARVEST_TYPE == Constants.HarvestType.harvestMisses) rgb.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_5.bmp"); int start_x = 0, start_y = 0; int y = 0; for (; y < Constants.SIGN_HEIGHT && (start_x+start_y)==0; y++) { for (int x = 0; x < Constants.SIGN_WIDTH; x++) { Color clr = rgb.GetPixel(x, y); if (clr.R == 0) { start_x = x; start_y = y; break; } } } PointedColorFloodFill filter = new PointedColorFloodFill(); filter.Tolerance = Color.FromArgb(0, 0, 0); filter.FillColor = Color.FromArgb(255, 255, 255); filter.StartingPoint = new Point(start_x, start_y); Bitmap rgb_flood_fill = filter.Apply(rgb); int black_region_found_at_center = 0; y = 4 * (Constants.SIGN_HEIGHT / 10); for (int x = 4 * (Constants.SIGN_WIDTH / 10); x < 6 * (Constants.SIGN_WIDTH / 10); x += 2) { Color clr = rgb_flood_fill.GetPixel(x, y); if (clr.R == 0) { black_region_found_at_center++; } } if (black_region_found_at_center < 8) { y = 6 * (Constants.SIGN_HEIGHT / 10); for (int x = 4 * (Constants.SIGN_WIDTH / 10); x < 6 * (Constants.SIGN_WIDTH / 10); x += 2) { Color clr = rgb_flood_fill.GetPixel(x, y); if (clr.R == 0) { black_region_found_at_center++; } } } if (black_region_found_at_center >= 5) { rgb = rgb_flood_fill; } BitmapData image_data = rgb.LockBits(new Rectangle(0, 0, rgb.Width, rgb.Height), ImageLockMode.ReadWrite, rgb.PixelFormat); int bpp = 3; int nOffset = image_data.Stride - rgb.Width * bpp; System.IntPtr Scan0 = image_data.Scan0; unsafe { byte* p = (byte*)Scan0; for (y = 0; y < Constants.SIGN_HEIGHT; y++) { // for each pixel for (int x = 0; x < Constants.SIGN_WIDTH; x++, p += bpp) { if (y >= Constants.SIGN_HEIGHT - 12 || y <= 14 || x >= Constants.SIGN_WIDTH - 12 || x <= 12 || (x <= Constants.SIGN_WIDTH / 2 && y <= (Constants.SIGN_HEIGHT) - 2 * x + 8) || (x > Constants.SIGN_WIDTH / 2 && y <= 2 * (x - Constants.SIGN_HEIGHT / 2) + 8) ) { p[RGB.R] = 255; p[RGB.G] = 255; p[RGB.B] = 255; } else if (p[RGB.R] == 0) { com_x_sum += x; com_y_sum += y; com_x_y_point_count++; } } p += nOffset; } } rgb.UnlockBits(image_data); if (com_x_y_point_count < 10) bestChromo = null; else if (Constants.HARVEST_TYPE > Constants.HarvestType.noHarvest) { if (Constants.HARVEST_TYPE == Constants.HarvestType.harvestIntoFolder) { string[] signs = Globals.SIGN_IN_FRAME.Split(','); for (int j = 1; j < signs.Length; j++) { if (!Directory.Exists(Constants.base_folder + "hasat\\" + signs[j])) Directory.CreateDirectory(Constants.base_folder + "hasat\\" + signs[j]); lock (Globals.HARVEST_LOCK) { rgb.Save(Constants.base_folder + "hasat\\" + signs[j] + "\\" + Globals.HARVEST_SIGN_ID + ".bmp"); } } } else { rgb.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_6.bmp"); } } gtcBmp = rgb; } } if (Constants.EVALUATE_TIME_ENABLED) { int x = (int)(DateTime.Now.Ticks / 10000 - start); if (x >= 0) { Globals.TIME_TRIANGLE_MIN = x < Globals.TIME_TRIANGLE_MIN ? x : Globals.TIME_TRIANGLE_MIN; Globals.TIME_TRIANGLE_MAX = x > Globals.TIME_TRIANGLE_MAX ? x : Globals.TIME_TRIANGLE_MAX; Globals.TIME_TRIANGLE_TOTAL += x; } } if (bestChromo != null) { if (panel != null) { Graphics g = panel.getPanelGraphics(); g.DrawRectangle(Pens.Silver, 5, 74, Constants.SIGN_WIDTH, Constants.SIGN_HEIGHT); g.DrawImage(gtcBmp, new Point(5, 74)); } if (msgService != null) { VisionMessage vm = new VisionMessage(gtcBmp.Height, gtcBmp.Width, ByteTools.pixelFormatToBPP(gtcBmp.PixelFormat), gtcBmp); // Center of Mass vm.CoM_X = com_x_sum / (com_x_y_point_count == 0 ? 1 : com_x_y_point_count); vm.CoM_Y = com_y_sum / (com_x_y_point_count == 0 ? 1 : com_x_y_point_count); msgService.sendMsg(vm); } } else { if (Globals.RIGHT_PANEL_SHOWING_STH) { Globals.RIGHT_PANEL_SHOWING_STH = false; Graphics g = panel.getPanelGraphics(); g.Clear(Color.Silver); } } //if (rs > RS_THRESHOLD) // bmp_x.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_" +rs+ "_" +sf.BlueCoeff+ "_" +sf.GreenCoeff+ ".bmp"); threadRunning = false; }
private Boolean colorIsPresent(Bitmap carImg, String color) { ColorImageQuantizer ciq = new ColorImageQuantizer(new MedianCutQuantizer()); ResizeBilinear rsF = new ResizeBilinear(Convert.ToInt32(carImg.Width * 0.3), Convert.ToInt32(carImg.Height * 0.3)); pictureBox2.Image = rsF.Apply(carImg); Crop cropFunction = new Crop(new Rectangle(150, 75, 400, 240)); Bitmap img = ciq.ReduceColors(rsF.Apply(cropFunction.Apply(carImg)), 16); pictureBox3.Image = img; int lowVal = 0; int highVal = 359; double s = 0.45; double lowL = 0.20; double highL = 0.90; Boolean flag = false; if (!(String.Equals(color, "white", StringComparison.OrdinalIgnoreCase)) && !(String.Equals(color, "black", StringComparison.OrdinalIgnoreCase)) && !(String.Equals(color, "gray", StringComparison.OrdinalIgnoreCase))) { if (String.Equals(color, "red", StringComparison.OrdinalIgnoreCase)) { lowVal = 0; highVal = 20; } if (String.Equals(color, "orange", StringComparison.OrdinalIgnoreCase)) { lowVal = 11; highVal = 50; } if (String.Equals(color, "brown", StringComparison.OrdinalIgnoreCase)) { lowVal = 21; highVal = 40; } if (String.Equals(color, "yellow", StringComparison.OrdinalIgnoreCase)) { lowVal = 41; highVal = 80; } if (String.Equals(color, "green", StringComparison.OrdinalIgnoreCase)) { lowVal = 61; highVal = 169; } if (String.Equals(color, "cyan", StringComparison.OrdinalIgnoreCase)) { lowVal = 141; highVal = 220; } if (String.Equals(color, "blue", StringComparison.OrdinalIgnoreCase)) { lowVal = 201; highVal = 280; } if (String.Equals(color, "purple", StringComparison.OrdinalIgnoreCase)) { lowVal = 241; highVal = 330; } if (String.Equals(color, "pink", StringComparison.OrdinalIgnoreCase)) { lowVal = 321; highVal = 355; } for (int i = 0; i < img.Width; i++) { for (int j = 0; j < img.Height; j++) { if (img.GetPixel(i, j).GetHue() >= lowVal && img.GetPixel(i, j).GetHue() <= highVal && img.GetPixel(i, j).GetSaturation() > s && img.GetPixel(i, j).GetBrightness() >= lowL && img.GetPixel(i, j).GetBrightness() <= highL) { flag = true; break; } } if (flag == true) { break; } } } else if (String.Equals(color, "black", StringComparison.OrdinalIgnoreCase)) { for (int i = 0; i < img.Width; i++) { for (int j = 0; j < img.Height; j++) { if (img.GetPixel(i, j).GetBrightness() <= 0.15) { flag = true; break; } } if (flag == true) { break; } } } else if (String.Equals(color, "white", StringComparison.OrdinalIgnoreCase)) { for (int i = 0; i < img.Width; i++) { for (int j = 0; j < img.Height; j++) { if (img.GetPixel(i, j).GetBrightness() >= 0.85) { flag = true; break; } } if (flag == true) { break; } } } //else if (String.Equals(color, "gray", StringComparison.OrdinalIgnoreCase)) //{ // for (int i = 0; i < img.Width; i++) // { // for (int j = 0; j < img.Height; j++) // { // int redVal = img.GetPixel(i, j).R; // int greenVal = img.GetPixel(i, j).G; // int blueVal = img.GetPixel(i, j).B; // if (redVal == greenVal && greenVal == blueVal) // { // flag = true; // break; // } // } // if (flag == true) // break; // } //} else if (String.Equals(color, "gray", StringComparison.OrdinalIgnoreCase)) { for (int i = 0; i < img.Width; i++) { for (int j = 0; j < img.Height; j++) { if (img.GetPixel(i, j).GetHue() >= lowVal && img.GetPixel(i, j).GetHue() <= highVal && img.GetPixel(i, j).GetSaturation() < 0.15 && img.GetPixel(i, j).GetBrightness() >= 0.3) { flag = true; break; } } if (flag == true) { break; } } } return(flag); }
private void videoSourcePlayer1_NewFrame(object sender, ref Bitmap image) { Invert inv = new Invert(); inv.ApplyInPlace(image); UnmanagedImage ui = UnmanagedImage.FromManagedImage(image); pictureBox1.Image = image; if (controller.Tracker.TrackingObject == null) return; if (controller.Tracker.TrackingObject.IsEmpty) return; var rect = controller.Tracker.TrackingObject.Rectangle; Crop crop = new Crop(rect); UnmanagedImage head = crop.Apply(ui); var points = new List<IntPoint>() { new IntPoint(head.Width / 2, head.Height / 2) }; var pps = head.Collect16bppPixelValues(points); double mean = Accord.Statistics.Tools.Mean(pps); double cutoff = mean + 15; Threshold t = new Threshold((int)cutoff); var mask = t.Apply(ui); LevelsLinear16bpp levels = new LevelsLinear16bpp(); levels.InGray = new IntRange((int)cutoff, 65535); levels.OutGray = new IntRange(0, 65535); levels.ApplyInPlace(ui); var mask8bit = AForge.Imaging.Image.Convert16bppTo8bpp(mask.ToManagedImage()); BlobCounter bc = new BlobCounter(); bc.ObjectsOrder = ObjectsOrder.Area; bc.ProcessImage(mask8bit); var blobs = bc.GetObjectsInformation(); inv.ApplyInPlace(image); Intersect intersect = new Intersect(); intersect.UnmanagedOverlayImage = mask; mask = intersect.Apply(ui); List<Rectangle> rects = new List<Rectangle>(); // Extract the uppermost largest blobs. for (int i = 0; i < blobs.Length; i++) { double dx = (blobs[i].Rectangle.Top - controller.Tracker.TrackingObject.Center.Y); double d = (dx * dx) / controller.Tracker.TrackingObject.Area; if (d < 2 && blobs[i].Area > 1000) rects.Add(blobs[i].Rectangle); } rects.Sort(compare); if (rects.Count > 0) { captureHand(mask, rects[0], pbLeftArm, pbLeftHand); } if (rects.Count > 1) { captureHand(mask, rects[1], pbRightArm, pbRightHand); } RectanglesMarker marker = new RectanglesMarker(rects); marker.MarkerColor = Color.White; marker.ApplyInPlace(mask8bit); image = mask.ToManagedImage(); }
public static void OCRPage(PDFPage thisPage, TraceWriter log) { foreach (var img in thisPage.ExtractedImages) { // Image must be Bitmap if (!(img is Bitmap)) { log.Info("Found image that was not Bitmap - ignoring"); continue; } // Image must be at least 40 x 40 if (img.Width < 40 || img.Height < 40) { log.Info("Image is too small - ignoring"); continue; } // Convert this image to grayscale (must be Bitmap as we discovered earlier) var bmp = (Bitmap)img; // In case Grayscale fails - just use it as-is if (img.PixelFormat != PixelFormat.Format1bppIndexed && img.PixelFormat != PixelFormat.Format8bppIndexed) { try { bmp = Grayscale.CommonAlgorithms.BT709.Apply((Bitmap)img); } catch (Exception) { } } // Image can't be larger than 3200 x 3200 if (bmp.Width > 3200 || bmp.Height > 3200) { log.Info(string.Format("Image is too big {0} x {1} - dealing with that...", bmp.Width, bmp.Height)); if (bmp.Width < 3500 && bmp.Height < 3500) { // Lets crop it - hopefully there are margins log.Info("Cropping the image"); // Calculate Crop Rectangle var rect = new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height); if (bmp.Width > 3200) { var halfWideCrop = (bmp.Width - 3200) / 2; rect.X = halfWideCrop; rect.Width = bmp.Width - halfWideCrop; } if (bmp.Height > 3200) { var halfHighCrop = (bmp.Width - 3200) / 2; rect.Y = halfHighCrop; rect.Height = bmp.Height - halfHighCrop; } Crop cropFilter = new Crop(rect); bmp = cropFilter.Apply(bmp); } else { // Scale the image down log.Info("Resizing the image"); // Calculate the shrinkage int newWidth, newHeight; if (bmp.Width > bmp.Height) { var scaleFactor = bmp.Width / 3200F; newWidth = Convert.ToInt32(bmp.Width / scaleFactor); newHeight = Convert.ToInt32(bmp.Height / scaleFactor); } else { var scaleFactor = bmp.Height / 3200F; newWidth = Convert.ToInt32(bmp.Width / scaleFactor); newHeight = Convert.ToInt32(bmp.Height / scaleFactor); } if (newWidth > 3200 || newHeight > 3200) { throw new ApplicationException("DOH! Miscalculated Scale"); } try { ResizeBicubic resizeFilter = new ResizeBicubic(newWidth, newHeight); bmp = resizeFilter.Apply(bmp); } catch (AForge.Imaging.UnsupportedImageFormatException) { return; } } } var ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); ms.Position = 0; try { Task <string> recoTask = Task.Run <string>(async() => { var result = await UploadAndRecognizeImageTextAsync(ms, "en"); return(result); }); recoTask.Wait(); var ocrResult = recoTask.Result; thisPage.OCRText += ocrResult.Trim() + "\r\n"; } catch (Exception ex) { log.Warning(string.Format("Page {0} OCR Exception: {1}", thisPage.Number, ex.Message)); } } }
private void cropSvc_SelectCropByIdCompleted(object sender, SelectCropByIdCompletedEventArgs e) { crop = e.Result; CropModel cm = mapCropToCropModel(crop); getCropByIdCallback(cm); }
}; //wilt1, grow_seed public static void ProcessPlant(GameObject plant) { PlantData setting = CustomizePlantsState.StateManager.State.PlantSettings?.FirstOrDefault(t => t.id == plant.name); if (setting == null) { return; } #region decor plant fixes if (setting.fruitId != null) //decor plant fixes { PrickleGrass grass = plant.GetComponent <PrickleGrass>(); if (grass != null || plant.name == ColdBreatherConfig.ID || plant.name == EvilFlowerConfig.ID) { UnityEngine.Object.DestroyImmediate(grass); //what happens if this is null? plant.AddOrGet <StandardCropPlant>(); KPrefabID prefab = plant.GetComponent <KPrefabID>(); prefab.prefabInitFn += (inst => { StandardCropPlant stdcrop2 = inst.GetComponent <StandardCropPlant>(); stdcrop2.anims = PlantHelper.DecorAnim; }); //KBatchedAnimController kbatchedAnimController = plant.AddOrGet<KBatchedAnimController>(); //kbatchedAnimController.AnimFiles = new KAnimFile[1] //{ // Assets.GetAnim("bristleblossom_kanim") //}; //kbatchedAnimController.initialAnim = "idle_empty"; } SeedProducer seed = plant.GetComponent <SeedProducer>(); if (seed != null) { seed.seedInfo.productionType = SeedProducer.ProductionType.Harvest; seed.seedInfo.newSeedsProduced = 1; } } #endregion #region fruitId if (setting.fruitId != null || setting.fruit_grow_time != null || setting.fruit_amount != null) //actual setting fruit { Crop crop = plant.AddOrGet <Crop>(); Crop.CropVal cropval = crop.cropVal; //this is a copy if (setting.fruitId != null) { cropval.cropId = setting.fruitId; } if (cropval.cropId == "") { cropval.cropId = "WoodLog"; } if (setting.fruit_grow_time != null) { cropval.cropDuration = (float)setting.fruit_grow_time; } if (cropval.cropDuration < 1f) { cropval.cropDuration = 1f; } if (setting.fruit_amount != null) { cropval.numProduced = (int)setting.fruit_amount; } if (cropval.numProduced < 1) { cropval.numProduced = 1; } crop.Configure(cropval); KPrefabID prefab = plant.GetComponent <KPrefabID>(); GeneratedBuildings.RegisterWithOverlay(OverlayScreen.HarvestableIDs, prefab.PrefabID().ToString()); Growing growing = plant.AddOrGet <Growing>(); growing.growthTime = cropval.cropDuration; if (setting.id != ForestTreeConfig.ID) // don't harvest arbor trees directly { plant.AddOrGet <Harvestable>(); } plant.AddOrGet <HarvestDesignatable>(); plant.AddOrGet <StandardCropPlant>(); } #endregion #region irrigation if (setting.irrigation != null) { RemoveIrrigation(plant); List <PlantElementAbsorber.ConsumeInfo> irrigation = new List <PlantElementAbsorber.ConsumeInfo>(3); List <PlantElementAbsorber.ConsumeInfo> fertilization = new List <PlantElementAbsorber.ConsumeInfo>(3); foreach (KeyValuePair <string, float> entry in setting.irrigation) { if (GameTags.LiquidElements.Contains(entry.Key)) { irrigation.Add(new PlantElementAbsorber.ConsumeInfo(entry.Key, entry.Value / 600f)); } else if (GameTags.SolidElements.Contains(entry.Key)) { fertilization.Add(new PlantElementAbsorber.ConsumeInfo(entry.Key, entry.Value / 600f)); } else { Debug.Log(ToDialog("Irrigation for " + setting.id + " defines bad element: " + entry.Key)); } } if (irrigation.Count > 0) { EntityTemplates.ExtendPlantToIrrigated(plant, irrigation.ToArray()); } if (fertilization.Count > 0) { EntityTemplates.ExtendPlantToFertilizable(plant, fertilization.ToArray()); } } #endregion #region illumination if (setting.illumination != null) { IlluminationVulnerable illumination = plant.GetComponent <IlluminationVulnerable>(); CropSleepingMonitor.Def cropSleep = plant.GetDef <CropSleepingMonitor.Def>(); if (setting.illumination == 0f) { if (illumination != null) { UnityEngine.Object.DestroyImmediate(illumination); } if (cropSleep != null) { FumLib.FumTools.RemoveDef(plant, cropSleep); } } else if (setting.illumination < 0f) { if (illumination == null) { illumination = plant.AddOrGet <IlluminationVulnerable>(); } if (cropSleep != null) { FumLib.FumTools.RemoveDef(plant, cropSleep); } illumination.SetPrefersDarkness(true); } else if (setting.illumination == 1f) { if (illumination == null) { illumination = plant.AddOrGet <IlluminationVulnerable>(); } if (cropSleep != null) { FumLib.FumTools.RemoveDef(plant, cropSleep); } illumination.SetPrefersDarkness(false); } else { if (illumination != null) { UnityEngine.Object.DestroyImmediate(illumination); } if (cropSleep == null) { cropSleep = plant.AddOrGetDef <CropSleepingMonitor.Def>(); } cropSleep.lightIntensityThreshold = (float)setting.illumination; cropSleep.prefersDarkness = false; } } #endregion #region safe_elements if (setting.safe_elements != null) { PressureVulnerable pressure = plant.AddOrGet <PressureVulnerable>(); pressure.safe_atmospheres.Clear(); foreach (string safe_element in setting.safe_elements) { pressure.safe_atmospheres.Add(ElementLoader.FindElementByName(safe_element)); } //plant.GetComponent<KPrefabID>().prefabInitFn += (inst => //{ // PressureVulnerable pressure = inst.GetComponent<PressureVulnerable>(); // pressure.safe_atmospheres.Clear(); // foreach (string safe_element in setting.safe_elements) // pressure.safe_atmospheres.Add(ElementLoader.FindElementByName(safe_element)); //}); } #endregion #region pressure if (setting.pressures != null) { PressureVulnerable pressure = plant.AddOrGet <PressureVulnerable>(); pressure.pressureLethal_Low = 0f; pressure.pressureWarning_Low = 0f; pressure.pressureWarning_High = float.MaxValue; pressure.pressureLethal_High = float.MaxValue; pressure.pressure_sensitive = false; for (int i = 0; i < setting.pressures.Length; i++) { switch (i) { case 0: pressure.pressureLethal_Low = setting.pressures[i]; pressure.pressure_sensitive = true; break; case 1: pressure.pressureWarning_Low = setting.pressures[i]; break; case 2: pressure.pressureWarning_High = setting.pressures[i]; break; case 3: pressure.pressureLethal_High = setting.pressures[i]; break; } } } #endregion #region decor try { if (setting.decor_value != null) { plant.GetComponent <DecorProvider>().baseDecor = (float)setting.decor_value; } if (setting.decor_radius != null) { plant.GetComponent <DecorProvider>().baseRadius = (float)setting.decor_radius; } } catch (Exception) { Debug.LogWarning("[CustomizePlants] For some weird reason " + plant.name + " has no DecorProvider."); } #endregion #region temperatures if (setting.temperatures != null) { TemperatureVulnerable temperature = plant.AddOrGet <TemperatureVulnerable>(); for (int i = 0; i < setting.temperatures.Length; i++) { switch (i) { case 0: temperature.internalTemperatureLethal_Low = setting.temperatures[i]; break; case 1: temperature.internalTemperatureWarning_Low = setting.temperatures[i]; break; case 2: temperature.internalTemperatureWarning_High = setting.temperatures[i]; break; case 3: temperature.internalTemperatureLethal_High = setting.temperatures[i]; break; } } } #endregion #region submerged_threshold if (setting.submerged_threshold != null) { DrowningMonitor drowning = plant.AddOrGet <DrowningMonitor>(); if (setting.submerged_threshold == 0f) //doesn't care about water { UnityEngine.Object.DestroyImmediate(drowning); } else if (setting.submerged_threshold < 0f) //needs water { drowning.livesUnderWater = true; drowning.canDrownToDeath = false; } else //if(setting.submerged_threshold > 0f) //hates water { drowning.livesUnderWater = false; drowning.canDrownToDeath = false; } } #endregion #region can_tinker if (setting.can_tinker != null) { if (setting.can_tinker == true) { Tinkerable.MakeFarmTinkerable(plant); } } #endregion #region require_solid_tile if (setting.require_solid_tile != null) { UprootedMonitor uproot = plant.AddOrGet <UprootedMonitor>(); if (setting.require_solid_tile == false) { UnityEngine.Object.DestroyImmediate(uproot); } } #endregion #region max_age if (setting.max_age != null && plant.GetComponent <StandardCropPlant>() != null) //only if plant has fruit { Growing growing = plant.AddOrGet <Growing>(); if (setting.max_age <= 0) { growing.shouldGrowOld = false; } else { growing.shouldGrowOld = true; growing.maxAge = (float)setting.max_age; } } #endregion #region disease if (setting.disease != null || setting.disease_amount != null) { DiseaseDropper.Def def = plant.AddOrGetDef <DiseaseDropper.Def>(); if (setting.disease != null) { def.diseaseIdx = Db.Get().Diseases.GetIndex(setting.disease); } if (setting.disease_amount != null) { def.singleEmitQuantity = (int)setting.disease_amount; } if (def.diseaseIdx == byte.MaxValue || def.singleEmitQuantity == 0) { FumLib.FumTools.RemoveDef(plant, def); } } #endregion #region input_element if (setting.input_element != null) { ElementConsumer consumer = plant.AddOrGet <ElementConsumer>(); Element element = ElementLoader.FindElementByName(setting.input_element); if (element == null || element.IsSolid) //invalid element { Debug.Log(ToDialog("input_element is bad element: " + setting.input_element)); UnityEngine.Object.DestroyImmediate(consumer); } else if (setting.input_rate <= 0f) //delete consumer { UnityEngine.Object.DestroyImmediate(consumer); } else { consumer.configuration = ElementConsumer.Configuration.Element; consumer.consumptionRadius = 2; consumer.sampleCellOffset = new Vector3(0f, 0f); consumer.EnableConsumption(true); consumer.showInStatusPanel = true; consumer.storeOnConsume = false; //consumer deletes elements; output_element might overrides this consumer.consumptionRate = (float)setting.input_rate; consumer.elementToConsume = element.id; consumer.capacityKG = (float)setting.input_rate * 10; plant.AddOrGet <Storage>().capacityKg = consumer.capacityKG; plant.AddOrGet <SaltPlant>(); } } #endregion #region output_element if (setting.output_element != null) { ElementConsumer consumer = plant.GetComponent <ElementConsumer>(); ElementConverter converter = plant.AddOrGet <ElementConverter>(); Element element = ElementLoader.FindElementByName(setting.output_element); if (element == null) //invalid element { Debug.Log(ToDialog("output_element is bad element: " + setting.output_element)); UnityEngine.Object.DestroyImmediate(converter); } else if (setting.output_rate <= 0f) //delete converter { UnityEngine.Object.DestroyImmediate(converter); if (consumer != null) { consumer.storeOnConsume = false; } } else { if (consumer != null) //transform elements { consumer.storeOnConsume = true; converter.consumedElements = new ElementConverter.ConsumedElement[1] { new ElementConverter.ConsumedElement(consumer.elementToConsume.CreateTag(), consumer.consumptionRate) }; converter.OutputMultiplier = (float)setting.output_rate / consumer.consumptionRate; //Debug.Log("TAG is: " + consumer.elementToConsume.CreateTag().Name + " SimHash is: " + consumer.elementToConsume.ToString()); } else //create from nothing { converter.consumedElements = new ElementConverter.ConsumedElement[0]; converter.OutputMultiplier = 1f; } converter.outputElements = new ElementConverter.OutputElement[1] { new ElementConverter.OutputElement((float)setting.output_rate, element.id, 0f, true, false, 0f, 1f) }; plant.AddOrGet <Storage>(); plant.AddOrGet <SaltPlant>(); } } #endregion }
// Maps DataContract from service to ViewModel private CropModel mapCropToCropModel(Crop cm) { CropModel crop = new CropModel(); crop.Id = cm.cropid; crop.Name = cm.name; crop.Type = cm.croptype; crop.TimeOfPlanting = cm.timeofplanting; crop.AvatarImage = cm.avatarimage; crop.CoverageValue = cm.fieldcoverage; crop.WateringFrequency = cm.wateringfrequency; crop.WateringPeriod = cm.wateringperiod; crop.HarvestTime = cm.harvesttime; crop.HillingTime = cm.hillingtime; crop.FertilizingTime = cm.fertilizingtime; crop.FieldId = cm.fieldid; return crop; }
protected override void Seed(FarmApp.DAL.EF.FarmContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. using (var transaction = context.Database.BeginTransaction()) { try { var msk = new Region() { Name = "Сочи" }; var psb = new Region() { Name = "Краснодар" }; context.Regions.AddOrUpdate(x => x.Name, msk); context.Regions.AddOrUpdate(x => x.Name, psb); var rye = new Agriculture() { Name = "Рожь" }; var wheat = new Agriculture() { Name = "Пшеница" }; context.Agricultures.AddOrUpdate(x => x.Name, rye); context.Agricultures.AddOrUpdate(x => x.Name, wheat); var vasya = new Farmer() { Name = "Василий Петрович" }; var parfen = new Farmer() { Name = "Парфён Семёнович" }; context.Farmers.AddOrUpdate(x => x.Name, vasya); context.Farmers.AddOrUpdate(x => x.Name, parfen); context.SaveChanges(); var smallFarm = new Farm() { Name = "Сочинская ферма Василия Петровича", Area = 100, FarmerId = vasya.Id, RegionId = msk.Id }; var bigFarm = new Farm() { Name = "ЗАО Краснодарский совхоз Парфёна", Area = 600, FarmerId = parfen.Id, RegionId = psb.Id }; context.Farms.AddOrUpdate(x => x.Name, smallFarm); context.Farms.AddOrUpdate(x => x.Name, bigFarm); context.SaveChanges(); var cropRyeSmallFarm = new Crop() { AgricultureId = rye.Id, FarmId = smallFarm.Id, Gather = 250 }; var cropWheatSmallFarm = new Crop() { AgricultureId = wheat.Id, FarmId = smallFarm.Id, Gather = 139 }; var cropRyeBigFarm = new Crop() { AgricultureId = rye.Id, FarmId = bigFarm.Id, Gather = 1100 }; var cropWheatBigFarm = new Crop() { AgricultureId = wheat.Id, FarmId = bigFarm.Id, Gather = 900 }; context.Crops.AddOrUpdate(x => new { x.AgricultureId, x.FarmId }, cropRyeSmallFarm); context.Crops.AddOrUpdate(x => new { x.AgricultureId, x.FarmId }, cropWheatSmallFarm); context.Crops.AddOrUpdate(x => new { x.AgricultureId, x.FarmId }, cropRyeBigFarm); context.Crops.AddOrUpdate(x => new { x.AgricultureId, x.FarmId }, cropWheatBigFarm); context.SaveChanges(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); } } }
public HttpResponseMessage GetCropStepMaterialData(int id, int langId) { try { LanguageName = comObj.fetchLang(langId); Crop crop = db.Crops.Find(id); var StepData = crop.Cultivation_Steps.Where(a => a.Active == false); foreach (var removeStepData in StepData.ToList()) { crop.Cultivation_Steps.Remove(removeStepData); } foreach (var StepsData in crop.Cultivation_Steps) { var matraislData = StepsData.CropSteps_Material.Where(b => b.Active == false); foreach (var removematraisl in matraislData.ToList()) { StepsData.CropSteps_Material.Remove(removematraisl); } } switch (LanguageName) { case "Hindi": crop.CropName = crop.CropName != null?comObj.GetResxNameByValue_Hindi(crop.CropName) : string.Empty; crop.Title_Audio = comObj.fetchAudioPahtCrops(id, langId); if (crop.Cultivation_Steps.Count > 0) { foreach (var item in crop.Cultivation_Steps) { item.Step_Name = item.Step_Name != null?comObj.GetResxNameByValue_Hindi(item.Step_Name) : string.Empty; item.Step_Description = item.Step_Description != null?comObj.GetResxNameByValue_Hindi(item.Step_Description) : string.Empty; item.Title_Audio = comObj.fetchAudioPahtSteps(item.Id, langId, "Title"); item.Description_audio = comObj.fetchAudioPahtSteps(item.Id, langId, "Description"); if (item.CropSteps_Material.Count > 0) { foreach (var itemMat in item.CropSteps_Material) { itemMat.Material_Name = itemMat.Material_Name != null?comObj.GetResxNameByValue_Hindi(itemMat.Material_Name) : string.Empty; itemMat.Audio_Path = comObj.fetchAudioPahtMaterials(itemMat.Id, langId); itemMat.Image_Path = itemMat.Image_Path != null ? itemMat.Image_Path : string.Empty; } } } } else { return((HttpResponseMessage)Request.CreateResponse(HttpStatusCode.OK, new { data = new { string.Empty }, success = false, error = "There are no steps and Material for this Crop" })); } break; case "English": crop.CropName = crop.CropName; crop.Title_Audio = comObj.fetchAudioPahtCrops(id, langId); if (crop.Cultivation_Steps.Count > 0) { foreach (var item in crop.Cultivation_Steps) { item.Title_Audio = comObj.fetchAudioPahtSteps(item.Id, langId, "Title"); item.Description_audio = comObj.fetchAudioPahtSteps(item.Id, langId, "Description"); if (item.CropSteps_Material.Count > 0) { foreach (var itemMat in item.CropSteps_Material) { itemMat.Audio_Path = comObj.fetchAudioPahtMaterials(itemMat.Id, langId); itemMat.Image_Path = itemMat.Image_Path != null ? itemMat.Image_Path : string.Empty; } } } } else { return((HttpResponseMessage)Request.CreateResponse(HttpStatusCode.OK, new { data = new { string.Empty }, success = false, error = "There are no steps and Material for this Crop" })); } break; case "Oriya": crop.CropName = crop.CropName != null?comObj.GetResxNameByValue_Oriya(crop.CropName) : string.Empty; crop.Title_Audio = comObj.fetchAudioPahtCrops(id, langId); if (crop.Cultivation_Steps.Count > 0) { foreach (var item in crop.Cultivation_Steps) { item.Step_Name = item.Step_Name != null?comObj.GetResxNameByValue_Oriya(item.Step_Name) : string.Empty; item.Step_Description = item.Step_Description != null?comObj.GetResxNameByValue_Oriya(item.Step_Description) : string.Empty; if (item.CropSteps_Material.Count > 0) { foreach (var itemMat in item.CropSteps_Material) { itemMat.Material_Name = itemMat.Material_Name != null?comObj.GetResxNameByValue_Oriya(itemMat.Material_Name) : string.Empty; itemMat.Audio_Path = comObj.fetchAudioPahtMaterials(itemMat.Id, langId); itemMat.Image_Path = itemMat.Image_Path != null ? itemMat.Image_Path : string.Empty; } } } } else { return((HttpResponseMessage)Request.CreateResponse(HttpStatusCode.OK, new { data = new { string.Empty }, success = false, error = "There are no steps and Material for this Crop" })); } break; case "Santhali": crop.CropName = crop.CropName != null?comObj.GetResxNameByValue_Hindi(crop.CropName) : string.Empty; crop.Title_Audio = comObj.fetchAudioPahtCrops(id, langId); if (crop.Cultivation_Steps.Count > 0) { foreach (var item in crop.Cultivation_Steps) { item.Step_Name = item.Step_Name != null?comObj.GetResxNameByValue_Hindi(item.Step_Name) : string.Empty; item.Step_Description = item.Step_Description != null?comObj.GetResxNameByValue_Hindi(item.Step_Description) : string.Empty; item.Title_Audio = comObj.fetchAudioPahtSteps(item.Id, langId, "Title"); item.Description_audio = comObj.fetchAudioPahtSteps(item.Id, langId, "Description"); if (item.CropSteps_Material.Count > 0) { foreach (var itemMat in item.CropSteps_Material) { itemMat.Material_Name = itemMat.Material_Name != null?comObj.GetResxNameByValue_Hindi(itemMat.Material_Name) : string.Empty; itemMat.Audio_Path = comObj.fetchAudioPahtMaterials(itemMat.Id, langId); itemMat.Image_Path = itemMat.Image_Path != null ? itemMat.Image_Path : string.Empty; } } } } else { return((HttpResponseMessage)Request.CreateResponse(HttpStatusCode.OK, new { data = new { string.Empty }, success = false, error = "There are no steps and Material for this Crop" })); } break; case "Ho": crop.CropName = crop.CropName != null?comObj.GetResxNameByValue_Hindi(crop.CropName) : string.Empty; crop.Title_Audio = comObj.fetchAudioPahtCrops(id, langId); if (crop.Cultivation_Steps.Count > 0) { foreach (var item in crop.Cultivation_Steps) { item.Step_Name = item.Step_Name != null?comObj.GetResxNameByValue_Hindi(item.Step_Name) : string.Empty; item.Step_Description = item.Step_Description != null?comObj.GetResxNameByValue_Hindi(item.Step_Description) : string.Empty; item.Title_Audio = comObj.fetchAudioPahtSteps(item.Id, langId, "Title"); item.Description_audio = comObj.fetchAudioPahtSteps(item.Id, langId, "Description"); if (item.CropSteps_Material.Count > 0) { foreach (var itemMat in item.CropSteps_Material) { itemMat.Material_Name = itemMat.Material_Name != null?comObj.GetResxNameByValue_Hindi(itemMat.Material_Name) : string.Empty; itemMat.Audio_Path = comObj.fetchAudioPahtMaterials(itemMat.Id, langId); itemMat.Image_Path = itemMat.Image_Path != null ? itemMat.Image_Path : string.Empty; } } } } else { return((HttpResponseMessage)Request.CreateResponse(HttpStatusCode.OK, new { data = new { string.Empty }, success = false, error = "There are no steps and Material for this Crop" })); } break; default: break; } if (crop == null) { return((HttpResponseMessage)Request.CreateResponse(HttpStatusCode.OK, new { data = string.Empty, success = false, error = "No Data" })); } else { return((HttpResponseMessage)Request.CreateResponse(HttpStatusCode.OK, new { data = crop, success = true, error = (string)null })); } } catch (Exception ex) { return((HttpResponseMessage)Request.CreateResponse(HttpStatusCode.BadRequest, new { data = (string)null, success = true, error = ex.Message })); } }
void searchSolution(Bitmap rgb) { long start = DateTime.Now.Ticks / 10000; Globals.FRAMES_PROCESSED_CIRCULAR++; int com_x_sum = 0, com_y_sum = 0, com_x_y_point_count = 0; Globals.HARVEST_SIGN_ID++; Bitmap bmp = sf.Apply(rgb); //if (redTestPoints == null) // calculateRedTestPoints(); // GeoTransChromosome sampleChromosome = new GeoTransChromosome(bmp, sf, redTestPoints, nonRedTestPoints); GeoTransChromosome sampleChromosome = new GeoTransChromosome(bmp, sf, null, this); if (population == null || population.BestChromosome == null || population.BestChromosome.Fitness < RS_THRESHOLD - 10) { // fresh population population = new Population(Constants.GA_POPULATION_SIZE, sampleChromosome, sampleChromosome, new EliteSelection() ); population.MutationRate = Constants.GA_MUTATION_RATE; population.CrossoverRate = Constants.GA_CROSSOVER_RATE; } else { // half from previous Population tmpPopulation = new Population(Constants.GA_POPULATION_SIZE, sampleChromosome, sampleChromosome, new EliteSelection() ); tmpPopulation.MutationRate = Constants.GA_MUTATION_RATE; tmpPopulation.CrossoverRate = Constants.GA_CROSSOVER_RATE; for (int j = 0; j < tmpPopulation.Size / 2; j++) { ((GeoTransChromosome)tmpPopulation[j]).copyContent((GeoTransChromosome)population.BestChromosome); } population = tmpPopulation; } int i = 0; do { long start_epoch = DateTime.Now.Ticks / 10000; Globals.FRAMES_PROCESSED_GA_RUNEPOCH++; // run one epoch of genetic algorithm population.RunEpoch(); i++; if (Constants.EVALUATE_TIME_ENABLED) { int x = (int)(DateTime.Now.Ticks / 10000 - start_epoch); if (x >= 0) { Globals.TIME_GA_RUNEPOCH_MIN = x < Globals.TIME_GA_RUNEPOCH_MIN ? x : Globals.TIME_GA_RUNEPOCH_MIN; Globals.TIME_GA_RUNEPOCH_MAX = x > Globals.TIME_GA_RUNEPOCH_MAX ? x : Globals.TIME_GA_RUNEPOCH_MAX; Globals.TIME_GA_RUNEPOCH_TOTAL += x; } } } while (i < Constants.GA_NUMBER_ITERATIONS); GeoTransChromosome bestChromo = null; if (population.BestChromosome != null && population.BestChromosome.Fitness > RS_THRESHOLD) { bestChromo = (GeoTransChromosome)population.BestChromosome; // int rx = 0, ry = 0, rr = 0; // float rs = 0f; int rx = bestChromo.X, ry = bestChromo.Y, rr = bestChromo.Width; float rs = (float)bestChromo.Fitness; // findCircle(bestChromo.X, bestChromo.Y, bmp, ref rx, ref ry, ref rr, ref rs); if (rs < RS_THRESHOLD || rr==0) { bestChromo = null; } else { rr = (int)(Constants.CAPTURE_RESIZE_CIRCLE * rr); // rr = rr - 2; // Graphics g = Graphics.FromImage(rgb); // g.DrawEllipse(Pens.Cyan, rx - rr, ry - rr, rr * 2, rr * 2); if (Constants.HARVEST_TYPE == Constants.HarvestType.harvestAll || Constants.HARVEST_TYPE == Constants.HarvestType.harvestMisses) { rgb.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_0.bmp"); bmp.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_1.bmp"); } rgb = new Crop(new Rectangle(rx - rr, ry - rr, (rx + rr > rgb.Width - 1 ? rgb.Width - 1 - rx : 2 * rr + 2), (ry + rr > rgb.Height - 1 ? rgb.Height - 1 - ry : 2 * rr + 2))).Apply(rgb); rgb = new ResizeBicubic(Constants.SIGN_WIDTH, Constants.SIGN_HEIGHT).Apply(rgb); if (panel != null) { Graphics g = panel.getPanelGraphics(); g.DrawRectangle(Pens.Silver, 5, 4, Constants.SIGN_WIDTH, Constants.SIGN_HEIGHT); g.DrawImage(rgb, new Point(5, 4)); } if (Constants.HARVEST_TYPE == Constants.HarvestType.harvestAll || Constants.HARVEST_TYPE == Constants.HarvestType.harvestMisses) rgb.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_3_" +rs+ ".bmp"); rgb = AutoBrightnessProcessor.autoBrightness(rgb, Rectangle.Empty, Constants.AUTOBRIGHTNESS_BASE_LUM); if (Constants.HARVEST_TYPE == Constants.HarvestType.harvestAll || Constants.HARVEST_TYPE == Constants.HarvestType.harvestMisses) rgb.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_4.bmp"); if (Constants.LABELING_TYPE == Constants.LabelingType.redBlackWhite) rgb = new ColorLabelFilter(new Color[] { Color.FromArgb(255, 0, 0), Color.White, Color.Black }, true).Apply(rgb); else if (Constants.LABELING_TYPE == Constants.LabelingType.blackAndWhite) { int dynamic_gray = 0; rgb = new ColorLabelFilter(new Color[] { Color.White, Color.FromArgb(dynamic_gray, dynamic_gray, dynamic_gray) }, true).Apply(rgb); } /* int start_x = 0, start_y = 0; int y = 0; for (; y < Constants.SIGN_HEIGHT && (start_x + start_y) == 0; y++) { for (int x = 0; x < Constants.SIGN_WIDTH; x++) { Color clr = rgb.GetPixel(x, y); if (clr.R == 0) { start_x = x; start_y = y; break; } } } PointedColorFloodFill filter = new PointedColorFloodFill(); filter.Tolerance = Color.FromArgb(0, 0, 0); filter.FillColor = Color.FromArgb(255, 255, 255); filter.StartingPoint = new Point(start_x, start_y); Bitmap rgb_flood_fill = filter.Apply(rgb); bool black_region_found_at_center = false; y = 4 * (Constants.SIGN_HEIGHT / 10); for (int x = 4 * (Constants.SIGN_WIDTH / 10); x < 6 * (Constants.SIGN_WIDTH / 10); x += 2) { Color clr = rgb_flood_fill.GetPixel(x, y); if (clr.R == 0) { black_region_found_at_center = true; } } if (!black_region_found_at_center) { y = 6 * (Constants.SIGN_HEIGHT / 10); for (int x = 4 * (Constants.SIGN_WIDTH / 10); x < 6 * (Constants.SIGN_WIDTH / 10); x += 2) { Color clr = rgb_flood_fill.GetPixel(x, y); if (clr.R == 0) { black_region_found_at_center = true; break; } } } if (black_region_found_at_center) { rgb = rgb_flood_fill; } */ BitmapData image_data = rgb.LockBits(new Rectangle(0, 0, rgb.Width, rgb.Height), ImageLockMode.ReadWrite, rgb.PixelFormat); int bpp = 3; int nOffset = image_data.Stride - rgb.Width * bpp; System.IntPtr Scan0 = image_data.Scan0; unsafe { byte* p = (byte*)Scan0; for (int y = 0; y < Constants.SIGN_HEIGHT; y++) { // for each pixel for (int x = 0; x < Constants.SIGN_WIDTH; x++, p += bpp) { if (y >= Constants.SIGN_HEIGHT - 10 || y <= 10 || x >= Constants.SIGN_WIDTH - 10 || x <= 10 || Math.Sqrt( (y - Constants.SIGN_HEIGHT / 2) * (y - Constants.SIGN_HEIGHT / 2) + (x - Constants.SIGN_WIDTH / 2) * (x - Constants.SIGN_WIDTH / 2)) > 24 ) { p[RGB.R] = 255; p[RGB.G] = 255; p[RGB.B] = 255; } else if (p[RGB.R] == 0) { com_x_sum += x; com_y_sum += y; com_x_y_point_count++; } } p += nOffset; } } rgb.UnlockBits(image_data); // Graphics g = Graphics.FromImage(rgb); // g.DrawEllipse(Pens.Green, 32 - 24, 32 - 24, 24 * 2, 24 * 2); if (com_x_y_point_count < 10) bestChromo = null; else if (Constants.HARVEST_TYPE > Constants.HarvestType.noHarvest) { if (Constants.HARVEST_TYPE == Constants.HarvestType.harvestIntoFolder) { string[] signs = Globals.SIGN_IN_FRAME.Split(','); for (int j = 1; j < signs.Length; j++) { if (!Directory.Exists(Constants.base_folder + "hasat\\" + signs[j])) Directory.CreateDirectory(Constants.base_folder + "hasat\\" + signs[j]); lock (Globals.HARVEST_LOCK) { rgb.Save(Constants.base_folder + "hasat\\" + signs[j] + "\\" + Globals.HARVEST_SIGN_ID + ".bmp"); } } } else { rgb.Save(Constants.base_folder + "hasat\\" + Globals.HARVEST_SIGN_ID + "_6.bmp"); } } gtcBmp = rgb; } } if (Constants.EVALUATE_TIME_ENABLED) { int x = (int)(DateTime.Now.Ticks / 10000 - start); if (x >= 0) { Globals.TIME_CIRCULAR_MIN = x < Globals.TIME_CIRCULAR_MIN ? x : Globals.TIME_CIRCULAR_MIN; Globals.TIME_CIRCULAR_MAX = x > Globals.TIME_CIRCULAR_MAX ? x : Globals.TIME_CIRCULAR_MAX; Globals.TIME_CIRCULAR_TOTAL += x; } } if (bestChromo != null) { if (panel != null) { Graphics g = panel.getPanelGraphics(); g.DrawRectangle(Pens.Silver, 5, 74, Constants.SIGN_WIDTH, Constants.SIGN_HEIGHT); g.DrawImage(gtcBmp, new Point(5, 74)); } if (msgService != null) { VisionMessage vm = new VisionMessage(gtcBmp.Height, gtcBmp.Width, ByteTools.pixelFormatToBPP(gtcBmp.PixelFormat), gtcBmp); // Center of Mass int com_x = com_x_sum / (com_x_y_point_count == 0 ? 1 : com_x_y_point_count); int com_y = com_y_sum / (com_x_y_point_count == 0 ? 1 : com_x_y_point_count); vm.CoM_X = com_x; vm.CoM_Y = com_y; msgService.sendMsg(vm); } } else { if (Globals.RIGHT_PANEL_SHOWING_STH) { Globals.RIGHT_PANEL_SHOWING_STH = false; // Bitmap img = new Bitmap(160, Constants.IMAGE_HEIGHT, PixelFormat.Format24bppRgb); Graphics g = panel.getPanelGraphics(); g.Clear(Color.Silver); /*if (msgService != null) { VisionMessage vm = new VisionMessage(img.Height, img.Width, ByteTools.pixelFormatToBPP(img.PixelFormat), img); vm.bypass = true; msgService.sendMsg(vm); }*/ } } threadRunning = false; }
public List <Bitmap> breakBigBitMapUp(Bitmap fullBmp) { //9 accross seven down int width = Convert.ToInt32(fullBmp.Width * 0.1111111111); //7 down int heightperSqaure = Convert.ToInt32(fullBmp.Height * 0.14285714); //1st Row Start List <Bitmap> images = new List <Bitmap>(); Crop firstLine1 = new Crop(new Rectangle(0, 0, width, (heightperSqaure) + 5)); Crop firstLine2 = new Crop(new Rectangle(width, 0, width, (heightperSqaure) + 5)); Crop firstLine3 = new Crop(new Rectangle(width * 2, 0, width, (heightperSqaure) + 5)); Crop firstLine4 = new Crop(new Rectangle(width * 3, 0, width, (heightperSqaure) + 5)); Crop firstLine5 = new Crop(new Rectangle(width * 4, 0, width, (heightperSqaure) + 5)); Crop firstLine6 = new Crop(new Rectangle(width * 5, 0, width, (heightperSqaure) + 5)); Crop firstLine7 = new Crop(new Rectangle(width * 6, 0, width, (heightperSqaure) + 5)); Crop firstLine8 = new Crop(new Rectangle(width * 7, 0, width, (heightperSqaure) + 5)); Crop firstLine9 = new Crop(new Rectangle(width * 8, 0, width, (heightperSqaure) + 5)); Bitmap m = firstLine1.Apply(fullBmp); Bitmap m1 = firstLine2.Apply(fullBmp); Bitmap m2 = firstLine3.Apply(fullBmp); Bitmap m3 = firstLine4.Apply(fullBmp); Bitmap m4 = firstLine5.Apply(fullBmp); Bitmap m5 = firstLine6.Apply(fullBmp); Bitmap m6 = firstLine7.Apply(fullBmp); Bitmap m7 = firstLine8.Apply(fullBmp); Bitmap m8 = firstLine9.Apply(fullBmp); images.Add(m); images.Add(m1); images.Add(m2); images.Add(m3); images.Add(m4); images.Add(m5); images.Add(m6); images.Add(m7); images.Add(m8); //end of first row //Start of second row Crop SecondLine1 = new Crop(new Rectangle(0, heightperSqaure, width, (heightperSqaure) + 5)); Crop SecondLine2 = new Crop(new Rectangle(width, heightperSqaure, width, (heightperSqaure) + 5)); Crop SecondLine3 = new Crop(new Rectangle(width * 2, heightperSqaure, width, (heightperSqaure) + 5)); Crop SecondLine4 = new Crop(new Rectangle(width * 3, heightperSqaure, width, (heightperSqaure) + 5)); Crop SecondLine5 = new Crop(new Rectangle(width * 4, heightperSqaure, width, (heightperSqaure) + 5)); Crop SecondLine6 = new Crop(new Rectangle(width * 5, heightperSqaure, width, (heightperSqaure) + 5)); Crop SecondLine7 = new Crop(new Rectangle(width * 6, heightperSqaure, width, (heightperSqaure) + 5)); Crop SecondLine8 = new Crop(new Rectangle(width * 7, heightperSqaure, width, (heightperSqaure) + 5)); Crop SecondLine9 = new Crop(new Rectangle(width * 7, heightperSqaure, width, (heightperSqaure) + 5)); Bitmap s = SecondLine1.Apply(fullBmp); Bitmap s1 = SecondLine2.Apply(fullBmp); Bitmap s2 = SecondLine3.Apply(fullBmp); Bitmap s3 = SecondLine4.Apply(fullBmp); Bitmap s4 = SecondLine5.Apply(fullBmp); Bitmap s5 = SecondLine6.Apply(fullBmp); Bitmap s6 = SecondLine7.Apply(fullBmp); Bitmap s7 = SecondLine8.Apply(fullBmp); Bitmap s8 = SecondLine9.Apply(fullBmp); images.Add(s); images.Add(s1); images.Add(s2); images.Add(s3); images.Add(s4); images.Add(s5); images.Add(s6); images.Add(s7); images.Add(s8); //end of the second row //Start of thrid row Crop ThridLine1 = new Crop(new Rectangle(0, heightperSqaure * 2, width, (heightperSqaure) + 5)); Crop ThridLine2 = new Crop(new Rectangle(width, heightperSqaure * 2, width, (heightperSqaure) + 5)); Crop ThridLine3 = new Crop(new Rectangle(width * 2, heightperSqaure * 2, width, (heightperSqaure) + 5)); Crop ThridLine4 = new Crop(new Rectangle(width * 3, heightperSqaure * 2, width, (heightperSqaure) + 5)); Crop ThridLine5 = new Crop(new Rectangle(width * 4, heightperSqaure * 2, width, (heightperSqaure) + 5)); Crop ThridLine6 = new Crop(new Rectangle(width * 5, heightperSqaure * 2, width, (heightperSqaure) + 5)); Crop ThridLine7 = new Crop(new Rectangle(width * 6, heightperSqaure * 2, width, (heightperSqaure) + 5)); Crop ThridLine8 = new Crop(new Rectangle(width * 7, heightperSqaure * 2, width, (heightperSqaure) + 5)); Crop ThridLine9 = new Crop(new Rectangle(width * 8, heightperSqaure * 2, width, (heightperSqaure) + 5)); Bitmap t = ThridLine1.Apply(fullBmp); Bitmap t1 = ThridLine2.Apply(fullBmp); Bitmap t2 = ThridLine3.Apply(fullBmp); Bitmap t3 = ThridLine4.Apply(fullBmp); Bitmap t4 = ThridLine5.Apply(fullBmp); Bitmap t5 = ThridLine6.Apply(fullBmp); Bitmap t6 = ThridLine7.Apply(fullBmp); Bitmap t7 = ThridLine8.Apply(fullBmp); Bitmap t8 = ThridLine9.Apply(fullBmp); images.Add(t); images.Add(t1); images.Add(t2); images.Add(t3); images.Add(t4); images.Add(t5); images.Add(t6); images.Add(t7); images.Add(t8); //end of the thrid row //Start of fourth row Crop fourthLine1 = new Crop(new Rectangle(0, heightperSqaure * 3, width, (heightperSqaure) + 5)); Crop fourthLine2 = new Crop(new Rectangle(width, heightperSqaure * 3, width, (heightperSqaure) + 5)); Crop fourthLine3 = new Crop(new Rectangle(width * 2, heightperSqaure * 3, width, (heightperSqaure) + 5)); Crop fourthLine4 = new Crop(new Rectangle(width * 3, heightperSqaure * 3, width, (heightperSqaure) + 5)); Crop fourthLine5 = new Crop(new Rectangle(width * 4, heightperSqaure * 3, width, (heightperSqaure) + 5)); Crop fourthLine6 = new Crop(new Rectangle(width * 5, heightperSqaure * 3, width, (heightperSqaure) + 5)); Crop fourthLine7 = new Crop(new Rectangle(width * 6, heightperSqaure * 3, width, (heightperSqaure) + 5)); Crop fourthLine8 = new Crop(new Rectangle(width * 7, heightperSqaure * 3, width, (heightperSqaure) + 5)); Crop fourthLine9 = new Crop(new Rectangle(width * 8, heightperSqaure * 3, width, (heightperSqaure) + 5)); Bitmap f = fourthLine1.Apply(fullBmp); Bitmap f1 = fourthLine2.Apply(fullBmp); Bitmap f2 = fourthLine3.Apply(fullBmp); Bitmap f3 = fourthLine4.Apply(fullBmp); Bitmap f4 = fourthLine5.Apply(fullBmp); Bitmap f5 = fourthLine6.Apply(fullBmp); Bitmap f6 = fourthLine7.Apply(fullBmp); Bitmap f7 = fourthLine8.Apply(fullBmp); Bitmap f8 = fourthLine9.Apply(fullBmp); images.Add(f); images.Add(f1); images.Add(f2); images.Add(f3); images.Add(f4); images.Add(f5); images.Add(f6); images.Add(f7); images.Add(f8); //end of the fourth row //Start of fifth row Crop FifthLine1 = new Crop(new Rectangle(0, heightperSqaure * 4, width, (heightperSqaure) + 5)); Crop FifthLine2 = new Crop(new Rectangle(width, heightperSqaure * 4, width, (heightperSqaure) + 5)); Crop FifthLine3 = new Crop(new Rectangle(width * 2, heightperSqaure * 4, width, (heightperSqaure) + 5)); Crop FifthLine4 = new Crop(new Rectangle(width * 3, heightperSqaure * 4, width, (heightperSqaure) + 5)); Crop FifthLine5 = new Crop(new Rectangle(width * 4, heightperSqaure * 4, width, (heightperSqaure) + 5)); Crop FifthLine6 = new Crop(new Rectangle(width * 5, heightperSqaure * 4, width, (heightperSqaure) + 5)); Crop FifthLine7 = new Crop(new Rectangle(width * 6, heightperSqaure * 4, width, (heightperSqaure) + 5)); Crop FifthLine8 = new Crop(new Rectangle(width * 7, heightperSqaure * 4, width, (heightperSqaure) + 5)); Crop FifthLine9 = new Crop(new Rectangle(width * 8, heightperSqaure * 4, width, (heightperSqaure) + 5)); Bitmap fi = FifthLine1.Apply(fullBmp); Bitmap fi1 = FifthLine2.Apply(fullBmp); Bitmap fi2 = FifthLine3.Apply(fullBmp); Bitmap fi3 = FifthLine4.Apply(fullBmp); Bitmap fi4 = FifthLine5.Apply(fullBmp); Bitmap fi5 = FifthLine6.Apply(fullBmp); Bitmap fi6 = FifthLine7.Apply(fullBmp); Bitmap fi7 = FifthLine8.Apply(fullBmp); Bitmap fi8 = FifthLine9.Apply(fullBmp); images.Add(fi); images.Add(fi1); images.Add(fi2); images.Add(fi3); images.Add(fi4); images.Add(fi5); images.Add(fi6); images.Add(fi7); images.Add(fi8); //end of the Fifth row //Start of Sixth row Crop SixthLine1 = new Crop(new Rectangle(0, heightperSqaure * 5, width, (heightperSqaure) + 5)); Crop SixthLine2 = new Crop(new Rectangle(width, heightperSqaure * 5, width, (heightperSqaure) + 5)); Crop SixthLine3 = new Crop(new Rectangle(width * 2, heightperSqaure * 5, width, (heightperSqaure) + 5)); Crop SixthLine4 = new Crop(new Rectangle(width * 3, heightperSqaure * 5, width, (heightperSqaure) + 5)); Crop SixthLine5 = new Crop(new Rectangle(width * 4, heightperSqaure * 5, width, (heightperSqaure) + 5)); Crop SixthLine6 = new Crop(new Rectangle(width * 5, heightperSqaure * 5, width, (heightperSqaure) + 5)); Crop SixthLine7 = new Crop(new Rectangle(width * 6, heightperSqaure * 5, width, (heightperSqaure) + 5)); Crop SixthLine8 = new Crop(new Rectangle(width * 7, heightperSqaure * 5, width, (heightperSqaure) + 5)); Crop SixthLine9 = new Crop(new Rectangle(width * 8, heightperSqaure * 5, width, (heightperSqaure) + 5)); Bitmap Si = SixthLine1.Apply(fullBmp); Bitmap Si_1 = SixthLine2.Apply(fullBmp); Bitmap Si_2 = SixthLine3.Apply(fullBmp); Bitmap Si_3 = SixthLine4.Apply(fullBmp); Bitmap Si_4 = SixthLine5.Apply(fullBmp); Bitmap Si_5 = SixthLine6.Apply(fullBmp); Bitmap Si_6 = SixthLine7.Apply(fullBmp); Bitmap Si_7 = SixthLine8.Apply(fullBmp); Bitmap Si_8 = SixthLine9.Apply(fullBmp); images.Add(Si); images.Add(Si_1); images.Add(Si_2); images.Add(Si_3); images.Add(Si_4); images.Add(Si_5); images.Add(Si_6); images.Add(Si_7); images.Add(Si_8); //end of the Sixth row //Start of Seven row Crop SevenLine1 = new Crop(new Rectangle(0, heightperSqaure * 6, width, (heightperSqaure) + 5)); Crop SevenLine2 = new Crop(new Rectangle(width, heightperSqaure * 6, width, (heightperSqaure) + 5)); Crop SevenLine3 = new Crop(new Rectangle(width * 2, heightperSqaure * 6, width, (heightperSqaure) + 5)); Crop SevenLine4 = new Crop(new Rectangle(width * 3, heightperSqaure * 6, width, (heightperSqaure) + 5)); Crop SevenLine5 = new Crop(new Rectangle(width * 4, heightperSqaure * 6, width, (heightperSqaure) + 5)); Crop SevenLine6 = new Crop(new Rectangle(width * 5, heightperSqaure * 6, width, (heightperSqaure) + 5)); Crop SevenLine7 = new Crop(new Rectangle(width * 6, heightperSqaure * 6, width, (heightperSqaure) + 5)); Crop SevenLine8 = new Crop(new Rectangle(width * 7, heightperSqaure * 6, width, (heightperSqaure) + 5)); Crop SevenLine9 = new Crop(new Rectangle(width * 8, heightperSqaure * 6, width, (heightperSqaure) + 5)); Bitmap Se = SevenLine1.Apply(fullBmp); Bitmap Se_1 = SevenLine2.Apply(fullBmp); Bitmap Se_2 = SevenLine3.Apply(fullBmp); Bitmap Se_3 = SevenLine4.Apply(fullBmp); Bitmap Se_4 = SevenLine5.Apply(fullBmp); Bitmap Se_5 = SevenLine6.Apply(fullBmp); Bitmap Se_6 = SevenLine7.Apply(fullBmp); Bitmap Se_7 = SevenLine8.Apply(fullBmp); Bitmap Se_8 = SevenLine9.Apply(fullBmp); images.Add(Se); images.Add(Se_1); images.Add(Se_2); images.Add(Se_3); images.Add(Se_4); images.Add(Se_5); images.Add(Se_6); images.Add(Se_7); images.Add(Se_8); //end of the Sixth row return(images); }
public void AddCrop(string mapName, Crop _crop) { if (!Crops.ContainsKey(mapName)) Crops[mapName] = new List<Crop>(); if (!(Crops[mapName] as List<Crop>).Exists(c => c.Coordinates.X == _crop.Coordinates.X && c.Coordinates.Y == _crop.Coordinates.Y)) (Crops[mapName] as List<Crop>).Add(_crop); }