/* * Copyright (c) 2015, Jason Maltzen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; namespace DesertPaintLab { public class NewRecipeEventArgs : EventArgs { string color; PaintRecipe recipe; public NewRecipeEventArgs(string color, PaintRecipe recipe) { this.color = color; this.recipe = recipe; } public string Color { get { return color; } } public PaintRecipe Recipe { get { return recipe; } } } public class RecipeGenerator { private class SearchNode { //int initialReagentCount; List reagents; HashSet reagentInUse = new HashSet(); List costSortedReagents; PaintRecipe testRecipe = null; public PaintRecipe TestRecipe { get { return testRecipe; } set { testRecipe = value; } } public uint CurrentTargetQuantity { get; set; } public uint MaxQuantity { get; set; } uint maxReagents; public uint MaxReagents { get { return maxReagents; } set { maxReagents = value; currentWeights = new uint[maxReagents]; } } public uint UsedQuantity { get; private set; } public uint CatalystCount { get; set; } uint[] currentWeights; public uint[] CurrentWeights { get { return currentWeights; } } public SearchNode(List costSortedReagents, List reagents) { this.costSortedReagents = new List(costSortedReagents); this.reagents = new List(reagents); foreach (uint reagentIdx in reagents) { reagentInUse.Add(reagentIdx); } InitialCount = this.reagents.Count; MaxReagents = (uint)this.reagents.Count; // better set this later! UsedQuantity = 0; } // top-level search public SearchNode(List costSortedReagents, uint startReagent) { this.costSortedReagents = new List(costSortedReagents); this.reagents = new List(); this.reagents.Add(NextFreeReagent(startReagent)); InitialCount = 1; // don't iterate up beyond the start reagent MaxReagents = 1; UsedQuantity = 0; } public int InitialCount { get; private set; } public List Reagents { get { return reagents; } } public Reagent Reagent(int idx) { return costSortedReagents[(int)reagents[idx]]; } public uint LastReagent { get { return reagents[reagents.Count - 1]; } } public void RemoveLastReagent() { uint reagentIdx = reagents[reagents.Count-1]; ReleaseReagent(reagentIdx); if (costSortedReagents[(int)reagentIdx].IsCatalyst) { --CatalystCount; } reagents.RemoveAt(reagents.Count-1); } public void ReplaceLastReagent(uint reagentIdx) { uint oldReagentIdx = reagents[reagents.Count-1]; ReleaseReagent(oldReagentIdx); reagents[reagents.Count-1] = reagentIdx; if (costSortedReagents[(int)oldReagentIdx].IsCatalyst) { --CatalystCount; } if (costSortedReagents[(int)reagentIdx].IsCatalyst) { ++CatalystCount; } } public uint NextFreeReagent(uint startIdx) { uint idx = startIdx; for (; idx < costSortedReagents.Count; ++idx) { bool inUse = reagentInUse.Contains(idx); if (inUse == false) { //Console.WriteLine("Found free reagent idx {0}", idx); reagentInUse.Add(idx); return idx; } } //Console.WriteLine("Failed to find free reagent."); return (uint)costSortedReagents.Count; } private void ReleaseReagent(uint reagentIdx) { reagentInUse.Remove(reagentIdx); } public bool AddNextReagent() { bool ok = (reagents.Count < MaxReagents); if (ok) { uint nextReagent = NextFreeReagent(0); reagents.Add(nextReagent); if (costSortedReagents[(int)nextReagent].IsCatalyst) { ++CatalystCount; } InitForQuantity(CurrentTargetQuantity); } return ok; } public void InitForQuantity(uint quantity) { //System.Console.WriteLine("Target quantity: {0}, reagent count: {1}", quantity, reagents.Count); CurrentTargetQuantity = quantity; if (CurrentTargetQuantity < (10 + CatalystCount)) { return; } UsedQuantity = 0; uint remainingReagents = ((uint)reagents.Count - CatalystCount); uint remainingWeight = CurrentTargetQuantity - CatalystCount; for (int i = 0; i < reagents.Count; ++i) { Reagent reagent = Reagent(i); if (reagent.IsCatalyst) { currentWeights[i] = 1; ++UsedQuantity; } else { uint weight = (uint)Math.Min(remainingWeight - (remainingReagents-1), reagent.RecipeMax); remainingWeight -= weight; currentWeights[i] = weight; UsedQuantity += weight; } --remainingReagents; } } public void SetWeight(int idx, uint quantity) { UsedQuantity -= currentWeights[idx]; currentWeights[idx] = quantity; UsedQuantity += quantity; } } const uint DEFAULT_MAX_QUANTITY = 14; // minimum recipe: 10 base + 4 catalysts const uint DEFAULT_MAX_REAGENTS = 5; //uint maxQuantity; // maximum number of total ingredients uint maxReagents; // maximum number of reagents to use in the recipe uint fullQuantityDepth; // at or equal this number of reagents, ignore ingredient settings for max quantity uint fullQuantity; // The max number of a reagent to use at full quantity ReactionSet reactions; bool running = false; SortedDictionary recipeCosts = new SortedDictionary(); SortedDictionary recipes = new SortedDictionary(); uint totalReagents; List costSortedReagents = new List(); ConcurrentQueue searchQueue = new ConcurrentQueue(); int recipeCount = 0; List generatorThreads = new List(); Object workerLock = new Object(); bool requestCancel = false; // events public event EventHandler Finished; public event EventHandler Progress; public event EventHandler NewRecipe; public RecipeGenerator() { } public SortedDictionary Recipes { get { return recipes; } } public int RecipeCount { get { return recipeCount; } } private class ReagentCostSort : IComparer { public int Compare(Reagent reagent1, Reagent reagent2) { return (int)reagent1.Cost - (int)reagent2.Cost; } } public void InitRecipes(SortedDictionary recipes, ReactionSet reactions) { if (running) { return; } this.reactions = reactions; foreach (PaintRecipe recipe in recipes.Values) { // TODO: copy? AddCheapestRecipe(recipe); } } public void BeginRecipeGeneration(ReactionSet reactions, uint maxQuantity, uint maxReagents, uint fullQuantityDepth, uint fullQuantity) { if (running) { // Already running - don't start again return; } this.running = true; this.reactions = reactions; //this.maxQuantity = maxQuantity; this.maxReagents = maxReagents; this.fullQuantity = fullQuantity; this.fullQuantityDepth = fullQuantityDepth; // first, sort reagents by cost. costSortedReagents.Clear(); foreach (string name in ReagentManager.Names) { Reagent reagent = ReagentManager.GetReagent(name); if (reagent.Enabled) { costSortedReagents.Add(reagent); } } costSortedReagents.Sort(new ReagentCostSort()); this.maxReagents = (uint)Math.Min(costSortedReagents.Count, this.maxReagents); totalReagents = (uint)costSortedReagents.Count; // Pre-populate recipes list with: // 1) 1-ingredient recipes @ 10db for all enabled ingredients with a count >= 10 // 2) any previously-generated recipes foreach (Reagent reagent in costSortedReagents) { if (!reagent.IsCatalyst && reagent.RecipeMax >= 10) { PaintRecipe recipe = new PaintRecipe(); recipe.Reactions = reactions; recipe.AddReagent(reagent.Name, 10); AddCheapestRecipe(recipe); } } for (uint reagentIdx = 0; reagentIdx < costSortedReagents.Count; ++reagentIdx) { SearchNode initialNode = new SearchNode(costSortedReagents, reagentIdx); initialNode.MaxQuantity = maxQuantity; initialNode.MaxReagents = maxReagents; searchQueue.Enqueue(initialNode); } // start worker threads to do the actual work requestCancel = false; running = true; // Start the workers thread for (int i = 0; i < costSortedReagents.Count; ++i) { Thread thr = new Thread(new ThreadStart(this.Generate)); generatorThreads.Add(thr); } foreach (Thread thr in generatorThreads) { thr.Start(); } } public void ResumeRecipeGeneration() { if (running) { // Already running - don't start again return; } this.running = true; requestCancel = false; for (int i = 0; i < costSortedReagents.Count; ++i) { Thread thr = new Thread(new ThreadStart(this.Generate)); generatorThreads.Add(thr); } foreach (Thread thr in generatorThreads) { thr.Start(); } } private void Generate() { SearchNode node; bool ok = true; do { lock (workerLock) { ok = searchQueue.TryDequeue(out node); } if (ok) { uint targetQuantity = node.MaxQuantity + 1; do { --targetQuantity; node.InitForQuantity(targetQuantity); } while (targetQuantity > 10 && (node.CurrentTargetQuantity != node.UsedQuantity)); while (ok = Iterate(node) && !requestCancel) { if (Progress != null) { Progress(this, null); } } if (ok) { // stopped because cancel was requested - requeue the node in its current state for resume searchQueue.Enqueue(node); } } } while (!requestCancel && ok); bool done = false; lock(workerLock) { generatorThreads.Remove(Thread.CurrentThread); done = (generatorThreads.Count == 0); } if (done) { if (Finished != null) { Finished(this, null); } running = false; } } // Add the cheapest recipe to the recipe list // returns the discarded recipe from the pair (or null if no original recipe to replace) private PaintRecipe AddCheapestRecipe(PaintRecipe recipe) { PaintRecipe discarded = recipe; if (recipe.IsValid) { recipe.Reactions = reactions; string colorName = Palette.FindNearest(recipe.ReactedColor); //System.Console.WriteLine("Recipe: {0} {1}:", colorName, recipe.Cost); //foreach (PaintRecipe.RecipeIngredient ingr in recipe.Ingredients) //{ // System.Console.WriteLine(" -> {0} {1}", ingr.quantity, ingr.name); //} uint cost; lock (workerLock) { if (recipeCosts.TryGetValue(colorName, out cost)) { if (cost > recipe.Cost) { discarded = recipes[colorName]; recipeCosts[colorName] = recipe.Cost; recipes[colorName] = recipe; if (NewRecipe != null) { NewRecipeEventArgs args = new NewRecipeEventArgs(colorName, recipe); NewRecipe(this, args); } } } else { discarded = null; recipeCosts.Add(colorName, recipe.Cost); recipes.Add(colorName, recipe); if (NewRecipe != null) { NewRecipeEventArgs args = new NewRecipeEventArgs(colorName, recipe); NewRecipe(this, args); } } } } else { string msg = String.Format("Recipe is invalid ({0} ingredients)\n", recipe.Ingredients.Count); foreach (PaintRecipe.RecipeIngredient ingr in recipe.Ingredients) { msg += String.Format(" -> {0} {1}", ingr.quantity, ingr.name); } lock (workerLock) { Console.WriteLine(msg); } } return discarded; } private bool Iterate(SearchNode node) { // pick recipe quantities at current recipe ingredients/size if (NextRecipe(node)) { lock(workerLock) { ++recipeCount; } //System.Console.WriteLine("Found next recipe at size {0} qty {1}", node.Reagents.Count, node.CurrentTargetQuantity); return true; } if (NextRecipeSize(node)) { //System.Console.WriteLine("Found next recipee size {0}", node.CurrentTargetQuantity); return true; } // Search for next ingredient combo - all quantity combos for previous were searched //System.Console.WriteLine("Finding next ingredient combo"); do { if (!node.AddNextReagent()) { while ((node.Reagents.Count > node.InitialCount) && (node.LastReagent == (totalReagents-1))) { node.RemoveLastReagent(); } if (node.Reagents.Count == node.InitialCount) { // done return false; } uint nextReagent = node.NextFreeReagent(node.LastReagent); while ((node.Reagents.Count > node.InitialCount) && (nextReagent >= totalReagents)) { // No more reagents to try at this level node.RemoveLastReagent(); if (node.Reagents.Count > node.InitialCount) { nextReagent = node.NextFreeReagent(node.LastReagent); } } if (node.Reagents.Count == node.InitialCount) { // done return false; } node.ReplaceLastReagent(nextReagent); } } while (node.MaxQuantity < (10 + node.CatalystCount)); node.InitForQuantity(node.MaxQuantity); //string outStr = "{0} : {1} : "; //for (int i = 0; i < currentReagents.Count; ++i) //{ // Reagent reagent = costSortedReagents[(int)currentReagents[i]]; // if (i > 0) // { // outStr += ", "; // } // outStr += reagent.Name + " (" + reagent.Cost + ")"; //} //Console.WriteLine(outStr, currentReagents.Count, recipeCount); return true; } private bool NextRecipe(SearchNode node) { // First, run the current recipe if (node.TestRecipe == null) { node.TestRecipe = new PaintRecipe(); node.TestRecipe.Reactions = reactions; } node.TestRecipe.Clear(); for (int i = 0; i < node.Reagents.Count; ++i) { node.TestRecipe.AddReagent(node.Reagent(i).Name, node.CurrentWeights[i]); } PaintRecipe replacement = AddCheapestRecipe(node.TestRecipe); if (replacement == null) { node.TestRecipe = new PaintRecipe(); node.TestRecipe.Reactions = reactions; } else { node.TestRecipe = replacement; } // check for the next recipe uint remainingWeight = node.CurrentTargetQuantity - node.CatalystCount; if (remainingWeight < 10) { // not possible to make a valid recipe return false; } //uint remainingReagents = (uint)node.Reagents.Count - node.CatalystCount; uint depth = (uint)node.Reagents.Count; uint weightToConsume = 0; uint spaceBelow = 0; int reagentsBelow = 0; for (int i = (int)depth-1 ; i >= 0; --i) { uint currentWeight = node.CurrentWeights[i]; if ((spaceBelow >= (weightToConsume+1)) && (currentWeight > 1)) { // reduce this node by 1, allocate remaining weight to reagents below it node.SetWeight(i, currentWeight-1); weightToConsume += 1; for (int j = i+1; j < depth; ++j) { --reagentsBelow; Reagent reagent = node.Reagent(j); uint allocated = (uint)Math.Min(reagent.IsCatalyst ? 1 : (depth <= fullQuantityDepth ? fullQuantity : reagent.RecipeMax), weightToConsume - reagentsBelow); if (allocated > 100) { Console.WriteLine("ACK: allocated = {0}", allocated); } node.SetWeight(j, allocated); weightToConsume -= allocated; } break; } else { Reagent reagent = node.Reagent(i); spaceBelow += (reagent.IsCatalyst ? 1 : (depth <= fullQuantityDepth ? fullQuantity : reagent.RecipeMax)); weightToConsume += currentWeight; ++reagentsBelow; } } //int recipeWeight = 0; //foreach (int weight in node.CurrentWeights) //{ // recipeWeight += weight; //} //if ((weightToConsume != 0) || (recipeWeight != node.CurrentTargetQuantity)) //{ // Console.WriteLine("Failed recipe with leftover weight {0} ({1}/{2}):", weightToConsume, recipeWeight, node.CurrentTargetQuantity); // for (int i = 0; i < node.Reagents.Count; ++i) // { // Console.WriteLine(" > {0} {1}", node.Reagent(i).Name, node.CurrentWeights[i]); // } //} return (weightToConsume == 0); } private bool NextRecipeSize(SearchNode node) { uint newQuantity = node.CurrentTargetQuantity - 1; if (newQuantity < (10 + node.CatalystCount)) { return false; } node.InitForQuantity(newQuantity); if (node.CurrentTargetQuantity > node.UsedQuantity) { return false; } return true; } public void Wait() { if (running) { foreach (Thread thr in generatorThreads) { thr.Join(); } } } public void Stop() { this.requestCancel = true; } public void Reset() { recipes.Clear(); recipeCosts.Clear(); } } }