public Dialog_CreateJobsForIngredients( Manager manager, RecipeDef recipe, int count )
 {
     targetCount = count;
     targetRecipe = recipe;
     ingredients = recipe.ingredients.Select( ic => new IngredientSelector( manager, ic, targetCount, recipe ) ).ToList();
     this.manager = manager;
 }
Esempio n. 2
0
 public ManagerJobProduction(RecipeDef recipe)
 {
     Bill = recipe.UsesUnfinishedThing ? new Bill_ProductionWithUft(recipe) : new Bill_Production(recipe);
     MainProduct = new MainProductTracker(Bill.recipe);
     Trigger = new TriggerThreshold(this);
     BillGivers = new BillGiverTracker(this);
 }
 public static bool EverHasRecipe( this ThingDef thingDef, RecipeDef recipeDef )
 {
     return (
         ( thingDef.GetRecipesCurrent().Contains( recipeDef ) )||
         ( thingDef.GetRecipesUnlocked( ref nullDefs ).Contains( recipeDef ) )||
         ( thingDef.GetRecipesLocked( ref nullDefs ).Contains( recipeDef ) )
     );
 }
Esempio n. 4
0
 public OrderConfig(RecipeDef def)
 {
     this.order = null;
     this.recipe = def;
     this.ingredientsFilter = new ThingFilter();
     this.ingredientsFilter.CopyFrom(def.fixedIngredientFilter);
     this.scrollPosition = default(Vector2);
 }
 public Dialog_CreateJobsForIngredients( RecipeDef recipe, int count )
 {
     targetCount  = count;
     targetRecipe = recipe;
     ingredients  =
         recipe.ingredients.Select(
             ic   => new IngredientSelector( ic, targetCount, recipe ) ).ToList();
 }
        public ManagerJob_Production( RecipeDef recipe )
        {
            Bill = recipe.UsesUnfinishedThing ? new Bill_ProductionWithUft( recipe ) : new Bill_Production( recipe );
            _hasMeaningfulIngredientChoices = Dialog_CreateJobsForIngredients.HasPrerequisiteChoices( recipe );
            MainProduct = new MainProductTracker( Bill.recipe );
            Trigger = new Trigger_Threshold( this );
            BillGivers = new BillGiverTracker( this );

            History = new History( new[] { Trigger.ThresholdFilter.Summary } );
        }
 public Window_RecipeManagement(AssemblyLine line, Window_LineManagementUI previousPage)
     : base(line, "RecipeManagementHelp".Translate())
 {
     this.previousPage = previousPage;
     if (recipesList != null)
     {
         recipesList.Sort((o, y) => o.label.CompareTo(y.label));
         selectedDef = recipesList.First();
         config = new OrderConfig(selectedDef);
     }
 }
 public static void AddQualityToImplants(ref Thing product, RecipeDef recipeDef, Pawn worker)
 {
     if (product.HasThingCategory(InternalDefOf.GR_ImplantCategory))
     {
         foreach (Thing ingredient in GeneticRim_GenRecipe_MakeRecipeProducts.ingredients)
         {
             if (ingredient.HasThingCategory(InternalDefOf.GR_Genoframes))
             {
                 QualityCategory quality = ingredient.def.GetModExtension <DefExtension_Quality>().quality;
                 product.TryGetComp <CompQuality>().SetQuality(quality, ArtGenerationContext.Colony);
             }
         }
     }
 }
Esempio n. 9
0
            public void Postfix_MakeRecipeProducts(ref IEnumerable <Thing> __result, RecipeDef recipeDef, float skillChance, List <Thing> ingredients)
            {
                string prefix = null;

                InitializeAtRuntime();
                try
                {
                    if (recipeDef.Equals(Recipe_AutopsyBasic))
                    {
                        prefix = "Basic";
                    }
                    else if (recipeDef.Equals(Recipe_AutopsyAdvanced))
                    {
                        prefix = "Advanced";
                    }
                    else if (recipeDef.Equals(Recipe_AutopsyGlitterworld))
                    {
                        prefix = "Glitter";
                    }
                    else if (recipeDef.Equals(Recipe_AutopsyAnimal))
                    {
                        prefix = "Animal";
                    }
                    if (prefix != null)
                    {
                        var maxChance      = prefix == "Animal" ? 0f : GetValue(prefix + "AutopsyOrganMaxChance");
                        var age            = prefix == "Animal" ? 0 : (int)GetValue(prefix + "AutopsyCorpseAge") * 2500;
                        var frozen         = prefix == "Animal" ? 0f : GetValue(prefix + "AutopsyFrozenDecay");
                        var recipeSettings = Activator.CreateInstance(recipeInfoType,
                                                                      maxChance,
                                                                      age,
                                                                      GetValue(prefix + "AutopsyBionicMaxChance"),
                                                                      GetValue(prefix + "AutopsyMaxNumberOfOrgans"),
                                                                      frozen);
                        skillChance *= (float)GetValue(prefix + "AutopsyMedicalSkillScaling");

                        List <Thing> result = __result as List <Thing> ?? __result.ToList();
                        foreach (Corpse corpse in ingredients.OfType <Corpse>())
                        {
                            result.AddRange((IEnumerable <Thing>) this.traverseBody.Invoke(null, new object[] { recipeSettings, corpse, skillChance }));
                        }

                        __result = result;
                    }
                }
                catch (Exception e)
                {
                    Log.ErrorOnce("HOPMの実行時エラー. " + e.ToString(), 1660882676);
                }
            }
Esempio n. 10
0
 public override IEnumerable <BodyPartRecord> GetPartsToApplyOn(Pawn p, RecipeDef r)
 {
     if (p.gender == Gender.Female)
     {
         foreach (var part in p.health.hediffSet.GetNotMissingParts())
         {
             if (r.appliedOnFixedBodyParts.Contains(part.def) &&
                 ((part != xxx.breasts) || (!Genital_Helper.breasts_blocked(p))))
             {
                 yield return(part);
             }
         }
     }
 }
 public override IEnumerable <BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
 {
     foreach (Hediff diff in pawn.health.hediffSet.hediffs)
     {
         if (diff.Part != null)
         {
             if (IsRemovableHediff(diff))
             {
                 yield return(diff.Part);
             }
         }
     }
     yield break;
 }
        /// <summary>
        ///     Get all currently build buildings that use the recipe
        /// </summary>
        /// <param name="rd"></param>
        /// <returns></returns>
        public static List <Building_WorkTable> CurrentRecipeUsers(this RecipeDef rd, Map map)
        {
            List <ThingDef> recipeUsers        = rd.GetRecipeUsers();
            var             currentRecipeUsers = new List <Building_WorkTable>();

            foreach (ThingDef td in recipeUsers)
            {
                currentRecipeUsers.AddRange(
                    map.listerBuildings.AllBuildingsColonistOfDef(td)
                    .Select(b => b as Building_WorkTable));
            }

            return(currentRecipeUsers);
        }
 public virtual void IncreaseWeight(RecipeDef recipe, float factor)
 {
     if (factors.TryGetValue(recipe, out WorkSpeedFactorEntry entry))
     {
         entry.FactorFinal += factor;
     }
     else
     {
         factors.Add(recipe, new WorkSpeedFactorEntry()
         {
             FactorFinal = factor
         });
     }
 }
Esempio n. 14
0
        public static ThingFilter ClearFilter(RecipeDef recipe, int count)
        {
            IngredientCount ic = new IngredientCount();

            ic.SetBaseCount(count);
            recipe.ingredients.Clear();
            recipe.ingredients.Add(ic);
            ThingFilter filter = ic.filter;

            recipe.defaultIngredientFilter = filter;
            filter.SetDisallowAll(null, null);
            recipe.fixedIngredientFilter = filter;
            return(filter);
        }
        // Defalt Behavior:
        //   Look for Def
        //   Look for BonusYield
        //   If we have one of those, see about replacing it with recipe-specific yield
        public Thing BonusThing(RecipeDef recipe = null, QualityCategory?minQuality = null, QualityCategory?maxQuality = null)
        {
            Thing t = SimpleBonusThing(minQuality, maxQuality);

            if (t != null)
            {
                Thing u = RecipeBonusThing(recipe, minQuality, maxQuality);
                if (u != null)
                {
                    t = u;
                }
            }
            return(t);
        }
 private void addRecipeToRecipes(RecipeDef def)
 {
     if (this.def.recipes != null)
     {
         if (!this.recipesAdded.Contains(def.defName))
         {
             this.recipesAdded.Add(def.defName);
             this.def.recipes.Add(def);
             typeof(ThingDef).GetField("allRecipesCached", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(this.def, null);
         }
     }
     else
         Log.Message("recipes list was null " + this.def.defName);
 }
Esempio n. 17
0
        public static Bill MakeNewBill(this RecipeDef recipe)
        {
            Bill result;

            if (recipe.UsesUnfinishedThing)
            {
                result = new Bill_ProductionWithUft(recipe);
            }
            else
            {
                result = new Bill_Production(recipe);
            }
            return(result);
        }
Esempio n. 18
0
        private static void RememberRecipeLabel(RecipeDef r)
        {
            var label = TransformRecipeLabel(r.LabelCap);

            if (!dictLR.ContainsKey(label))
            {
                dictLR.Add(label, r);
            }
            else if (dictLR[label] != r)
            {
                Log.Warning($"Ambiguous recipe label: {label}. Right click menu will be disabled for this one.");
                dictLR[label] = null;
            }
        }
 public override IEnumerable <BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
 {
     return(from part in recipe.appliedOnFixedBodyParts
            let bpList = pawn.RaceProps.body.AllParts
                         let part1 = part
                                     from record in from record in bpList
                                     where record.def == part1
                                     where pawn.health.hediffSet.GetNotMissingParts().Contains(record)
                                     where !pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(record)
                                     let record1 = record
                                                   where !pawn.health.hediffSet.hediffs.Any(x => x.Part == record1 && x.def == recipe.addsHediff)
                                                   select record
                                                   select record);
 }
Esempio n. 20
0
    public static List <ThingDef> GetRecipeUsers(this RecipeDef recipeDef)
    {
        var thingDefs = DefDatabase <ThingDef> .AllDefsListForReading.Where(t =>
                                                                            !t.AllRecipes.NullOrEmpty() &&
                                                                            t.AllRecipes.Contains(recipeDef)
                                                                            ).ToList();

        if (!thingDefs.NullOrEmpty())
        {
            return(thingDefs);
        }

        return(new List <ThingDef>());
    }
Esempio n. 21
0
        public override IEnumerable <BodyPartRecord> GetPartsToApplyOn(Pawn p, RecipeDef r)
        {
            bool blocked  = Genital_Helper.genitals_blocked(p) || xxx.is_slime(p);            //|| xxx.is_demon(p);
            bool has_vag  = Genital_Helper.has_vagina(p);
            bool has_cock = Genital_Helper.has_penis(p) || Genital_Helper.has_penis_infertile(p) || Genital_Helper.has_ovipositorF(p);

            foreach (BodyPartRecord part in base.GetPartsToApplyOn(p, r))
            {
                if (r.appliedOnFixedBodyParts.Contains(part.def) && !blocked && (!has_vag && has_cock))
                {
                    yield return(part);
                }
            }
        }
        //
        // Fields
        //

        //
        // Methods
        //

        public override IEnumerable <BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
        {
            BodyPartRecord part = pawn.RaceProps.body.corePart;

            if (recipe.appliedOnFixedBodyParts[0] != null)
            {
                part = pawn.RaceProps.body.AllParts.Find(x => x.def == recipe.appliedOnFixedBodyParts[0]);
            }
            if (part != null && ChildrenUtility.RaceUsesChildren(pawn) && pawn.gender == Gender.Female &&
                pawn.ageTracker.CurLifeStageIndex >= AgeStage.Teenager)
            {
                yield return(part);
            }
        }
        public string generateSurgeryText(Pawn pawn, RecipeDef recipe, BodyPartRecord part)
        {
            string text = recipe.Worker.GetLabelWhenUsedOn(pawn, part);

            if (part != null && !recipe.hideBodyPartNames)
            {
                text += " (" + part.def.label + ")";
            }
            if (text == "Shut down")
            {
                text += " (" + pawn.def.label + ")";
            }
            return(text);
        }
Esempio n. 24
0
            public bool MoveNext()
            {
                uint num = (uint)this.$PC;

                this.$PC = -1;
                bool flag = false;

                switch (num)
                {
                case 0u:
                    enumerator = RecipeDefGenerator.DefsFromRecipeMakers().Concat(RecipeDefGenerator.DrugAdministerDefs()).GetEnumerator();
                    num        = 4294967293u;
                    break;

                case 1u:
                    break;

                default:
                    return(false);
                }
                try
                {
                    switch (num)
                    {
                    }
                    if (enumerator.MoveNext())
                    {
                        r             = enumerator.Current;
                        this.$current = r;
                        if (!this.$disposing)
                        {
                            this.$PC = 1;
                        }
                        flag = true;
                        return(true);
                    }
                }
                finally
                {
                    if (!flag)
                    {
                        if (enumerator != null)
                        {
                            enumerator.Dispose();
                        }
                    }
                }
                this.$PC = -1;
                return(false);
            }
        public bool                         RemoveResourcesFromHoppers(RecipeDef recipe, List <ThingAmount> chosen)
        {
            //Log.Message( string.Format( "{0}.CompHopperUser.RemoveResourcesFromHoppers( {0}, List<ThingAmount> )", this.parent.ThingID, recipe == null ? "null" : recipe.defName ) );
            var hoppers = FindHoppers();

            if (hoppers.NullOrEmpty())
            {
                return(false);
            }

            var allResources = new List <Thing>();

            foreach (var hopper in hoppers)
            {
                var hopperResources = hopper.GetAllResources(ResourceSettings.filter);
                if (hopperResources != null)
                {
                    allResources.AddRangeUnique(hopperResources);
                }
            }

            bool removeThings = false;

            if (recipe.allowMixingIngredients)
            {
                removeThings = recipe.TryFindBestRecipeIngredientsInSet_AllowMix(allResources, chosen);
            }
            else
            {
                removeThings = recipe.TryFindBestRecipeIngredientsInSet_NoMix(allResources, chosen);
            }
            if (!removeThings)
            {
                return(false);
            }

            foreach (var chosenThing in chosen)
            {
                if (chosenThing.count >= chosenThing.thing.stackCount)
                {
                    chosenThing.thing.Destroy();
                }
                else
                {
                    chosenThing.thing.stackCount -= chosenThing.count;
                }
            }

            return(true);
        }
Esempio n. 26
0
 public static void Postfix(RecipeDef recipeDef, Pawn worker, IEnumerable<Thing> __result)
 {
     foreach(Thing thing in __result)
     {
         if (thing != null)
         {
             StoryHandler.Missions.ForEach(m => m.objectives.Where(o => o.CurrentState == MOState.Active).Do(o =>
             {
                 o.thingTracker?.ProcessTarget(thing.def, worker.Position, worker.Map, ObjectiveType.ConstructOrCraft, thing);
             }
             ));
         }
     }
 }
 public override IEnumerable <BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
 {
     foreach (BodyPartDef part in recipe.appliedOnFixedBodyParts)
     {
         foreach (BodyPartRecord record in pawn.RaceProps.body.AllParts)
         {
             if (record.def == part && pawn.health.hediffSet.GetNotMissingParts(BodyPartHeight.Undefined, BodyPartDepth.Undefined).Contains(record) && !pawn.health.hediffSet.PartOrAnyAncestorHasDirectlyAddedParts(record) && !pawn.health.hediffSet.hediffs.Any((Hediff x) => x.Part == record && x.def == recipe.addsHediff) && !pawn.health.hediffSet.hediffs.Any((Hediff x) => x.Part == record && x.def.hediffClass == typeof(Polarisbloc.Hediff_CombatChip)))
             {
                 yield return(record);
             }
         }
     }
     yield break;
 }
        public override IEnumerable <BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
        {
            BodyPartRecord part = pawn.RaceProps.body.corePart;

            if (recipe.appliedOnFixedBodyParts[0] != null)
            {
                part = pawn.RaceProps.body.AllParts.Find(x => x.def == recipe.appliedOnFixedBodyParts[0]);
            }
            if (part != null && (pawn.ageTracker.CurLifeStage.reproductive) ||
                pawn.IsPregnant(true))
            {
                yield return(part);
            }
        }
Esempio n. 29
0
        private static bool TryFindBestBillIngredientsInSet_NoMix(List <Thing> availableThings, Bill bill, List <ThingCount> chosen)
        {
            RecipeDef recipe = bill.recipe;

            chosen.Clear();
            availableCounts.Clear();
            availableCounts.GenerateFrom(availableThings);
            for (int i = 0; i < ingredientsOrdered.Count; i++)
            {
                IngredientCount ingredientCount = recipe.ingredients[i];
                bool            flag            = false;
                for (int j = 0; j < availableCounts.Count; j++)
                {
                    float num = (float)ingredientCount.CountRequiredOfFor(availableCounts.GetDef(j), bill.recipe);
                    if (!(num > availableCounts.GetCount(j)) && ingredientCount.filter.Allows(availableCounts.GetDef(j)) && (ingredientCount.IsFixedIngredient || bill.ingredientFilter.Allows(availableCounts.GetDef(j))))
                    {
                        for (int k = 0; k < availableThings.Count; k++)
                        {
                            if (availableThings[k].def == availableCounts.GetDef(j))
                            {
                                int num2 = availableThings[k].stackCount - ThingCountUtility.CountOf(chosen, availableThings[k]);
                                if (num2 > 0)
                                {
                                    int num3 = Mathf.Min(Mathf.FloorToInt(num), num2);
                                    ThingCountUtility.AddToList(chosen, availableThings[k], num3);
                                    num -= (float)num3;
                                    if (num < 0.001f)
                                    {
                                        flag = true;
                                        float count = availableCounts.GetCount(j);
                                        count -= (float)ingredientCount.CountRequiredOfFor(availableCounts.GetDef(j), bill.recipe);
                                        availableCounts.SetCount(j, count);
                                        break;
                                    }
                                }
                            }
                        }
                        if (flag)
                        {
                            break;
                        }
                    }
                }
                if (!flag)
                {
                    return(false);
                }
            }
            return(true);
        }
Esempio n. 30
0
    IEnumerator MakeItems(RecipeDef recipeDef)
    {
        foreach (ItemDef itemDef in recipeDef.returnedItems)
        {
            print("Making item: " + itemDef.name);
            Item item = Instantiate(Resources.Load <Item>("Prefabs/Item Prefab"), transform.position,
                                    Quaternion.identity);
            yield return(new WaitForEndOfFrame());

            item.SetDef(itemDef);
            item.GetComponent <BounceBehaviour>().Throw(new Vector2(Random.Range(minThrowRange.x, maxThrowRange.x), Random.Range(minThrowRange.y, maxThrowRange.y)));
            yield return(new WaitForSeconds(0.15f));
        }
    }
        public override IEnumerable <BodyPartRecord> GetPartsToApplyOn(Pawn pawn, RecipeDef recipe)
        {
            var targetSkill = GetSkill(recipe.defName);
            var isAdvanced  = recipe.defName.Contains("_Adv_");

            var brainPart = pawn.health.hediffSet.GetBrain();

            var currentPassion = pawn.skills.GetSkill(targetSkill).passion;

            if (currentPassion == Passion.None || isAdvanced && currentPassion == Passion.Minor)
            {
                yield return(brainPart);
            }
        }
        public bool AlienHasJobOnRecipe(Thing alien, RecipeDef recipe)
        {
            bool result = false;

            if (recipe == PurpleIvyDefOf.DrawAlienBlood)
            {
                result = this.HasBloodInAlien(alien);
            }
            else if (recipe == PurpleIvyDefOf.DrawAlphaAlienBlood)
            {
                if ("Genny_ParasiteAlpha" == alien.def.defName)
                {
                    result = this.HasBloodInAlien(alien);
                }
            }
            else if (recipe == PurpleIvyDefOf.DrawBetaAlienBlood)
            {
                if ("Genny_ParasiteBeta" == alien.def.defName)
                {
                    result = this.HasBloodInAlien(alien);
                }
            }
            else if (recipe == PurpleIvyDefOf.DrawGammaAlienBlood)
            {
                if ("Genny_ParasiteGamma" == alien.def.defName)
                {
                    result = this.HasBloodInAlien(alien);
                }
            }
            else if (recipe == PurpleIvyDefOf.DrawOmegaAlienBlood)
            {
                if ("Genny_ParasiteOmega" == alien.def.defName)
                {
                    result = this.HasBloodInAlien(alien);
                }
            }
            else if (recipe == PurpleIvyDefOf.DrawGuardAlienBlood)
            {
                if ("Genny_ParasiteNestGuard" == alien.def.defName)
                {
                    result = this.HasBloodInAlien(alien);
                }
            }
            else if (recipe == PurpleIvyDefOf.DrawKorsolianToxin)
            {
                result = this.HasToxinInAlien(alien);
            }
            return(result);
        }
Esempio n. 33
0
 private static IEnumerable <RecipeDef> DefsFromRecipeMakers()
 {
     foreach (ThingDef def in from d in DefDatabase <ThingDef> .AllDefs
              where d.recipeMaker != null
              select d)
     {
         RecipeMakerProperties rm = def.recipeMaker;
         RecipeDef             r  = new RecipeDef();
         r.defName        = "Make_" + def.defName;
         r.label          = "RecipeMake".Translate(def.label);
         r.jobString      = "RecipeMakeJobString".Translate(def.label);
         r.modContentPack = def.modContentPack;
         r.workAmount     = (float)rm.workAmount;
         r.workSpeedStat  = rm.workSpeedStat;
         r.efficiencyStat = rm.efficiencyStat;
         if (def.MadeFromStuff)
         {
             IngredientCount ingredientCount = new IngredientCount();
             ingredientCount.SetBaseCount((float)def.costStuffCount);
             ingredientCount.filter.SetAllowAllWhoCanMake(def);
             r.ingredients.Add(ingredientCount);
             r.fixedIngredientFilter.SetAllowAllWhoCanMake(def);
             r.productHasIngredientStuff = true;
         }
         if (def.costList != null)
         {
             foreach (ThingDefCountClass current in def.costList)
             {
                 IngredientCount ingredientCount2 = new IngredientCount();
                 ingredientCount2.SetBaseCount((float)current.count);
                 ingredientCount2.filter.SetAllow(current.thingDef, true);
                 r.ingredients.Add(ingredientCount2);
             }
         }
         r.defaultIngredientFilter = rm.defaultIngredientFilter;
         r.products.Add(new ThingDefCountClass(def, rm.productCount));
         r.targetCountAdjustment   = rm.targetCountAdjustment;
         r.skillRequirements       = rm.skillRequirements.ListFullCopyOrNull <SkillRequirement>();
         r.workSkill               = rm.workSkill;
         r.workSkillLearnFactor    = rm.workSkillLearnPerTick;
         r.unfinishedThingDef      = rm.unfinishedThingDef;
         r.recipeUsers             = rm.recipeUsers.ListFullCopyOrNull <ThingDef>();
         r.effectWorking           = rm.effectWorking;
         r.soundWorking            = rm.soundWorking;
         r.researchPrerequisite    = rm.researchPrerequisite;
         r.factionPrerequisiteTags = rm.factionPrerequisiteTags;
         yield return(r);
     }
 }
        public void GiveHediff(Pawn pawn)
        {
            //If the random number is not within the chance range, exit.
            if (!(chance >= Rand.Range(0.0f, 100.0f)))
            {
                return;
            }
            //If the gender is male, check the male commonality chance, and if it fails, exit.
            if (pawn.gender == Gender.Male && !(maleCommonality >= Rand.Range(0.0f, 100.0f)))
            {
                return;
            }
            if (pawn.gender == Gender.Female && !(femaleCommonality >= Rand.Range(0.0f, 100.0f)))
            {
                return;
            }
            float cash = pawn.kindDef.techHediffsMoney.RandomInRange;

            if (!allowedPawnkinds.NullOrEmpty() && !allowedPawnkinds.Contains(pawn.kindDef))
            {
                return;
            }
            if (!disallowedPawnkinds.NullOrEmpty() && disallowedPawnkinds.Contains(pawn.kindDef))
            {
                return;
            }

            float partsMoney = pawn.kindDef.techHediffsMoney.RandomInRange;
            IEnumerable <ThingDef> source = from x in DefDatabase <ThingDef> .AllDefs
                                            where x.isTechHediff && x.BaseMarketValue <= partsMoney && x.techHediffsTags != null && pawn.kindDef.techHediffsTags.Any((string tag) => x.techHediffsTags.Contains(tag))
                                            select x;

            if (source.Any <ThingDef>())
            {
                ThingDef partDef = source.RandomElementByWeight((ThingDef w) => w.BaseMarketValue);
                IEnumerable <RecipeDef> source2 = from x in DefDatabase <RecipeDef> .AllDefs
                                                  where x.IsIngredient(partDef) && pawn.def.AllRecipes.Contains(x)
                                                  select x;
                if (source2.Any <RecipeDef>())
                {
                    RecipeDef recipeDef = source2.RandomElement <RecipeDef>();
                    if (recipeDef.Worker.GetPartsToApplyOn(pawn, recipeDef).Any <BodyPartRecord>())
                    {
                        recipeDef.Worker.ApplyOnPawn(pawn, recipeDef.Worker.GetPartsToApplyOn(pawn, recipeDef).RandomElement <BodyPartRecord>(), null, emptyIngredientsList, null);
                    }
                }
            }
            //   HediffGiverUtility.TryApply(pawn, hediff, partsToAffect);
        }
Esempio n. 35
0
        protected override void FillTab()
        {
            var recipes = this.Machine.GetRecipes();

            PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.BillsTab, KnowledgeAmount.FrameDisplayed);
            Rect rect = new Rect(0f, 0f, ITab_MaterializeBills.WinSize.x, ITab_MaterializeBills.WinSize.y).ContractedBy(10f);
            Func <List <FloatMenuOption> > recipeOptionsMaker = delegate
            {
                List <FloatMenuOption> list = new List <FloatMenuOption>();
                for (int i = 0; i < recipes.Count; i++)
                {
                    if (recipes[i].AvailableNow)
                    {
                        RecipeDef recipe = recipes[i];
                        list.Add(new FloatMenuOption(recipe.LabelCap, delegate
                        {
                            if (!this.Machine.Map.mapPawns.FreeColonists.Any((Pawn col) => recipe.PawnSatisfiesSkillRequirements(col)))
                            {
                                Bill.CreateNoPawnsWithSkillDialog(recipe);
                            }
                            Bill bill = new Bill_Production2(recipe, this.Machine.OnComplete);
                            this.Machine.billStack.AddBill(bill);
                            if (recipe.conceptLearned != null)
                            {
                                PlayerKnowledgeDatabase.KnowledgeDemonstrated(recipe.conceptLearned, KnowledgeAmount.Total);
                            }
                        }, MenuOptionPriority.Default, null, null, 58f, (rect2) =>
                        {
                            if (recipe.defName.StartsWith(Building_MaterialMahcine.MaterializeRecipeDefData.MaterializeRecipeDefPrefix))
                            {
                                if (Widgets.ButtonImage(new Rect(rect2.x + 34f, rect2.y + (rect2.height - 24f), 24f, 24f), Resources.DeleteX))
                                {
                                    this.Machine.RemoveMaterializeRecipe(recipe);
                                    return(true);
                                }
                            }
                            return(Widgets.InfoCardButton(rect2.x + 5f, rect2.y + (rect2.height - 24f) / 2f, recipe));
                        }, null));
                    }
                }
                if (!list.Any <FloatMenuOption>())
                {
                    list.Add(new FloatMenuOption("NoneBrackets".Translate(), null, MenuOptionPriority.Default, null, null, 0f, null, null));
                }
                return(list);
            };

            this.mouseoverBill = this.Machine.billStack.DoListing(rect, recipeOptionsMaker, ref this.scrollPosition, ref this.viewHeight);
        }
        public static List <DefHyperlink> SurgeryToHyperlinks(RecipeDef surgery)
        {
            var defs = new HashSet <Def> {
            };

            Predicate <string> checkWorkerType = delegate(string t) {
                return(SafeTypeByName(t) is Type type && type != null && IsSupertypeOf(type, surgery.workerClass));
            };

            foreach (IngredientCount ingredientCount in surgery.ingredients.Where(i => i.IsFixedIngredient))
            {
                ThingDef part = ingredientCount.FixedIngredient;
                if (
                    // Exempt from this check
                    !(checkWorkerType("Recipe_AdministerIngestible") || checkWorkerType("Recipe_AdministerUsableItem")) && (
                        part.IsMedicine || part.IsStuff || part.defName.StartsWith("RepairKit")
                        )
                    )
                {
                    continue;
                }

                defs.Add(part);
            }

            var hediffChangers = new List <HediffDef> {
                surgery.addsHediff, surgery.removesHediff, surgery.changesHediffLevel
            };

            foreach (HediffDef hediff in hediffChangers.Where(
                         hd => hd != null && defs.All(d => d.defName != hd.defName)
                         ))
            {
                if (!hediff.descriptionHyperlinks.NullOrEmpty())
                {
                    defs.AddRange(hediff.descriptionHyperlinks.Select(dhl => dhl.def));
                }
                else if (hediff.spawnThingOnRemoved != null)
                {
                    defs.Add(hediff.spawnThingOnRemoved);
                }
                else
                {
                    defs.Add(hediff);
                }
            }

            return(defs.Select(d => new DefHyperlink(d)).ToList());
        }
Esempio n. 37
0
        // Token: 0x06000043 RID: 67 RVA: 0x00004CA0 File Offset: 0x00002EA0
        private static bool GenAdminOption(Pawn patient, RecipeDef recipe, BodyPartRecord part = null)
        {
            bool result = false;

            if (patient != null)
            {
                Bill_Medical bill_Medical = new Bill_Medical(recipe);
                patient.BillStack.AddBill(bill_Medical);
                result            = true;
                bill_Medical.Part = part;
                if (recipe.conceptLearned != null)
                {
                    PlayerKnowledgeDatabase.KnowledgeDemonstrated(recipe.conceptLearned, KnowledgeAmount.Total);
                }
                Pawn patient2 = patient;
                Map  map      = patient2?.Map;
                if (map != null)
                {
                    if (!map.mapPawns.FreeColonists.Any((Pawn col) => recipe.PawnSatisfiesSkillRequirements(col)))
                    {
                        Bill.CreateNoPawnsWithSkillDialog(recipe);
                    }
                    if (!RestUtility.InBed(patient) && patient.RaceProps.IsFlesh)
                    {
                        if (patient.RaceProps.Humanlike)
                        {
                            if (!GenCollection.Any(map.listerBuildings.allBuildingsColonist, (Building x) => x is Building_Bed bed && RestUtility.CanUseBedEver(patient, x.def) && bed.Medical))
                            {
                                Messages.Message(Translator.Translate("MessageNoMedicalBeds"), patient, MessageTypeDefOf.CautionInput, false);
                            }
                        }
                        else if (!GenCollection.Any <Building>(map.listerBuildings.allBuildingsColonist, (Building x) => x is Building_Bed && RestUtility.CanUseBedEver(patient, x.def)))
                        {
                            Messages.Message(Translator.Translate("MessageNoAnimalBeds"), patient, MessageTypeDefOf.CautionInput, false);
                        }
                    }
                    if (patient.Faction != null && !patient.Faction.def.hidden && !FactionUtility.HostileTo(patient.Faction, Faction.OfPlayer) && recipe.Worker.IsViolationOnPawn(patient, part, Faction.OfPlayer))
                    {
                        Messages.Message(TranslatorFormattedStringExtensions.Translate("MessageMedicalOperationWillAngerFaction", patient.Faction), patient, MessageTypeDefOf.CautionInput, false);
                    }
                    ThingDef minRequiredMedicine = MSAddDrugBill.GetMinRequiredMedicine(recipe);
                    if (minRequiredMedicine != null && patient.playerSettings != null && !MedicalCareUtility.AllowsMedicine(patient.playerSettings.medCare, minRequiredMedicine))
                    {
                        Messages.Message(TranslatorFormattedStringExtensions.Translate("MessageTooLowMedCare", minRequiredMedicine.label, patient.LabelShort, MedicalCareUtility.GetLabel(patient.playerSettings.medCare), NamedArgumentUtility.Named(patient, "PAWN")), patient, MessageTypeDefOf.CautionInput, false);
                    }
                }
            }
            return(result);
        }
Esempio n. 38
0
        static void UnmarkDesignation(Pawn_JobTracker __instance, JobCondition condition, bool releaseReservations, bool cancelBusyStancesSoft, bool canReturnToPool)
        {
            if (__instance?.curJob?.bill == null || __instance.curJob.bill.billStack != null /*|| condition != JobCondition.Succeeded*/)
            {
                return;
            }

            if (__instance.curJob.targetB != null && __instance.curJob.targetB.HasThing && !__instance.curJob.targetB.ThingDestroyed)
            {
                RecipeDef      rec   = __instance.curJob.bill.recipe;
                ThingWithComps thing = __instance.curJob.targetB.Thing as ThingWithComps;
                if (thing == null)
                {
                    return;
                }
                //
                DesignationDef dDef = DefDatabase <DesignationDef> .AllDefsListForReading.FirstOrDefault(x => x.defName == rec.defName + "Designation");

                if (dDef == null)
                {
                    return;
                }

                Designation d = thing.Map.designationManager.DesignationOn(__instance.curJob.targetB.Thing, dDef);

                if (d == null)
                {
                    return;
                }

                thing.Map.designationManager.RemoveDesignation(d);
                if (condition != JobCondition.Succeeded)
                {
                    Settings.ResetSelectTick();
                    var comp = thing.AllComps?.FirstOrDefault(x => x is ApplicableDesignationThingComp && (x as ApplicableDesignationThingComp).Props.designationDef == dDef) as ApplicableDesignationThingComp;
                    if (comp != null)
                    {
                        comp.Allowed = null;
                    }
                    var ds = Find.ReverseDesignatorDatabase.AllDesignators.FirstOrDefault(x => (x as Designator_MicroRecipe) != null && (x as Designator_MicroRecipe).designationDef == dDef);
                    if (ds == null || !ds.CanDesignateThing(thing))
                    {
                        return;
                    }
                    //
                    thing.Map.designationManager.AddDesignation(new Designation(thing, dDef));
                }
            }
        }
        // set market value from the actual ingredients costs
        public void SetMarketValue(RecipeDef recipe, List<Thing> currentIngredients)
        {
            var workValue = parent.def.GetStatValueAbstract(StatDefOf.WorkToMake) * ValuePerWork;

            var curIngredientsValue = currentIngredients.Sum(ingredient => ingredient.MarketValue * ingredient.stackCount);
            var minIngredientsValue = recipe.ingredients.Sum(ingredient =>
                ingredient.filter.AllowedThingDefs.Min(def => def.BaseMarketValue) * ingredient.GetBaseCount());
            var maxIngredientsValue = recipe.ingredients.Sum(ingredient =>
                ingredient.filter.AllowedThingDefs.Max(def => def.BaseMarketValue) * ingredient.GetBaseCount());

            var profitCoefficient = maxIngredientsValue != minIngredientsValue
                ? (float)Math.Pow(maxIngredientsValue - minIngredientsValue, 1 - ProfitFactor)
                : 0f;

            marketValue = profitCoefficient * (curIngredientsValue - minIngredientsValue) + workValue + minIngredientsValue;
        }
Esempio n. 40
0
        public RecipeDef FullCopyRecipeDef(RecipeDef recipeDef)
        {
            if (recipeDef == null)
                return null;

            RecipeDef copy = new RecipeDef();

            copy.defName = recipeDef.defName;
            copy.workSpeedStat = recipeDef.workSpeedStat;
            copy.workSkill = recipeDef.workSkill;
            copy.workSkillLearnFactor = recipeDef.workSkillLearnFactor;
            copy.effectWorking = recipeDef.effectWorking;
            copy.soundWorking = recipeDef.soundWorking;
            copy.recipeUsers = GenList.ListFullCopyOrNull(recipeDef.recipeUsers);
            copy.defaultIngredientFilter = new ThingFilter();
            copy.defaultIngredientFilter.categories = GenList.ListFullCopyOrNull(recipeDef.defaultIngredientFilter.categories);
            copy.defaultIngredientFilter.exceptedThingDefs = GenList.ListFullCopyOrNull(recipeDef.defaultIngredientFilter.exceptedThingDefs);
            copy.unfinishedThingDef = recipeDef.unfinishedThingDef;

            return copy;
        }
Esempio n. 41
0
        static void CopyDefToVanilla(RecipeDef def, Recipe r)
        {
            var or = SettingUpRecipes;
            SettingUpRecipes = true;

            r.createItem.netDefaults(def.CreateItem.Resolve().NetID);
            r.createItem.stack = def.CreateStack;

            //if (def.RequiredItems.Keys.Any(e => (e.Kind & EitherKind.Left) != 0) ||
            //        def.RequiredTiles .Any(e => (e.Kind & EitherKind.Left) != 0))
            //    r.P_GroupDef = def; // handled by RecipeHooks.FindRecipes

            // for groups: display first the first, it's handled by RecipeHooks.FindRecipes
            int i = 0;
            foreach (var kvp in def.RequiredItems)
            {
                if (i >= Recipe.maxRequirements)
                    break;

                r.requiredItem[i] = new Item();
                r.requiredItem[i].netDefaults(kvp.Key.Match(MiscExtensions.Identity, g => g[0]).Resolve().NetID);
                r.requiredItem[i].stack = kvp.Value;

                i++;
            }

            i = 0;
            foreach (var t in def.RequiredTiles)
            {
                if (i >= Recipe.maxRequirements)
                    break;

                r.requiredTile[i] = t.Match(MiscExtensions.Identity, g => g[0]).Resolve().Type;

                i++;
            }

            r.alchemy = def.AlchemyReduction;

            r.needWater = (def.RequiredLiquids & RecipeLiquids.Water) != 0;
            r.needLava  = (def.RequiredLiquids & RecipeLiquids.Lava ) != 0;
            r.needHoney = (def.RequiredLiquids & RecipeLiquids.Honey) != 0;

            ////TODO: set any* to true when TileGroups are defined & implemented
            // RecipeHooks.FindRecipes handles this

            SettingUpRecipes = or;
        }
 private void MergeIngredientIntoHopperSettings( IngredientCount ingredient, RecipeDef recipe )
 {
     //Log.Message( string.Format( "{0}.CompHopperUser.MergeIngredientIntoHopperSettings( IngredientCount, {1} )", this.parent.ThingID, recipe == null ? "null" : recipe.defName ) );
     if( ingredient.filter != null )
     {
         if( !ingredient.filter.Categories().NullOrEmpty() )
         {
             foreach( var category in ingredient.filter.Categories() )
             {
                 var categoryDef = DefDatabase<ThingCategoryDef>.GetNamed( category, true );
                 HopperSettingsAmount.AddToList( hopperSettings, categoryDef, ingredient.GetBaseCount(), recipe );
             }
         }
         if( !ingredient.filter.ThingDefs().NullOrEmpty() )
         {
             foreach( var thingDef in ingredient.filter.ThingDefs() )
             {
                 HopperSettingsAmount.AddToList( hopperSettings, thingDef, ingredient.GetBaseCount(), recipe );
             }
         }
     }
 }
        private void DrawRecipeList(Rect inRect)
        {
            Rect availableRecipeMainRect = new Rect(0f, currentYMaxLeft, availableRecipeMainRectSize.x, availableRecipeMainRectSize.y);
            this.bottom = availableRecipeMainRect.yMax;
            this.recipeEntrySize = new Vector2(availableRecipeMainRect.width - 16f, 48f);
            this.recipeAddButtonSize = new Vector2(120f, this.recipeEntrySize.y - 12f);

            Widgets.DrawMenuSection(availableRecipeMainRect);

            GUI.BeginGroup(availableRecipeMainRect);

            if (enteredText != "")
            {
                list = (
                    from t in this.recipesList
                    where t.label.ToLower().Contains(enteredText.ToLower())
                    select t).ToList();
            }
            else
            {
                list = this.recipesList;
            }
            float entryHeight = this.recipeEntrySize.y;

            float height = (float)list.Count * entryHeight;

            Rect viewRect = new Rect(0f, 0f, availableRecipeMainRect.width - 16f, height);
            Rect outRect = new Rect(availableRecipeMainRect.AtZero());

            Widgets.BeginScrollView(outRect, ref this.scrollPosition, viewRect);

            float currentY = 0f;
            float num3 = 0f;
            if (recipesList.Count == 0)
            {
                Rect rect = new Rect(0f, currentY, this.recipeEntrySize.x, this.recipeEntrySize.y);
                Text.Font = GameFont.Small;
                Widgets.Label(rect, "NoRecipesFound".Translate());
            }
            else
            {
                foreach (RecipeDef def in list)
                {
                    Rect rect2 = new Rect(0f, currentY, this.recipeEntrySize.x, this.recipeEntrySize.y);
                    if ((rect2.Contains(Event.current.mousePosition)) || (selectedDef != null && def == selectedDef))
                    {
                        GUI.color = MouseHoverColor;
                        GUI.DrawTexture(rect2, BaseContent.WhiteTex);
                    }
                    else if (num3 % 2 == 0)
                    {
                        GUI.DrawTexture(rect2, AltTexture);
                    }
                    Rect innerRect = rect2.ContractedBy(3f);
                    GUI.BeginGroup(innerRect);
                    string recipeName = def.label.CapitalizeFirst();
                    GUI.color = Color.white;
                    Text.Font = GameFont.Small;
                    Text.Anchor = TextAnchor.MiddleLeft;
                    Rect rect = new Rect(15f, 0f, innerRect.width, innerRect.height);
                    Widgets.Label(rect, recipeName);
                    float buttonX = recipeEntrySize.x - 6f - recipeAddButtonSize.x;
                    Rect butRect = new Rect(buttonX, 0f, recipeAddButtonSize.x, recipeAddButtonSize.y);
                    if (Widgets.InvisibleButton(rect))
                    {
                        this.selectedDef = def;
                        this.config = new OrderConfig(def);
                        //Log.Message("Clicked " + def.defName);
                    }
                    GUI.EndGroup();
                    currentY += entryHeight;
                    num3++;
                }
            }
            GUI.EndGroup();
            Text.Anchor = TextAnchor.UpperLeft;
            Widgets.EndScrollView();
        }
 public bool IsRecipeInFilter( RecipeDef recipe )
 {
     //Log.Message( string.Format( "{0}.CompHopperUser.IsRecipeInFilter( {1} )", this.parent.ThingID, recipe == null ? "null" : recipe.defName ) );
     return recipeFilter.Contains( recipe );
 }
 public void MergeRecipeIntoFilter( ThingFilter filter, RecipeDef recipe )
 {
     //Log.Message( string.Format( "{0}.CompHopperUser.MergeRecipeInfoFilter( ThingFilter, {1} )", this.parent.ThingID, recipe == null ? "null" : recipe.defName ) );
     if( recipeFilter.Contains( recipe ) )
     {
         return;
     }
     recipeFilter.Add( recipe );
     if( !recipe.ingredients.NullOrEmpty() )
     {
         foreach( var ingredient in recipe.ingredients )
         {
             MergeIngredientIntoFilter( filter, ingredient );
         }
     }
     if( recipe.defaultIngredientFilter != null )
     {
         MergeExceptionsIntoFilter( filter, recipe.defaultIngredientFilter );
     }
     if( recipe.fixedIngredientFilter != null )
     {
         MergeExceptionsIntoFilter( filter, recipe.fixedIngredientFilter );
     }
 }
Esempio n. 46
0
        static void CopyDefToVanilla(RecipeDef def, Recipe r)
        {
            r.createItem.netDefaults(def.CreateItem.Resolve().NetID);
            r.createItem.stack = def.CreateStack;

            int i = 0;
            foreach (var kvp in def.RequiredItems)
            {
                if (i >= Recipe.maxRequirements)
                    break;

                r.requiredItem[i] = new Item();
                r.requiredItem[i].netDefaults(kvp.Key.Resolve().NetID);
                r.requiredItem[i].stack = kvp.Value;

                i++;
            }

            i = 0;
            foreach (var t in def.RequiredTiles)
            {
                if (i >= Recipe.maxRequirements)
                    break;

                r.requiredTile[i] = t;

                i++;
            }

            r.needWater = (def.RequiredLiquids & RecipeLiquids.Water) != 0;
            r.needLava  = (def.RequiredLiquids & RecipeLiquids.Lava ) != 0;
            r.needHoney = (def.RequiredLiquids & RecipeLiquids.Honey) != 0;

            r.alchemy = def.RequiredTiles.Any(id => id == TileID.Bottles);

            //TODO: set any* to true when TileGroups are defined & implemented
        }
 /// <summary>
 /// Returns true if the recipe has prerequisite ingredients, and those ingredients can currently be crafted.
 /// </summary>
 /// <param name="recipe"></param>
 /// <returns></returns>
 public static bool HasPrerequisiteChoices( Map map, RecipeDef recipe )
 {
     return
         recipe.ingredients.Select( ing => new IngredientSelector( Manager.For( map ), ing, 1, recipe ) )
               .Any( ins => IngredientSelector.HasRecipeChoices( map, ins ) );
 }
 public void SelectRecipe( RecipeDef recipe )
 {
     selectedRecipe = recipe;
     newCount = targetCount.ToString();
     children =
         recipe?.ingredients.Select( ic => new IngredientSelector( manager, ic, targetCount, recipe ) ).ToList();
 }
            public RecipeDef targetRecipe; // the parent recipe itself.

            #endregion Fields

            #region Constructors

            public IngredientSelector( Manager manager, IngredientCount ingredient, int count, RecipeDef targetRecipe )
            {
                // set up vars
                this.ingredient = ingredient;
                this.targetRecipe = targetRecipe;
                this.manager = manager;
                targetCount = (int) Math.Sqrt( count ) * (int) ingredient.GetBaseCount();
                allowedThingDefs = ingredient.filter.AllowedThingDefs.ToList();

                // if there's only one allowed we don't need to manually choose.
                if ( allowedThingDefs.Count == 1 )
                {
                    recipeSelector = new RecipeSelector( manager, allowedThingDefs.First(), targetCount );
                }
            }
        public bool EnoughResourcesInHoppers( RecipeDef recipe )
        {
            //Log.Message( string.Format( "{0}.CompHopperUser.EnoughResourcesInHoppers()", this.parent.ThingID, recipe == null ? "null" : recipe.defName ) );
            var hoppers = FindHoppers();
            if( hoppers.NullOrEmpty() )
            {
                return false;
            }

            var allResources = new List<Thing>();

            foreach( var hopper in hoppers )
            {
                var hopperResources = hopper.GetAllResources( ResourceSettings.filter );
                if( hopperResources != null )
                {
                    allResources.AddRangeUnique( hopperResources );
                }
            }

            List<ThingAmount> chosen = new List<ThingAmount>();
            if( recipe.allowMixingIngredients )
            {
                if( recipe.TryFindBestRecipeIngredientsInSet_AllowMix( allResources, chosen ) )
                {
                    return true;
                }
            }
            else
            {
                if( recipe.TryFindBestRecipeIngredientsInSet_NoMix( allResources, chosen ) )
                {
                    return true;
                }
            }

            return false;
        }
        public bool RemoveResourcesFromHoppers( RecipeDef recipe, List<ThingAmount> chosen )
        {
            //Log.Message( string.Format( "{0}.CompHopperUser.RemoveResourcesFromHoppers( {0}, List<ThingAmount> )", this.parent.ThingID, recipe == null ? "null" : recipe.defName ) );
            var hoppers = FindHoppers();
            if( hoppers.NullOrEmpty() )
            {
                return false;
            }

            var allResources = new List<Thing>();

            foreach( var hopper in hoppers )
            {
                var hopperResources = hopper.GetAllResources( ResourceSettings.filter );
                if( hopperResources != null )
                {
                    allResources.AddRangeUnique( hopperResources );
                }
            }

            bool removeThings = false;
            if( recipe.allowMixingIngredients )
            {
                removeThings = recipe.TryFindBestRecipeIngredientsInSet_AllowMix( allResources, chosen );
            }
            else
            {
                removeThings = recipe.TryFindBestRecipeIngredientsInSet_NoMix( allResources, chosen );
            }
            if( !removeThings )
            {
                return false;
            }

            foreach( var chosenThing in chosen )
            {
                if( chosenThing.count >= chosenThing.thing.stackCount )
                {
                    chosenThing.thing.Destroy();
                }
                else
                {
                    chosenThing.thing.stackCount -= chosenThing.count;
                }
            }

            return true;
        }
        static HelpDef HelpForRecipe( ThingDef thingDef, RecipeDef recipeDef, HelpCategoryDef category )
        {
            var helpDef = new HelpDef();
            helpDef.keyDef = thingDef.defName +"_" + recipeDef.defName;
            helpDef.defName = helpDef.keyDef + "_RecipeDef_Help";
            helpDef.label = recipeDef.label;
            helpDef.category = category;

            var s = new StringBuilder();

            s.AppendLine( recipeDef.description );
            s.AppendLine();

            #region Base Stats

            s.AppendLine( "WorkAmount".Translate() + " : " + GenText.ToStringWorkAmount( recipeDef.WorkAmountTotal( (ThingDef) null ) ) );
            s.AppendLine();

            #endregion

            #region Skill Requirements

            if( ( recipeDef.skillRequirements != null )&&
                ( recipeDef.skillRequirements.Count > 0 ) )
            {
                s.AppendLine( "MinimumSkills".Translate() );
                foreach( var sr in recipeDef.skillRequirements )
                {
                    s.Append( "\t" );
                    s.AppendLine( "BillRequires".Translate( new object[] {
                        sr.minLevel.ToString( "####0" ),
                        sr.skill.label.ToLower()
                    } ) );
                }
                s.AppendLine();
            }

            #endregion

            #region Ingredients

            // List of ingredients
            if( ( recipeDef.ingredients != null )&&
                ( recipeDef.ingredients.Count > 0 ) )
            {
                s.Append( "Ingredients".Translate() );
                s.AppendLine( ":" );
                foreach( var ing in recipeDef.ingredients )
                {
                    if( !GenText.NullOrEmpty( ing.filter.Summary ) )
                    {
                        s.Append( "\t" );
                        s.AppendLine( recipeDef.IngredientValueGetter.BillRequirementsDescription( ing ) );
                    }
                }
                s.AppendLine();
            }

            #endregion

            #region Products

            // List of products
            if( ( recipeDef.products != null )&&
                ( recipeDef.products.Count > 0 ) )
            {
                s.AppendLine( "AutoHelpListRecipeProducts".Translate() );
                foreach( var ing in recipeDef.products )
                {
                    s.Append( "\t" );
                    s.Append( ing.thingDef.LabelCap );
                    s.Append( " : " );
                    s.AppendLine( ing.count.ToString() );
                }
                s.AppendLine();
            }

            #endregion

            #region Things & Research

            // Add things it's on
            var thingDefs = recipeDef.GetThingsCurrent();
            BuildDefDescription( s, "AutoHelpListRecipesOnThings".Translate(), thingDefs.ConvertAll<Def>( def => (Def)def ) );

            // Add research required
            var researchDefs = recipeDef.GetResearchRequirements();
            BuildDefDescription( s, "AutoHelpListResearchRequired".Translate(), researchDefs );

            // What things is it on after research
            thingDefs = recipeDef.GetThingsUnlocked( ref researchDefs );
            BuildDefWithDefDescription( s, "AutoHelpListRecipesOnThingsUnlocked".Translate(), "AutoHelpListResearchBy".Translate(), thingDefs.ConvertAll<Def>( def => (Def)def ), researchDefs.ConvertAll<Def>( def => (Def)def ) );

            // Get research which locks recipe
            thingDefs = recipeDef.GetThingsLocked( ref researchDefs );
            BuildDefWithDefDescription( s, "AutoHelpListRecipesOnThingsLocked".Translate(), "AutoHelpListResearchBy".Translate(), thingDefs.ConvertAll<Def>( def => (Def)def ), researchDefs.ConvertAll<Def>( def => (Def)def ) );

            #endregion

            helpDef.description = s.ToString();
            return helpDef;
        }
        public void SetNewRecipe( RecipeDef newRecipe )
        {
            // clear currently assigned bills.
            CleanUp();

            // set the bill on this job
            Bill = newRecipe.UsesUnfinishedThing
                       ? new Bill_ProductionWithUft( newRecipe )
                       : new Bill_Production( newRecipe );
            _hasMeaningfulIngredientChoices = Dialog_CreateJobsForIngredients.HasPrerequisiteChoices( manager, newRecipe );

            // mainproduct and trigger do not change.
            BillGivers = new BillGiverTracker( this );

            // set the last cache time so it gets updated.
            ForceRecacheOtherRecipe();

            // null targets cache so it gets updated
            _targets = null;
        }
 public static void AddToList( List<HopperSettingsAmount> list, ThingCategoryDef categoryDef, float baseCount, RecipeDef recipe )
 {
     int countNeeded = CountForCategoryDef( categoryDef, baseCount, recipe );
     for( int index = 0; index < list.Count; ++index )
     {
         if( list[ index ].fixedCategoryDef == categoryDef )
         {
             if( countNeeded > list[ index ].fixedCount )
             {
                 list[ index ] = new HopperSettingsAmount( list[ index ].fixedCategoryDef, countNeeded );
             }
             return;
         }
     }
     list.Add( new HopperSettingsAmount( categoryDef, countNeeded ) );
 }
Esempio n. 55
0
 public MainProductTracker( RecipeDef recipe )
 {
     _recipe = recipe;
     Set();
 }
 /// <summary>
 /// Returns true if the recipe has prerequisite ingredients, and those ingredients can currently be crafted.
 /// </summary>
 /// <param name="recipe"></param>
 /// <returns></returns>
 public static bool HasPrerequisiteChoices( RecipeDef recipe )
 {
     return
         recipe.ingredients.Select( ing => new IngredientSelector( ing, 1, recipe ) )
               .Any( IngredientSelector.HasRecipeChoices );
 }
            public static int CountForCategoryDef( ThingCategoryDef categoryDef, float baseCount, RecipeDef recipe )
            {
                int largest = 0;
                foreach( var thingDef in categoryDef.DescendantThingDefs )
                {
                    int thisThingCount = CountForThingDef( thingDef, baseCount, recipe );
                    if( thisThingCount > largest )
                    {
                        largest = thisThingCount;
                    }
                }

                foreach( var childCategoryDef in categoryDef.childCategories )
                {
                    int thisCategoryCount = CountForCategoryDef( childCategoryDef, baseCount, recipe );
                    if( thisCategoryCount > largest )
                    {
                        largest = thisCategoryCount;
                    }
                }

                return largest;
            }
 // hidden in vanilla
 public static Thing GetDominantIngredient(RecipeDef recipe, List<Thing> ingredients)
 {
     // checks if there are any stuff ingredients used which are not forbidden in defaultIngredientFilter
     if (!recipe.products.NullOrEmpty())
     {
         var stuffBasedProduct =
             recipe.products.FirstOrDefault(product => product.thingDef.MadeFromStuff).thingDef;
         if (stuffBasedProduct != null)
         {
             return ingredients.Find(
                 ingredient =>
                     ingredient.def.IsStuff
                     && ingredient.def.stuffProps.CanMake(stuffBasedProduct)
                     && (!recipe.defaultIngredientFilter?.Allows(ingredient.def) ?? true));
         }
     }
     return ingredients.MaxBy(product => product.stackCount);
 }
 public static int CountForThingDef( ThingDef thingDef, float baseCount, RecipeDef recipe )
 {
     if( !recipe.IsIngredient( thingDef ) )
     {
         return 0;
     }
     if( baseCount < 0 )
     {
         foreach( var ingredientCount in recipe.ingredients )
         {
             if( ingredientCount.filter.AllowedThingDefs.Contains( thingDef ) )
             {
                 baseCount = ingredientCount.GetBaseCount();
                 break;
             }
         }
     }
     float ingredientValue = recipe.IngredientValueGetter.ValuePerUnitOf( thingDef );
     return Mathf.Max( 1, Mathf.CeilToInt( baseCount / ingredientValue ) );
 }
        static HelpDef HelpForRecipe( ThingDef thingDef, RecipeDef recipeDef, HelpCategoryDef category )
        {
            var helpDef = new HelpDef();
            helpDef.keyDef = recipeDef;
            helpDef.defName = helpDef.keyDef + "_RecipeDef_Help";
            helpDef.label = recipeDef.label;
            helpDef.category = category;
            helpDef.description = recipeDef.description;

            #region Base Stats

            helpDef.HelpDetailSections.Add( new HelpDetailSection( null, new[] { "WorkAmount".Translate() + " : " + recipeDef.WorkAmountTotal( (ThingDef)null ).ToStringWorkAmount() } ) );

            #endregion

            #region Skill Requirements

            if( !recipeDef.skillRequirements.NullOrEmpty() )
            {
                helpDef.HelpDetailSections.Add( new HelpDetailSection(
                    "MinimumSkills".Translate(),
                    recipeDef.skillRequirements.Select( sr => sr.skill ).ToList().ConvertAll( sd => (Def)sd ),
                    null,
                    recipeDef.skillRequirements.Select( sr => sr.minLevel.ToString( "####0" ) ).ToArray() ) );
            }

            #endregion

            #region Ingredients

            // List of ingredients
            if( !recipeDef.ingredients.NullOrEmpty() )
            {
                // TODO: find the actual thingDefs of ingredients so we can use defs instead of strings.
                HelpDetailSection ingredients = new HelpDetailSection(
                    "Ingredients".Translate(),
                    recipeDef.ingredients.Select(ic => recipeDef.IngredientValueGetter.BillRequirementsDescription( ic )).ToArray());

                helpDef.HelpDetailSections.Add( ingredients );
            }

            #endregion

            #region Products

            // List of products
            if( !recipeDef.products.NullOrEmpty() )
            {
                HelpDetailSection products = new HelpDetailSection(
                    "AutoHelpListRecipeProducts".Translate(),
                    recipeDef.products.Select(tc => tc.thingDef).ToList().ConvertAll(def => (Def)def),
                    recipeDef.products.Select(tc => tc.count.ToString()).ToArray());

                helpDef.HelpDetailSections.Add( products );
            }

            #endregion

            #region Things & Research

            // Add things it's on
            var thingDefs = recipeDef.GetThingsCurrent();
            if( !thingDefs.NullOrEmpty() )
            {
                HelpDetailSection billgivers = new HelpDetailSection(
                    "AutoHelpListRecipesOnThings".Translate(),
                    thingDefs.ConvertAll<Def>(def => (Def)def));

                helpDef.HelpDetailSections.Add( billgivers );
            }

            // Add research required
            var researchDefs = recipeDef.GetResearchRequirements();
            if( !researchDefs.NullOrEmpty() )
            {
                HelpDetailSection requiredResearch = new HelpDetailSection(
                    "AutoHelpListResearchRequired".Translate(),
                    researchDefs);

                helpDef.HelpDetailSections.Add( requiredResearch );
            }

            // What things is it on after research
            thingDefs = recipeDef.GetThingsUnlocked( ref researchDefs );
            if( !thingDefs.NullOrEmpty() )
            {
                HelpDetailSection recipesOnThingsUnlocked = new HelpDetailSection(
                    "AutoHelpListRecipesOnThingsUnlocked".Translate(),
                    thingDefs.ConvertAll<Def>(def => (Def)def));

                helpDef.HelpDetailSections.Add( recipesOnThingsUnlocked );

                if( !researchDefs.NullOrEmpty() )
                {
                    HelpDetailSection researchBy = new HelpDetailSection(
                        "AutoHelpListResearchBy".Translate(),
                        researchDefs.ConvertAll<Def>(def => (Def)def));

                    helpDef.HelpDetailSections.Add( researchBy );
                }
            }

            // Get research which locks recipe
            thingDefs = recipeDef.GetThingsLocked( ref researchDefs );
            if( !thingDefs.NullOrEmpty() )
            {
                HelpDetailSection recipesOnThingsLocked = new HelpDetailSection(
                    "AutoHelpListRecipesOnThingsLocked".Translate(),
                    thingDefs.ConvertAll<Def>(def => (Def)def));

                helpDef.HelpDetailSections.Add( recipesOnThingsLocked );

                if( !researchDefs.NullOrEmpty() )
                {
                    HelpDetailSection researchBy = new HelpDetailSection(
                        "AutoHelpListResearchBy".Translate(),
                        researchDefs.ConvertAll<Def>(def => (Def)def));

                    helpDef.HelpDetailSections.Add( researchBy );
                }
            }

            #endregion

            return helpDef;
        }