Example #1
0
 private static void BindDefsFor(Type type)
 {
     FieldInfo[] fields = type.GetFields();
     for (int i = 0; i < fields.Length; i++)
     {
         FieldInfo fieldInfo = fields[i];
         Type      fieldType = fieldInfo.FieldType;
         if (!typeof(Def).IsAssignableFrom(fieldType))
         {
             Log.Error(fieldType + " is not a Def.");
         }
         else if (fieldType == typeof(SoundDef))
         {
             if (!DefOfHelper.earlyTry)
             {
                 fieldInfo.SetValue(null, SoundDef.Named(fieldInfo.Name));
             }
         }
         else
         {
             Def def = GenDefDatabase.GetDef(fieldType, fieldInfo.Name, !DefOfHelper.earlyTry);
             fieldInfo.SetValue(null, def);
         }
     }
 }
Example #2
0
 private static void BindDefsFor(Type type)
 {
     FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
     foreach (FieldInfo fieldInfo in fields)
     {
         Type fieldType = fieldInfo.FieldType;
         if (!typeof(Def).IsAssignableFrom(fieldType))
         {
             Log.Error(fieldType + " is not a Def.");
         }
         else if (fieldType == typeof(SoundDef))
         {
             SoundDef soundDef = SoundDef.Named(fieldInfo.Name);
             if (soundDef.isUndefined && !earlyTry)
             {
                 Log.Error("Could not find SoundDef named " + fieldInfo.Name);
             }
             fieldInfo.SetValue(null, soundDef);
         }
         else
         {
             Def def = GenDefDatabase.GetDef(fieldType, fieldInfo.Name, !earlyTry);
             fieldInfo.SetValue(null, def);
         }
     }
 }
Example #3
0
 private static void BindDefsFor(Type type)
 {
     FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
     foreach (FieldInfo fieldInfo in fields)
     {
         Type fieldType = fieldInfo.FieldType;
         if (!typeof(Def).IsAssignableFrom(fieldType))
         {
             Log.Error(fieldType + " is not a Def.");
             continue;
         }
         MayRequireAttribute mayRequireAttribute = fieldInfo.TryGetAttribute <MayRequireAttribute>();
         bool              flag = (mayRequireAttribute == null || ModsConfig.IsActive(mayRequireAttribute.modId)) && !earlyTry;
         string            text = fieldInfo.Name;
         DefAliasAttribute defAliasAttribute = fieldInfo.TryGetAttribute <DefAliasAttribute>();
         if (defAliasAttribute != null)
         {
             text = defAliasAttribute.defName;
         }
         if (fieldType == typeof(SoundDef))
         {
             SoundDef soundDef = SoundDef.Named(text);
             if (soundDef.isUndefined && flag)
             {
                 Log.Error("Could not find SoundDef named " + text);
             }
             fieldInfo.SetValue(null, soundDef);
         }
         else
         {
             Def def = GenDefDatabase.GetDef(fieldType, text, flag);
             fieldInfo.SetValue(null, def);
         }
     }
 }
Example #4
0
        public bool RequirementIsMeet()
        {
            Def def = GenDefDatabase.GetDef(defType, defName);

            if (condition == Condition.built)
            {
                return(ConditionEvaluator.EvaluateBuilt(def));
            }
            if (condition == Condition.notbuilt)
            {
                return(!ConditionEvaluator.EvaluateBuilt(def));
            }
            if (condition == Condition.researched)
            {
                return(ConditionEvaluator.EvaluateResearched(def));
            }
            if (condition == Condition.notresearched)
            {
                return(!ConditionEvaluator.EvaluateResearched(def));
            }
            if (condition == Condition.powered)
            {
                return(ConditionEvaluator.EvaluatePowered(def));
            }
            if (condition == Condition.notpowered)
            {
                return(!ConditionEvaluator.EvaluatePowered(def));
            }

            return(false);
        }
Example #5
0
 private static void BindDefsFor(Type type)
 {
     FieldInfo[] fields = type.GetFields(BindingFlags.Static | BindingFlags.Public);
     for (int i = 0; i < fields.Length; i++)
     {
         FieldInfo fieldInfo = fields[i];
         Type      fieldType = fieldInfo.FieldType;
         if (!typeof(Def).IsAssignableFrom(fieldType))
         {
             Log.Error(fieldType + " is not a Def.", false);
         }
         else if (fieldType == typeof(SoundDef))
         {
             SoundDef soundDef = SoundDef.Named(fieldInfo.Name);
             if (soundDef.isUndefined && !DefOfHelper.earlyTry)
             {
                 Log.Error("Could not find SoundDef named " + fieldInfo.Name, false);
             }
             fieldInfo.SetValue(null, soundDef);
         }
         else
         {
             Def def = GenDefDatabase.GetDef(fieldType, fieldInfo.Name, !DefOfHelper.earlyTry);
             fieldInfo.SetValue(null, def);
         }
     }
 }
 public static void RemoveDefaultFacialStuff(Pawn pawn, Dictionary <string, ThingComp> compLookup, HashSet <string> savedComps)
 {
     // If the pawn was saved when facial stuff was not enabled, but it was enabled when they load the pawn,
     // then the pawn will end up with random facial stuff settings, possibly including facial hair.  This post-load action clears
     // out as much of those random settings as possible.
     if (!savedComps.Contains("FacialStuff.CompFace"))
     {
         if (compLookup.TryGetValue("FacialStuff.CompFace", out ThingComp c))
         {
             ReflectionUtil.InvokeActionMethod(c, "InitializeCompFace");
             object pawnFace = ReflectionUtil.GetPropertyValue <object>(c, "PawnFace");
             if (pawnFace == null)
             {
                 //Logger.Debug("Couldn't get the PawnFace value from the comp with class " + c.GetType().FullName);
                 return;
             }
             Type beardDefType = ReflectionUtil.TypeByName("FacialStuff.Defs.BeardDef");
             if (beardDefType == null)
             {
                 //Logger.Debug("Didn't find the beard definition type");
             }
             else
             {
                 Def defaultBeardDef = GenDefDatabase.GetDef(beardDefType, "Beard_Shaved", false);
                 if (defaultBeardDef == null)
                 {
                     //Logger.Debug("Didn't find the default beard definition");
                 }
                 else
                 {
                     ReflectionUtil.SetFieldValue(pawnFace, "_beardDef", defaultBeardDef);
                 }
             }
             Type stacheDefType = ReflectionUtil.TypeByName("FacialStuff.Defs.MoustacheDef");
             if (stacheDefType == null)
             {
                 //Logger.Debug("Didn't find the moustache definition type");
             }
             else
             {
                 Def defaultStacheDef = GenDefDatabase.GetDef(stacheDefType, "Shaved", false);
                 if (defaultStacheDef == null)
                 {
                     //Logger.Debug("Didn't find the default moustache definition");
                 }
                 else
                 {
                     ReflectionUtil.SetFieldValue(pawnFace, "_moustacheDef", defaultStacheDef);
                 }
             }
         }
     }
 }
Example #7
0
        public override Thing CreateThing(bool useOriginalID = false, int stackCount = 0, bool needPirate = false)
        {
            //useOriginalID не используется.

            var   def      = (ThingDef)GenDefDatabase.GetDef(typeof(ThingDef), DefName);
            var   stuffDef = !string.IsNullOrEmpty(StuffName) ? (ThingDef)GenDefDatabase.GetDef(typeof(ThingDef), StuffName) : null;
            Thing thing    = !string.IsNullOrEmpty(StuffName)
                ? ThingMaker.MakeThing(def, stuffDef)
                : ThingMaker.MakeThing(def);

            thing.stackCount = stackCount > 0 ? stackCount : Count;

            if (HitPoints > 0)
            {
                thing.HitPoints = HitPoints;
            }

            SetFaction(thing, isColonist && !needPirate);

            CompQuality compQuality = thing.TryGetComp <CompQuality>();

            if (compQuality != null)
            {
                compQuality.SetQuality((QualityCategory)Quality, ArtGenerationContext.Outsider);
            }

            if (WornByCorpse)
            {
                Apparel thingA = thing as Apparel;
                if (thingA != null)
                {
                    typeof(Apparel)
                    .GetField("wornByCorpseInt", BindingFlags.Instance | BindingFlags.NonPublic)
                    .SetValue(thingA, true);
                }
            }

            thing.Rotation = new Rot4(Rotation);

            Plant thingP = thing as Plant;

            if (thingP != null)
            {
                thingP.Growth = Growth;
            }

            thing.Position = Position.Get();

            return(thing);
        }
Example #8
0
 public override void ExposeData()
 {
     if (Scribe.mode == LoadSaveMode.Saving)
     {
         tmpDefName = ((def != null) ? def.defName : null);
         tmpDefType = ((def != null) ? def.GetType() : null);
     }
     Scribe_Values.Look(ref tmpDefName, "defName");
     Scribe_Values.Look(ref tmpDefType, "defType");
     if (Scribe.mode == LoadSaveMode.LoadingVars && tmpDefName != null)
     {
         def = GenDefDatabase.GetDef(tmpDefType, BackCompatibility.BackCompatibleDefName(tmpDefType, tmpDefName));
     }
 }
Example #9
0
 public override void ExposeData()
 {
     if (Scribe.mode == LoadSaveMode.Saving)
     {
         this.tmpDefName = ((this.def == null) ? null : this.def.defName);
         this.tmpDefType = ((this.def == null) ? null : this.def.GetType());
     }
     Scribe_Values.Look <string>(ref this.tmpDefName, "defName", null, false);
     Scribe_Values.Look <Type>(ref this.tmpDefType, "defType", null, false);
     if (Scribe.mode == LoadSaveMode.LoadingVars && this.tmpDefName != null)
     {
         this.def = GenDefDatabase.GetDef(this.tmpDefType, this.tmpDefName, true);
     }
 }
Example #10
0
        public static void PatchAndroids(Harmony harmony)
        {
            //patch the drawOverviewTab, so we can pass info about the current pawn displayed to the medicalcaresetter
            harmony.Patch(typeof(HealthCardUtility).GetMethod("DrawOverviewTab", BindingFlags.NonPublic | BindingFlags.Static), new HarmonyMethod(typeof(DrawOverviewTab).GetMethod("_Prefix")), new HarmonyMethod(typeof(DrawOverviewTab).GetMethod("_Postfix")));

            //unpatch the medical care select button, we'll take over that for andoirdtiers

            /*var androidMedCareSelectPatch = AccessTools.Inner(AccessTools.TypeByName("MOARANDROIDS.MedicalCareUtility_Patch"), "MedicalCareSelectButton_Patch").GetMethod("Listener", BindingFlags.Static);
             * harmony.Unpatch(typeof(MedicalCareUtility).GetMethod("MedicalCareSelectButton"),androidMedCareSelectPatch);
             */
            harmony.Unpatch(typeof(MedicalCareUtility).GetMethod("MedicalCareSelectButton"), HarmonyPatchType.Prefix, "rimworld.rwmods.androidtiers");

            //get android flesh type
            AndroidFlesh = (FleshTypeDef)GenDefDatabase.GetDef(typeof(FleshTypeDef), "AndroidTier", true);

            //create android-only med list and store
            androidMedList = new List <ModMedicine>();
            humanMedList   = new List <ModMedicine>();

            for (int i = 0; i < medList.Count; i++)
            {
                //always add no care and no medicine
                if (i == 0)
                {
                    androidMedList.Add(medList[i]);
                    humanMedList.Add(medList[i]);
                }
                else if (i == 1)
                {
                    humanMedList.Add(medList[i]);
                    //change no medicine texture for androids
                    androidMedList.Add(new ModMedicine((MedicalCareCategory)1, 0, ContentFinder <Texture2D> .Get("Things/Misc/ATPP_OnlyDocVisit", true)));
                }
                else
                {
                    if (IsAndroidMedicine(medList[i]))
                    {
                        androidMedList.Add(medList[i]);
                    }
                    else
                    {
                        humanMedList.Add(medList[i]);
                    }
                }
            }
        }
        public static void GenerateDescForHediffList(ref StringBuilder builder, List <HediffInfo> hediffs)
        {
            var hediffsNonNull = hediffs?.Where(h => h.def != null);

            if (hediffsNonNull != null)
            {
                if (hediffsNonNull.Any())
                {
                    builder.AppendLine("QE_GenomeSequencerDescription_Hediffs".Translate());

                    //sort hediffs in alphabetical order
                    var ordered = hediffsNonNull.OrderBy(h => h.def.LabelCap);

                    //loop through hediffs and add line to StringBuilder for each
                    foreach (HediffInfo h in ordered)
                    {
                        if (h.part != null)
                        {
                            builder.AppendLine("    " + h.def.LabelCap + " [" + h.part.LabelCap + "]");

                            //Psychic Awakening compatibility
                            if (h.psychicAwakeningPowersKnownDefNames != null && h.psychicAwakeningPowersKnownDefNames?.Count > 0)
                            {
                                foreach (string defName in h.psychicAwakeningPowersKnownDefNames.OrderBy(a => a))
                                {
                                    var psychicPowerDef = GenDefDatabase.GetDef(PsychicAwakeningCompat.PsychicPowerDefType, defName, false);

                                    if (psychicPowerDef != null)
                                    {
                                        builder.AppendLine("        " + psychicPowerDef.LabelCap);
                                    }
                                    else
                                    {
                                        builder.AppendLine("        " + defName);
                                    }
                                }
                            }
                        }
                        else
                        {
                            builder.AppendLine("    " + h.def.LabelCap);
                        }
                    }
                }
            }
        }
Example #12
0
        public Thing CreateThing()
        {
            var   def      = (ThingDef)GenDefDatabase.GetDef(typeof(ThingDef), DefName);
            var   stuffDef = !string.IsNullOrEmpty(StuffName) ? (ThingDef)GenDefDatabase.GetDef(typeof(ThingDef), StuffName) : null;
            Thing thing    = !string.IsNullOrEmpty(StuffName)
                ? ThingMaker.MakeThing(def, stuffDef)
                : ThingMaker.MakeThing(def);

            thing.stackCount = Count;

            if (HitPoints > 0)
            {
                thing.HitPoints = HitPoints;
            }

            CompQuality compQuality = thing.TryGetComp <CompQuality>();

            if (compQuality != null)
            {
                compQuality.SetQuality((QualityCategory)Quality, ArtGenerationContext.Outsider);
            }

            if (WornByCorpse)
            {
                Apparel thingA = thing as Apparel;
                if (thingA != null)
                {
                    typeof(Apparel)
                    .GetField("wornByCorpseInt", BindingFlags.Instance | BindingFlags.NonPublic)
                    .SetValue(thingA, true);
                }
            }

            thing.Rotation = new Rot4(Rotation);

            Plant thingP = thing as Plant;

            if (thingP != null)
            {
                thingP.Growth = Growth;
            }

            return(thing);
        }
Example #13
0
        static void PathAvoidDesignatorSyncWorker(SyncWorker sw, ref Designator designator)
        {
            Def def = null;

            if (sw.isWriting)
            {
                def = (Def)PathAvoidDefField.GetValue(designator);

                sw.Write(def.defName);
            }
            else
            {
                string defName = sw.Read <string>();

                def = GenDefDatabase.GetDef(PathAvoidDefType, defName, false);

                designator = (Designator)Activator.CreateInstance(Designator_PathAvoidType, new object[] { def });
            }
        }
Example #14
0
        public static object Parse(this FieldInfo fieldInfo, string value)
        {
            object val;

            try
            {
                if (fieldInfo.FieldType.IsSubclassOf(typeof(Def)))
                {
                    val = GenDefDatabase.GetDef(fieldInfo.FieldType, value);
                }
                else
                {
                    val = ParseHelper.FromString(value, fieldInfo.FieldType);
                }
                return(val);
            }
            catch (Exception e)
            {
                throw new Exception("Researchable Stat Upgrades :: Exception parsing string: " + e);
            }
        }
Example #15
0
        public override Job JobOnThing(Pawn pawn, Thing t, bool forced = false)
        {
            if (!CanGetThing(pawn, t, forced))
            {
                return(null);
            }

            //plan count and dests
            HaulExplicitlyPosting posting = HaulExplicitly.GetManager(t.Map).PostingWithItem(t);

            if (posting == null)
            {
                return(null);
            }
            int            space_request        = AmountPawnWantsToPickUp(pawn, t, posting);
            var            destInfo             = DeliverableDestinations.For(t, pawn, posting);
            List <IntVec3> dests                = destInfo.RequestSpaceForItemAmount(space_request);
            int            dest_space_available = destInfo.FreeSpaceInCells(dests);
            var            count                = Math.Min(space_request, dest_space_available);

            if (count < 1)
            {
                return(null);
            }

            //make job
            JobDef JobDefOfHaulExplicitly =
                (JobDef)(GenDefDatabase.GetDef(typeof(JobDef), "HaulExplicitlyHaul"));
            Job job = new Job(JobDefOfHaulExplicitly, t, dests.First());

            //((JobDriver_HaulExplicitly)job.GetCachedDriver(pawn)).init();
            job.count        = count;
            job.targetQueueA = new List <LocalTargetInfo>(
                new LocalTargetInfo[] { new IntVec3(posting.id, dest_space_available, 0) });
            job.targetQueueB = new List <LocalTargetInfo>(dests.Skip(1).Take(dests.Count - 1)
                                                          .Select(c => new LocalTargetInfo(c)));
            job.haulOpportunisticDuplicates = true;
            return(job);
        }
        private void TryOrbit()
        {
            //move ship there
            Map newMap = null;
            Map oldMap = parent.Map;

            ShipInteriorMod.Log("Adding world object...");
            Planet.MapParent obj = Planet.WorldObjectMaker.MakeWorldObject(GenDefDatabase.GetDef(typeof(WorldObjectDef), "OrbitShip") as WorldObjectDef) as Planet.MapParent;
            obj.Tile = oldMap.Tile;

            Find.World.worldObjects.Add(obj);

            //create world map pawn for ship
            LongEventHandler.QueueLongEvent(() =>
            {
                ShipInteriorMod.Log("Generating map...");
                //generate orbit map
                var generatorDef = GenDefDatabase.GetDef(typeof(MapGeneratorDef), "Orbit") as MapGeneratorDef;
                ShipInteriorMod.noSpaceWeather = true;
                newMap = MapGenerator.GenerateMap(oldMap.Size, obj, generatorDef, obj.ExtraGenStepDefs, null);
                ShipInteriorMod.noSpaceWeather = false;
            }, "Orbit_Generate", doAsynchronously: true, exceptionHandler: GameAndMapInitExceptionHandlers.ErrorWhileGeneratingMap);

            oldMap
            .GetSpaceAtmosphereMapComponent()
            .DefinitionAt(parent.Position)
            .Move(oldMap, () => newMap, "Orbit", true, Handler, (AirShipWorldObject)obj)
            .Then(() =>
            {
                HashSet <RoomGroup> processedGroups = new HashSet <RoomGroup>();
                foreach (var room in newMap.regionGrid.allRooms)
                {
                    var group = room.Group;
                    if (!processedGroups.Contains(group))
                    {
                        processedGroups.Add(group);
                        group.Temperature = 21f;     // initialize life support
                    }
                }
            }, "Orbit_Temperature", Handler)
            .Then(() =>
            {
                //generate some meteors
                ShipInteriorMod.Log("Generating meteors...");
                int numMeteors = Rand.Range(ShipInteriorMod.instance.meteorMinCount.Value, ShipInteriorMod.instance.meteorMaxCount.Value);
                for (int i = 0; i < numMeteors; i++)
                {
                    if (!TryFindCell(out IntVec3 cell, newMap))
                    {
                        ShipInteriorMod.Log("Nowhere for meteor!?!");
                        continue;
                    }

                    ShipInteriorMod.Log("Found cell for meteor!");

                    List <Thing> list = new List <Thing>();
                    for (int m = 0; m < ShipInteriorMod.instance.meteorSizeMultiplier.Value; m++)
                    {
                        list.AddRange(ThingSetMakerDefOf.Meteorite.root.Generate());
                    }
                    ShipInteriorMod.Log("Meteor has " + list.Count + " chunks!");
                    for (int num = list.Count - 1; num >= 0; num--)
                    {
                        ShipInteriorMod.Log("Placing chunk!");
                        GenPlace.TryPlaceThing(list[num], cell, newMap, ThingPlaceMode.Near, (Thing thing, int count) =>
                        {
                            PawnUtility.RecoverFromUnwalkablePositionOrKill(thing.Position, thing.Map);
                        });
                    }
                }
            }, "Orbit_Meteors", Handler)
            .Then(() => { Current.Game.CurrentMap = newMap; }, "Orbit_Swap", Handler)
            .Then(() => {
                foreach (var cell in Find.CurrentMap.areaManager.Home.ActiveCells.ToList())
                {
                    if (!Find.CurrentMap.thingGrid.ThingsAt(cell).Any(x => (x.def.building?.shipPart).GetValueOrDefault(false)))
                    {
                        Find.CurrentMap.areaManager.Home[cell] = false;
                    }
                }
                foreach (var pawn in Find.CurrentMap.mapPawns.AllPawns.Where(p => p.Faction == Faction.OfPlayer))
                {
                    pawn.playerSettings.AreaRestriction = Find.CurrentMap.areaManager.Home;
                }
            }, "Orbit_Swap", Handler);


            //do cool graphic?
        }
        public static void ApplyBrainScanTemplateOnPawn(Pawn thePawn, BrainScanTemplate brainScan, float efficency = 1f)
        {
            if (thePawn.IsValidBrainScanningTarget())
            {
                //Backgrounds
                Pawn_StoryTracker storyTracker = thePawn.story;
                if (storyTracker != null)
                {
                    //story.childhood = brainScan.backStoryChild;
                    storyTracker.adulthood = brainScan.backStoryAdult;
                }

                //Skills
                Pawn_SkillTracker skillTracker = thePawn.skills;
                if (skillTracker != null)
                {
                    foreach (ComparableSkillRecord skill in brainScan.skills)
                    {
                        SkillRecord pawnSkill = skillTracker.GetSkill(skill.def);
                        pawnSkill.Level   = (int)Math.Floor((float)skill.level * efficency);
                        pawnSkill.passion = skill.passion;
                        pawnSkill.Notify_SkillDisablesChanged();
                    }
                }

                //Training
                Pawn_TrainingTracker trainingTracker = thePawn.training;
                if (trainingTracker != null)
                {
                    DefMap <TrainableDef, bool> learned = (DefMap <TrainableDef, bool>)AccessTools.Field(typeof(Pawn_TrainingTracker), "learned").GetValue(trainingTracker);
                    DefMap <TrainableDef, int>  steps   = (DefMap <TrainableDef, int>)AccessTools.Field(typeof(Pawn_TrainingTracker), "steps").GetValue(trainingTracker);

                    //Copy
                    foreach (var item in brainScan.trainingLearned)
                    {
                        learned[item.Key] = item.Value;
                    }
                    foreach (var item in brainScan.trainingSteps)
                    {
                        steps[item.Key] = (int)Math.Floor((float)item.Value * efficency);
                    }
                }

                //Add Hediffs
                thePawn.health.AddHediff(QEHediffDefOf.QE_BrainTemplated);
                if (brainScan.hediffInfos != null && brainScan.hediffInfos?.Count > 0)
                {
                    //add hediffs to pawn from defs in HediffInfo class
                    foreach (HediffInfo h in brainScan.hediffInfos)
                    {
                        Hediff addedHediff = thePawn.health.AddHediff(h.def, h.part);

                        //Psychic Awakened compatibility
                        if (h.psychicAwakeningPowersKnownDefNames != null && h.psychicAwakeningPowersKnownDefNames?.Count > 0)
                        {
                            //create a List of the type PsychicPowerDef via Reflection. Cast it as IList to interact with it.
                            var   listType        = typeof(List <>).MakeGenericType(PsychicAwakeningCompat.PsychicPowerDefType);
                            var   powers          = Activator.CreateInstance(listType);
                            IList powersInterface = (IList)powers;

                            //iterate through the defNames saved in the list inside HediffInfo
                            foreach (string defName in h.psychicAwakeningPowersKnownDefNames)
                            {
                                //look for this PsychicPowerDef in the DefDatabase
                                var psychicPowerDef = GenDefDatabase.GetDef(PsychicAwakeningCompat.PsychicPowerDefType, defName, false);

                                if (psychicPowerDef != null)
                                {
                                    //add this to the list
                                    powersInterface.Add(psychicPowerDef);
                                }
                                else
                                {
                                    QEEMod.TryLog("Psychic Power def " + defName + " not loaded in database of Rimworld Defs. This power will not be applied.");
                                }
                            }

                            if (powersInterface.Count > 0)
                            {
                                QEEMod.TryLog("assigning " + powersInterface.Count + " psychic powers to " + thePawn.LabelCap + " from brain template");

                                PsychicAwakeningCompat.powersKnownField.SetValue(addedHediff, powers);
                            }
                        }
                    }
                }

                Messages.Message("QE_BrainTemplatingComplete".Translate(thePawn.Named("PAWN")), MessageTypeDefOf.PositiveEvent, false);
            }
        }
Example #18
0
 public override void ResolveReferences(ThingDef parentDef)
 {
     base.ResolveReferences(parentDef);
     defaultStuffDef = (ThingDef)GenDefDatabase.GetDef(typeof(ThingDef), defaultStuff, true);
 }
Example #19
0
        /// <summary>
        /// область снизу справа - просмотр и редактирование ордера
        /// </summary>
        /// <param name="inRect"></param>
        public void DoWindowEditOrder(Rect inRect)
        {
            if (PlaceCurrent == null)
            {
                PlaceCurrent = new Place();
                WorldObject wo;
                if (PlaceMap != null)
                {
                    wo = PlaceMap.info.parent;
                }
                else
                {
                    wo = PlaceCaravan;
                }
                PlaceCurrent.Name          = wo.LabelCap;
                PlaceCurrent.PlaceServerId = UpdateWorldController.GetServerInfo(wo).ServerId;
                PlaceCurrent.ServerName    = SessionClientController.My.ServerName;
                PlaceCurrent.Tile          = wo.Tile;
                PlaceCurrent.DayPath       = 0;
            }
            if (EditOrder == null)
            {
                //Действие не выбрано: по умолчанию настраиваем панельна создание нового ордера
                EditOrderTitle = "OCity_Dialog_Exchenge_Order_Create".Translate();
                var editOrder = new OrderTrade();
                editOrder.Owner         = SessionClientController.My;
                editOrder.Place         = PlaceCurrent;
                editOrder.CountBeginMax = 1;

                editOrder.SellThings = new List <ThingTrade>();
                editOrder.BuyThings  = new List <ThingTrade>();
                var silverDef = (ThingDef)GenDefDatabase.GetDef(typeof(ThingDef), "Silver");
                var th        = ThingTrade.CreateTrade(silverDef, 0f, QualityCategory.Awful, 1);
                editOrder.BuyThings.Add(th);

                editOrder.PrivatPlayers = new List <Player>();

                SetEditOrder(editOrder);
            }

            bool existInServer = EditOrder.Id != 0;

            //заголовок
            Rect rect = new Rect(0f, 0f, inRect.width, 18);

            inRect.yMin += rect.height;
            Text.Font    = GameFont.Tiny; // высота Tiny 18
            Text.Anchor  = TextAnchor.MiddleCenter;
            Widgets.Label(rect, EditOrderTitle);

            ///todo
            ///полоску проскрутки

            //кнопка в углу
            rect = new Rect(inRect.width - 150f, 20f, 150f, 24);
            if (!EditOrderToTrade)
            {
                GUI.color = Color.red;
            }
            if (Widgets.ButtonText(rect.ContractedBy(1f)
                                   , EditOrderIsMy
                    ? existInServer ? "OCity_Dialog_Exchenge_Save".Translate() : "OCity_Dialog_Exchenge_Create".Translate()
                    : "OCity_Dialog_Exchenge_Trade".Translate()
                                   , true, false, true))
            {
                GUI.color = Color.white;
                SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
                if (!EditOrderToTrade)
                {
                    return;
                }

                if (!EditOrderIsMy)
                {
                    //торговать
                    //todo
                }
                else
                {
                    //создать или отредактировать
                    SessionClientController.Command((connect) =>
                    {
                        SoundDefOf.Tick_High.PlayOneShotOnCamera(null);

                        if (!connect.ExchengeEdit(EditOrder))
                        {
                            Loger.Log("Client ExchengeEdit error: " + connect.ErrorMessage);
                            Find.WindowStack.Add(new Dialog_Input("OCity_Dialog_Exchenge_Action_Not_CarriedOut".Translate(), connect.ErrorMessage, true));
                        }
                        else
                        {
                            SetEditOrder(null);
                        }

                        UpdateOrders();
                    });
                    return;
                }

                EditOrderChange();
                return;
            }
            GUI.color = Color.white;

            //кнопка
            if (!EditOrderIsMy)
            {
                rect = new Rect(160f, 20f, inRect.width - 160f - 160f, 24);
                if (Widgets.ButtonText(rect.ContractedBy(1f)
                                       , "OCity_Dialog_Exchenge_Counterproposal".Translate()
                                       , true, false, true))
                {
                    SoundDefOf.Tick_High.PlayOneShotOnCamera(null);

                    //todo

                    return;
                }
            }
            if (EditOrderIsMy && existInServer && EditOrder.Id != 0)
            {
                rect = new Rect(160f, 20f, 100f, 24);
                if (Widgets.ButtonText(rect.ContractedBy(1f)
                                       , "OCity_Dialog_Exchenge_Delete".Translate()
                                       , true, false, true))
                {
                    SoundDefOf.Tick_High.PlayOneShotOnCamera(null);

                    SessionClientController.Command((connect) =>
                    {
                        SoundDefOf.Tick_High.PlayOneShotOnCamera(null);

                        EditOrder.Id = -EditOrder.Id;
                        if (!connect.ExchengeEdit(EditOrder))
                        {
                            EditOrder.Id = -EditOrder.Id;
                            Loger.Log("Client ExchengeEdit error: " + connect.ErrorMessage);
                            Find.WindowStack.Add(new Dialog_Input("OCity_Dialog_Exchenge_Action_Not_CarriedOut".Translate(), connect.ErrorMessage, true));
                        }
                        else
                        {
                            SetEditOrder(null);
                        }

                        UpdateOrders();
                    });

                    return;
                }
            }

            rect = new Rect(0, 20f, 150f, 24f);
            if (Widgets.ButtonText(rect.ContractedBy(1f)
                                   , "OCity_Dialog_Exchenge_Order_New".Translate()
                                   , true, false, true))
            {
                SoundDefOf.Tick_High.PlayOneShotOnCamera(null);

                SetEditOrder(null);

                return;
            }

            inRect.yMin += rect.height;

            rect        = new Rect(0f, 44f, inRect.width, 24f);
            Text.Anchor = TextAnchor.MiddleLeft;

            if (EditOrderIsMy)
            {
                Widgets.Label(rect, "OCity_Dialog_Exchenge_No_Exchanges".Translate());
                var rect2 = new Rect(rect.x + 250f, rect.y, 70f, rect.height);

                int    countToTransfer = EditOrder.CountBeginMax;
                string editBuffer;
                if (!EditOrderEditBuffer.TryGetValue(EditOrder.GetHashCode(), out editBuffer))
                {
                    EditOrderEditBuffer.Add(EditOrder.GetHashCode(), editBuffer = countToTransfer.ToString());
                }
                Widgets.TextFieldNumeric <int>(rect2.ContractedBy(2f), ref countToTransfer, ref editBuffer, 1f, 999999999f);
                EditOrderEditBuffer[EditOrder.GetHashCode()] = editBuffer;
                if (countToTransfer > 0)
                {
                    EditOrder.CountBeginMax = countToTransfer;
                    EditOrderChange();
                }

                rect.y += 24f;
            }

            Widgets.Label(rect, "OCity_Dialog_Exchenge_No_Available_Exchange".Translate() + EditOrder.CountReady.ToString());
            if (EditOrderIsMy)
            {
                rect.xMin += 250;
                Widgets.Label(rect, "OCity_Dialog_Exchenge_Done_Once".Translate() + EditOrder.CountFnished.ToString());
                rect.xMin = 0;
            }
            rect.y += 24f;

            if (EditOrderIsMy)
            {
                Widgets.Label(rect, "OCity_Dialog_Exchenge_We_Give".Translate());
                rect.y += 24f;
                EditOrderShowSellThings(ref rect);

                Widgets.Label(rect, "OCity_Dialog_Exchenge_We_Get".Translate());
                rect.y += 24f;
                EditOrderShowBuyThings(ref rect);
            }
            else
            {
                Widgets.Label(rect, "OCity_Dialog_Exchenge_We_Get".Translate());
                rect.y += 24f;
                EditOrderShowBuyThings(ref rect);

                Widgets.Label(rect, "OCity_Dialog_Exchenge_We_Give2".Translate(EditOrder.Owner.Login));
                rect.y += 24f;
                EditOrderShowSellThings(ref rect);
            }

            if (EditOrder.PrivatPlayers == null || EditOrder.PrivatPlayers.Count == 0)
            {
                Widgets.Label(rect, "OCity_Dialog_Exchenge_No_User_Restrictions".Translate());
                rect.y += 24f;
            }
            else
            {
                Widgets.Label(rect, "OCity_Dialog_Exchenge_User_Restrictions".Translate());
                rect.y += 24f;
                for (int i = 0; i < EditOrder.PrivatPlayers.Count; i++)
                {
                    var rect3 = new Rect(rect.x, rect.y, 24f, 24f);
                    Widgets.Label(rect3, EditOrder.PrivatPlayers[i].Login);

                    rect3 = new Rect(rect.xMax - 24f, rect.y, 24f, 24f);
                    if (EditOrderIsMy && Widgets.ButtonImage(rect3, IconDelTex))
                    {
                        EditOrder.PrivatPlayers.RemoveAt(i--);
                    }
                    rect.y += 24f;
                }
            }
            var rect4 = new Rect(rect);

            rect4.width = 150f;
            if (Widgets.ButtonText(rect4.ContractedBy(1f)
                                   , "OCity_Dialog_Exchenge_Add_User".Translate()
                                   , true, false, true))
            {
                SoundDefOf.Tick_High.PlayOneShotOnCamera(null);

                var editOrder = EditOrder;
                var list      = SessionClientController.Data.Players.Keys
                                .Where(p => !editOrder.PrivatPlayers.Any(pp => pp.Login == p) && p != "system")
                                .Select(p => new FloatMenuOption(p,
                                                                 () =>
                {
                    if (editOrder.PrivatPlayers.Any(pp => pp.Login == p))
                    {
                        return;
                    }
                    editOrder.PrivatPlayers.Add(SessionClientController.Data.Players[p].Public);
                }))
                                .ToList();
                if (list.Count == 0)
                {
                    return;
                }
                var menu = new FloatMenu(list);
                Find.WindowStack.Add(menu);

                return;
            }
        }
Example #20
0
 public Def GetDef(Type defType) =>
 GenDefDatabase.GetDef(defType, this.defName);