protected override void HandleChooser()
		{
			using (var dlg = new GenDateChooserDlg(m_mediator.HelpTopicProvider))
			{
				dlg.Text = string.Format(DetailControlsStrings.ksFieldChooserDlgTitle, m_fieldName);
				GenDate x = (m_cache.DomainDataByFlid as ISilDataAccessManaged).get_GenDateProp(m_obj.Hvo, m_flid);
				// If we don't yet have a value, make today the default.
				if (x.IsEmpty)
				{
					DateTime now = DateTime.Now;
					x = new GenDate(GenDate.PrecisionType.Exact, now.Month, now.Day, now.Year, true);
				}
				dlg.GenericDate = x;
				if (dlg.ShowDialog(m_mediator.PropertyTable.GetValue("window") as IWin32Window) == DialogResult.OK)
				{
					var genDate = dlg.GenericDate;
					UndoableUnitOfWorkHelper.Do(string.Format(DetailControlsStrings.ksUndoSet, m_fieldName),
						string.Format(DetailControlsStrings.ksRedoSet, m_fieldName), m_obj, () =>
					{
						(m_cache.DomainDataByFlid as ISilDataAccessManaged).SetGenDate(m_obj.Hvo, m_flid, genDate);
					});
					m_genDateTextBox.Text = genDate.ToLongString();
				}
			}
		}
        public static bool Prefix(
            Rect dateRect,
            ref List <string> ___seasonsCached,
            ref int ___dateStringDay,
            ref Season ___dateStringSeason,
            ref Quadrum ___dateStringQuadrum,
            ref int ___dateStringYear,
            ref string ___dateString
            )
        {
            Vector2 vector2;

            if (WorldRendererUtility.WorldRenderedNow && Find.WorldSelector.selectedTile >= 0)
            {
                vector2 = Find.WorldGrid.LongLatOf(Find.WorldSelector.selectedTile);
            }
            else if (WorldRendererUtility.WorldRenderedNow && Find.WorldSelector.NumSelectedObjects > 0)
            {
                vector2 = Find.WorldGrid.LongLatOf(Find.WorldSelector.FirstSelectedObject.Tile);
            }
            else
            {
                if (Find.CurrentMap == null)
                {
                    return(false);
                }
                vector2 = Find.WorldGrid.LongLatOf(Find.CurrentMap.Tile);
            }

            var num1     = GenDate.DayOfTwelfth(Find.TickManager.TicksAbs, vector2.x);
            var season   = GenDate.Season(Find.TickManager.TicksAbs, vector2);
            var quadrum1 = GenDate.Quadrum(Find.TickManager.TicksAbs, vector2.x);
            var num2     = GenDate.Year(Find.TickManager.TicksAbs, vector2.x);
            var str      = true ? ___seasonsCached[(int)season] : "";

            if (num1 != ___dateStringDay || season != ___dateStringSeason || quadrum1 != ___dateStringQuadrum || num2 != ___dateStringYear)
            {
                ___dateString        = GenDate.DateReadoutStringAt(Find.TickManager.TicksAbs, vector2);
                ___dateStringDay     = num1;
                ___dateStringSeason  = season;
                ___dateStringQuadrum = quadrum1;
                ___dateStringYear    = num2;
            }

            var userTime = "";

            if (!BetterTimeFormatMod.UpdateTime)
            {
                userTime = BetterTimeFormatMod.settings.timeFormat;
                var dayPercent = GenLocalDate.DayPercent(Find.CurrentMap);

                if (BetterTimeFormatMod.UpdateHours)
                {
                    var hours = Math.Floor(dayPercent * 24);
                    if (BetterTimeFormatMod.settings.twelveHourFormat)
                    {
                        hours = dayPercent < 0.6 ? hours : hours - 12;
                    }

                    userTime = userTime.ReplaceFirst("HH", $"{hours,0:00}");
                    userTime = userTime.ReplaceFirst("H", $"{hours,0}");
                }

                if (BetterTimeFormatMod.UpdateMinutes)
                {
                    var minutes = Math.Floor(dayPercent * 24 % 1 * 60);
                    userTime = userTime.ReplaceFirst("MM", $"{minutes,0:00}");
                    userTime = userTime.ReplaceFirst("M", $"{minutes,0:0}");
                }

                if (BetterTimeFormatMod.UpdateSeconds)
                {
                    var seconds = Math.Floor(dayPercent * 24 % 1 * 60 % 1 * 60);
                    userTime = userTime.ReplaceFirst("SS", $"{seconds,0:00}");
                    userTime = userTime.ReplaceFirst("S", $"{seconds,0:0}");
                }

                if (BetterTimeFormatMod.settings.twelveHourFormat)
                {
                    var notation = dayPercent < 0.5 ? BetterTimeFormatMod.settings.amString : BetterTimeFormatMod.settings.pmString;
                    userTime = userTime.ReplaceFirst("N", notation);
                }
            }

            Text.Font = GameFont.Small;
            var num3 =
                Mathf.Max(Mathf.Max(Text.CalcSize(userTime).x, Text.CalcSize(___dateString).x), Text.CalcSize(str).x) + 7f;

            dateRect.xMin = dateRect.xMax - num3;
            if (Mouse.IsOver(dateRect))
            {
                Widgets.DrawHighlight(dateRect);
            }
            GUI.BeginGroup(dateRect);
            Text.Font   = GameFont.Small;
            Text.Anchor = TextAnchor.UpperRight;
            var rect = dateRect.AtZero();

            rect.xMax -= 7f;
            Widgets.Label(rect, userTime);
            rect.yMin += 26f;
            Widgets.Label(rect, ___dateString);
            rect.yMin += 26f;
            if (!str.NullOrEmpty())
            {
                Widgets.Label(rect, str);
            }
            Text.Anchor = TextAnchor.UpperLeft;
            GUI.EndGroup();
            if (!Mouse.IsOver(dateRect))
            {
                return(false);
            }
            var stringBuilder = new StringBuilder();

            for (var index2 = 0; index2 < 4; ++index2)
            {
                var quadrum2 = (Quadrum)index2;
                stringBuilder.AppendLine(quadrum2.Label() + " - " + quadrum2.GetSeason(vector2.y).LabelCap());
            }

            var taggedString = "DateReadoutTip".Translate(GenDate.DaysPassed, 15, (NamedArgument)season.LabelCap(), 15,
                                                          (NamedArgument)GenDate.Quadrum(GenTicks.TicksAbs, vector2.x).Label(), (NamedArgument)stringBuilder.ToString());

            TooltipHandler.TipRegion(dateRect, new TipSignal(taggedString, 86423));

            return(false);
        }
Exemple #3
0
        // Token: 0x06000022 RID: 34 RVA: 0x00002868 File Offset: 0x00000A68
        public override string CompInspectStringExtra()
        {
            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendLine(this.StatusInfo());
            if (!this.Empty && !this.Ruined)
            {
                if (this.Fermented)
                {
                    stringBuilder.AppendLine(TranslatorFormattedStringExtensions.Translate("VG_ContainsProduct", this.ingredientCount, this.Product.maxCapacity, this.Product.thingDef.label));
                }
                else
                {
                    stringBuilder.AppendLine(TranslatorFormattedStringExtensions.Translate("VG_ContainsIngredient", this.ingredientCount, this.Product.maxCapacity, this.SummaryAddedIngredients));
                }
            }
            if (!this.Empty)
            {
                if (this.Fermented)
                {
                    stringBuilder.AppendLine(Translator.Translate("VG_Finished"));
                }
                else
                {
                    stringBuilder.AppendLine(TranslatorFormattedStringExtensions.Translate("FermentationProgress", GenText.ToStringPercent(this.Progress), GenDate.ToStringTicksToPeriod(this.EstimatedTicksLeft)));
                    if (this.CurrentTempProgressSpeedFactor != 1f)
                    {
                        stringBuilder.AppendLine(TranslatorFormattedStringExtensions.Translate("FermentationBarrelOutOfIdealTemperature", GenText.ToStringPercent(this.CurrentTempProgressSpeedFactor)));
                    }
                }
            }
            stringBuilder.AppendLine(string.Concat(new string[]
            {
                Translator.Translate("VG_IdealSafeFermentingTemperature"),
                ": ",
                GenText.ToStringTemperature(this.Product.temperatureIdeal.min, "F0"),
                "~",
                GenText.ToStringTemperature(this.Product.temperatureIdeal.max, "F0"),
                " (",
                GenText.ToStringTemperature(this.Product.temperatureSafe.min, "F0"),
                "~",
                GenText.ToStringTemperature(this.Product.temperatureSafe.max, "F0"),
                ")"
            }));
            return(GenText.TrimEndNewlines(stringBuilder.ToString()));
        }
Exemple #4
0
        public IEnumerable <Event> GetByEventTypeAndDate(IEnumerable <int> eventTypeIds, GenDate date)
        {
            var query = GetBaseQuery().Where(GetWhereEventTypeIn()).And(GetWhereDate());

            return(GetListSql(query, new { EventTypeIds = eventTypeIds, date.From, date.To }));
        }
Exemple #5
0
        public override void Tick(int currentTick)
        {
            base.Tick(currentTick);

            int ticks = Find.TickManager.TicksAbs;

            if (ticks % GenDate.TicksPerHour != 0 || Find.CurrentMap == null || _store == null)
            {
                return;
            }

            Vector2 location     = Find.WorldGrid.LongLatOf(Find.CurrentMap.Tile);
            Quadrum quadrum      = GenDate.Quadrum(ticks, location.x);
            int     dayOfQuadrum = GenDate.DayOfQuadrum(ticks, location.x); // zero based
            int     hour         = GenDate.HourOfDay(ticks, location.x);

            // check settlement
            int     startTicks        = Find.TickManager.gameStartAbsTick;
            Quadrum settlementQuadrum = GenDate.Quadrum(startTicks, 0);
            int     settlementDay     = GenDate.DayOfQuadrum(startTicks, 0); // zero based
            int     settlementYears   = Mathf.RoundToInt(GenDate.YearsPassedFloat);

            if ((hour == 0 || _store.Settlement.Start() == hour) && settlementQuadrum == quadrum && settlementDay == dayOfQuadrum)
            {
                if (hour == 0)
                {
                    Messages.Message("DM.Message.TodaySettlement".Translate(settlementYears), MessageTypeDefOf.PositiveEvent);
                }
                else
                {
                    StartParty("DM.Letter.SettlementParty".Translate(), new List <Pawn>(), _store.Settlement == Duration.AllDay);
                }
            }

            // check built in days
            if (hour == 0 || _store.Birthdays.Start() == hour || _store.MarriageAnniversaries.Start() == hour || _store.LoversAnniversaries.Start() == hour)
            {
                Dictionary <Pawn, DirectPawnRelation> handledRelations = new Dictionary <Pawn, DirectPawnRelation>();

                var colonists = Find.CurrentMap.mapPawns.PawnsInFaction(Faction.OfPlayer);
                foreach (var colonist in colonists)
                {
                    if (colonist.Dead || !colonist.RaceProps.Humanlike)
                    {
                        continue;
                    }

                    // check marriage
                    List <DirectPawnRelation> marriageRelations = colonist.relations.DirectRelations.FindAll(x => x.def == PawnRelationDefOf.Spouse);
                    foreach (DirectPawnRelation relation in marriageRelations)
                    {
                        if (handledRelations.ContainsKey(colonist) || handledRelations.ContainsKey(relation.otherPawn))
                        {
                            continue;
                        }
                        handledRelations.Add(colonist, relation);
                        int     startTick    = relation.startTicks + startTicks;
                        int     startDay     = GenDate.DayOfQuadrum(startTick, location.x);
                        Quadrum startQuadrum = GenDate.Quadrum(startTick, location.x);
                        if (startDay == dayOfQuadrum && startQuadrum == quadrum)
                        {
                            if (hour == 0)
                            {
                                Messages.Message("DM.Message.TodayMarriageAnniversary".Translate(colonist.Name.ToStringShort, relation.otherPawn.Name.ToStringShort), MessageTypeDefOf.PositiveEvent);
                            }
                            else if (_store.MarriageAnniversaries.Start() == hour)
                            {
                                StartParty("DM.Letter.MarriageAnniversaryParty".Translate(colonist.Name.ToStringShort, relation.otherPawn.Name.ToStringShort), new List <Pawn> {
                                    colonist, relation.otherPawn
                                }, _store.MarriageAnniversaries == Duration.AllDay, colonist);
                            }
                        }
                    }

                    // check relationship
                    List <DirectPawnRelation> loverRelations = colonist.relations.DirectRelations.FindAll(x => x.def == PawnRelationDefOf.Lover);
                    foreach (DirectPawnRelation relation in loverRelations)
                    {
                        if (handledRelations.ContainsKey(colonist) || handledRelations.ContainsKey(relation.otherPawn))
                        {
                            continue;
                        }
                        handledRelations.Add(colonist, relation);
                        int     startTick    = relation.startTicks + startTicks;
                        int     startDay     = GenDate.DayOfQuadrum(startTick, location.x);
                        Quadrum startQuadrum = GenDate.Quadrum(startTick, location.x);
                        if (startDay == dayOfQuadrum && startQuadrum == quadrum)
                        {
                            if (hour == 0)
                            {
                                Messages.Message("DM.Message.TodayRelationshipAnniversary".Translate(colonist.Name.ToStringShort, relation.otherPawn.Name.ToStringShort), MessageTypeDefOf.PositiveEvent);
                            }
                            else if (_store.LoversAnniversaries.Start() == hour)
                            {
                                StartParty("DM.Letter.RelationshipAnniversaryParty".Translate(colonist.Name.ToStringShort, relation.otherPawn.Name.ToStringShort), new List <Pawn> {
                                    colonist, relation.otherPawn
                                }, _store.LoversAnniversaries == Duration.AllDay, colonist);
                            }
                        }
                    }

                    // check birthday
                    long    birthdayTick = colonist.ageTracker.BirthAbsTicks;
                    int     birthDate    = GenDate.DayOfQuadrum(birthdayTick, location.x); // zero based
                    Quadrum birthQuadrum = GenDate.Quadrum(birthdayTick, location.x);
                    int     colonistAge  = Mathf.RoundToInt(colonist.ageTracker.AgeChronologicalYearsFloat);
                    if (birthDate == dayOfQuadrum && birthQuadrum == quadrum)
                    {
                        if (hour == 0)
                        {
                            Messages.Message("DM.Message.TodayBirthday".Translate(colonist.Name.ToStringShort, colonistAge), MessageTypeDefOf.PositiveEvent);
                        }
                        else if (_store.Birthdays.Start() == hour)
                        {
                            StartParty("DM.Letter.BirthdayParty".Translate(colonist.Name.ToStringShort), new List <Pawn>(), _store.Birthdays == Duration.AllDay);
                        }
                    }
                }
            }

            // check custom days
            var matchedEvents = _store.MatteredDays.FindAll(x => x.DayOfQuadrum - 1 == dayOfQuadrum && x.Quadrum == quadrum);

            if (matchedEvents.Count == 0)
            {
                return;
            }

            foreach (MatteredDay day in matchedEvents)
            {
                if (hour == 0)
                {
                    Messages.Message("DM.Message.TodayCustomDay".Translate(day.Name), MessageTypeDefOf.PositiveEvent);
                }
                else if (day.Duration.Start() == hour)
                {
                    StartParty("DM.Letter.CustomDayParty".Translate(day.Name), new List <Pawn>(), day.Duration == Duration.AllDay);
                }
            }
        }
		private static void VerifyGenDate(CustomFieldData fieldData, GenDate genDate)
		{
			//"<trait name=\"CustomFldEntry GenDate\" value=\"201105232\"/>",
			//   '-'(BC and ''AD) 2011 05(May) 11(Day) 2(GenDate.PrecisionType (Before, Exact, Approximate, After)
			var sValue = fieldData.GenDateLiftFormat;
			Assert.IsNotNull(sValue);
			var liftGenDate = LiftExporter.GetGenDateFromInt(Convert.ToInt32(sValue));
			Assert.AreEqual(liftGenDate.Precision, genDate.Precision);
			Assert.AreEqual(liftGenDate.IsAD, genDate.IsAD);
			Assert.AreEqual(liftGenDate.Year, genDate.Year);
			Assert.AreEqual(liftGenDate.Month, genDate.Month);
			Assert.AreEqual(liftGenDate.Day, genDate.Day);
		}
		/// <summary>
		/// Set the generic date property.
		/// </summary>
		/// <param name="hvo">The hvo.</param>
		/// <param name="tag">The tag.</param>
		/// <param name="genDate">The generic date.</param>
		public override void SetGenDate(int hvo, int tag, GenDate genDate)
		{
			m_domainDataByFlid.SetGenDate(hvo, tag, genDate);
		}
Exemple #8
0
        public static float OffsetFromSunCycle(int absTick, int tile)
        {
            float num = GenDate.DayPercent(absTick, Find.WorldGrid.LongLatOf(tile).x);

            return(Mathf.Cos((float)Math.PI * 2f * (num + 0.32f)) * 7f);
        }
        public List <Speciality> getSpecialityList()
        {
            Settlement settlement = TradeSession.trader as Settlement;

            if (settlement == null)
            {
                return(new List <Speciality>());
            }
            List <Speciality> specialityList;

            if (specialityLists.ContainsKey(settlement))
            {
                specialityList = specialityLists[settlement];
            }
            else
            {
                specialityList = new List <Speciality>();
                int                    ticksPerDay            = 60000 / 24 * 14;
                WorldGrid              grid                   = Find.WorldGrid;
                WorldPathFinder        finder                 = Find.WorldPathFinder;
                SpecialityWorldManager specialityWorldManager = Find.World.GetComponent <SpecialityWorldManager>();
                finder.FloodPathsWithCost(new List <int> {
                    settlement.Tile
                }, (int currentPlace, int neighborPlace) => {
                    float moveCost = 2500;
                    Tile tile      = grid.tiles[neighborPlace];
                    if (tile == null && tile.WaterCovered)
                    {
                        return(99999);
                    }
                    Season season = GenDate.Season(Find.TickManager.TicksGame, grid.LongLatOf(neighborPlace));
                    switch (season)
                    {
                    case Season.Spring:
                        moveCost += tile.biome.pathCost_spring;
                        break;

                    case Season.Summer:
                    case Season.PermanentSummer:
                        moveCost += tile.biome.pathCost_summer;
                        break;

                    case Season.Fall:
                        moveCost += tile.biome.pathCost_fall;
                        break;

                    case Season.Winter:
                    case Season.PermanentWinter:
                        moveCost += tile.biome.pathCost_winter;
                        break;
                    }
                    moveCost *= grid.GetRoadMovementMultiplierFast(currentPlace, neighborPlace);
                    return((int)moveCost);
                }, null, (int currentPlace, float cost) => {
                    if (cost <= ticksPerDay)
                    {
                        Speciality speciality = specialityWorldManager.getSpeciality(currentPlace);
                        if (speciality != null)
                        {
                            specialityList.Add(speciality);
                        }
                        return(false);
                    }
                    else
                    {
                        return(true);
                    }
                });
                specialityLists[settlement] = specialityList;
            }
            return(specialityList);
        }
        public DialogList(ListType type)
        {
            forcePause = true;
            doCloseX   = true;
            // closeOnEscapeKey = true;
            closeOnClickedOutside   = true;
            absorbInputAroundWindow = true;

            int gameStartTick = Find.TickManager.gameStartAbsTick;
            var colonists     = Find.CurrentMap.mapPawns.PawnsInFaction(Faction.OfPlayer);

            switch (type)
            {
            case ListType.Birthdays:
                foreach (var colonist in colonists)
                {
                    if (colonist.Dead || colonist.NonHumanlikeOrWildMan())
                    {
                        continue;
                    }

                    long    birthdayTick = colonist.ageTracker.BirthAbsTicks;
                    int     birthDate    = GenDate.DayOfQuadrum(birthdayTick, 0); // zero based
                    Quadrum birthQuadrum = GenDate.Quadrum(birthdayTick, 0);
                    _list.Add(new QuadrumDayPair("DM.Letter.BirthdayParty".Translate(colonist.Name.ToStringShort), birthQuadrum, birthDate + 1));
                }
                break;

            case ListType.Relationships:
                Dictionary <Pawn, DirectPawnRelation> loverRelations = new Dictionary <Pawn, DirectPawnRelation>();
                foreach (var colonist in colonists)
                {
                    if (colonist.Dead || colonist.NonHumanlikeOrWildMan())
                    {
                        continue;
                    }

                    List <DirectPawnRelation> relations = colonist.relations.DirectRelations.FindAll(x => x.def == PawnRelationDefOf.Lover);
                    foreach (DirectPawnRelation relation in relations)
                    {
                        if (loverRelations.ContainsKey(colonist) || loverRelations.ContainsKey(relation.otherPawn))
                        {
                            continue;
                        }
                        loverRelations.Add(colonist, relation);
                        int     startTick    = relation.startTicks + gameStartTick;
                        int     startDay     = GenDate.DayOfQuadrum(startTick, 0);
                        Quadrum startQuadrum = GenDate.Quadrum(startTick, 0);
                        _list.Add(new QuadrumDayPair("DM.Letter.RelationshipAnniversaryParty".Translate(colonist.Name.ToStringShort, relation.otherPawn.Name.ToStringShort), startQuadrum, startDay + 1));
                    }
                }
                break;

            case ListType.Marriages:
                Dictionary <Pawn, DirectPawnRelation> marriageRelations = new Dictionary <Pawn, DirectPawnRelation>();
                foreach (var colonist in colonists)
                {
                    if (colonist.Dead || colonist.NonHumanlikeOrWildMan())
                    {
                        continue;
                    }

                    List <DirectPawnRelation> relations = colonist.relations.DirectRelations.FindAll(x => x.def == PawnRelationDefOf.Spouse);
                    foreach (DirectPawnRelation relation in relations)
                    {
                        if (marriageRelations.ContainsKey(colonist) || marriageRelations.ContainsKey(relation.otherPawn))
                        {
                            continue;
                        }
                        marriageRelations.Add(colonist, relation);
                        int     startTick    = relation.startTicks + gameStartTick;
                        int     startDay     = GenDate.DayOfQuadrum(startTick, 0);
                        Quadrum startQuadrum = GenDate.Quadrum(startTick, 0);
                        _list.Add(new QuadrumDayPair("DM.Letter.MarriageAnniversaryParty".Translate(colonist.Name.ToStringShort, relation.otherPawn.Name.ToStringShort), startQuadrum, startDay + 1));
                    }
                }
                break;

            default:
                break;
            }
        }
 private static void GenerateRandomAge(Pawn pawn, PawnGenerationRequest request)
 {
     if (request.FixedBiologicalAge.HasValue && request.FixedChronologicalAge.HasValue)
     {
         float?fixedBiologicalAge    = request.FixedBiologicalAge;
         bool  hasValue              = fixedBiologicalAge.HasValue;
         float?fixedChronologicalAge = request.FixedChronologicalAge;
         if ((hasValue & fixedChronologicalAge.HasValue) && fixedBiologicalAge.GetValueOrDefault() > fixedChronologicalAge.GetValueOrDefault())
         {
             Log.Warning("Tried to generate age for pawn " + pawn + ", but pawn generation request demands biological age (" + request.FixedBiologicalAge + ") to be greater than chronological age (" + request.FixedChronologicalAge + ").");
         }
     }
     if (request.Newborn)
     {
         pawn.ageTracker.AgeBiologicalTicks = 0L;
     }
     else if (request.FixedBiologicalAge.HasValue)
     {
         pawn.ageTracker.AgeBiologicalTicks = (long)(request.FixedBiologicalAge.Value * 3600000.0);
     }
     else
     {
         float num  = 0f;
         int   num2 = 0;
         while (true)
         {
             num = ((pawn.RaceProps.ageGenerationCurve == null) ? ((!pawn.RaceProps.IsMechanoid) ? (Rand.ByCurve(PawnGenerator.DefaultAgeGenerationCurve, 200) * pawn.RaceProps.lifeExpectancy) : ((float)Rand.Range(0, 2500))) : ((float)Mathf.RoundToInt(Rand.ByCurve(pawn.RaceProps.ageGenerationCurve, 200))));
             num2++;
             if (num2 > 300)
             {
                 Log.Error("Tried 300 times to generate age for " + pawn);
                 break;
             }
             if (!(num > (float)pawn.kindDef.maxGenerationAge) && !(num < (float)pawn.kindDef.minGenerationAge))
             {
                 break;
             }
         }
         pawn.ageTracker.AgeBiologicalTicks = (long)(num * 3600000.0) + Rand.Range(0, 3600000);
     }
     if (request.Newborn)
     {
         pawn.ageTracker.AgeChronologicalTicks = 0L;
     }
     else if (request.FixedChronologicalAge.HasValue)
     {
         pawn.ageTracker.AgeChronologicalTicks = (long)(request.FixedChronologicalAge.Value * 3600000.0);
     }
     else
     {
         int num3;
         if (request.CertainlyBeenInCryptosleep || Rand.Value < pawn.kindDef.backstoryCryptosleepCommonality)
         {
             float value = Rand.Value;
             if (value < 0.699999988079071)
             {
                 num3 = Rand.Range(0, 100);
             }
             else if (value < 0.949999988079071)
             {
                 num3 = Rand.Range(100, 1000);
             }
             else
             {
                 int max = GenDate.Year(GenTicks.TicksAbs, 0f) - 2026 - pawn.ageTracker.AgeBiologicalYears;
                 num3 = Rand.Range(1000, max);
             }
         }
         else
         {
             num3 = 0;
         }
         int  ticksAbs = GenTicks.TicksAbs;
         long num4     = ticksAbs - pawn.ageTracker.AgeBiologicalTicks;
         num4 -= (long)num3 * 3600000L;
         pawn.ageTracker.BirthAbsTicks = num4;
     }
     if (pawn.ageTracker.AgeBiologicalTicks > pawn.ageTracker.AgeChronologicalTicks)
     {
         pawn.ageTracker.AgeChronologicalTicks = pawn.ageTracker.AgeBiologicalTicks;
     }
 }
		private bool GenDateIsInRange(GenDate gen)
		{
			return GenDateIsAfterDate(gen, m_start, IsStartAD) &&
				GenDateIsBeforeDate(gen, m_end, IsEndAD);
		}
		private bool GenDateMightBeAfterDate(GenDate gen, DateTime date, bool fAD)
		{
			if (gen.IsAD && !fAD)		// AD > BC
				return true;
			if (!gen.IsAD && fAD)		// BC < AD
				return gen.Precision == GenDate.PrecisionType.After;
			if (!gen.IsAD && !fAD)		// Both BC
			{
				if (gen.Year > date.Year)
					return gen.Precision == GenDate.PrecisionType.After;
				else if (gen.Year < date.Year)
					return true;
			}
			if (gen.IsAD && fAD)		// Both AD
			{
				if (gen.Year < date.Year)
					return gen.Precision == GenDate.PrecisionType.After;
				else if (gen.Year > date.Year)
					return true;
			}
			if (gen.Month < date.Month)
			{
				return gen.Month == GenDate.UnknownMonth &&
					gen.Precision != GenDate.PrecisionType.Before;
			}
			else if (gen.Month > date.Month)
			{
				return true;
			}
			if (gen.Day == GenDate.UnknownDay)
				return gen.Precision != GenDate.PrecisionType.Before;
			else if (gen.Day == date.Day)
				return gen.Precision != GenDate.PrecisionType.Before;
			else
				return gen.Day > date.Day || gen.Precision == GenDate.PrecisionType.After;
		}
		private bool GenDateIsAfterDate(GenDate gen, DateTime date, bool fAD)
		{
			if (UnspecificMatching)
				return GenDateMightBeAfterDate(gen, date, fAD);

			if (gen.IsAD && !fAD)		// AD > BC
				return gen.Precision != GenDate.PrecisionType.Before;
			if (!gen.IsAD && fAD)		// BC < AD
				return false;
			if (!gen.IsAD && !fAD)		// Both BC
			{
				if (gen.Year > date.Year)
					return false;
				else if (gen.Year < date.Year)
					return gen.Precision != GenDate.PrecisionType.Before;
			}
			if (gen.IsAD && fAD)		// Both AD
			{
				if (gen.Year < date.Year)
					return false;
				else if (gen.Year > date.Year)
					return gen.Precision != GenDate.PrecisionType.Before;
			}
			if (gen.Month < date.Month)
			{
				return gen.Month == GenDate.UnknownMonth &&
					gen.Precision == GenDate.PrecisionType.After;
			}
			else if (gen.Month > date.Month)
			{
				return gen.Precision != GenDate.PrecisionType.Before;
			}
			if (gen.Day == GenDate.UnknownDay)
				return gen.Precision == GenDate.PrecisionType.After;
			return gen.Day >= date.Day && gen.Precision != GenDate.PrecisionType.Before;
		}
		/// <summary>
		/// Set the generic date property.
		/// </summary>
		/// <param name="hvo">The hvo.</param>
		/// <param name="tag">The tag.</param>
		/// <param name="genDate">The generic date.</param>
		public void SetGenDate(int hvo, int tag, GenDate genDate)
		{
			GetInternalInterfaceForObject(hvo).SetProperty(tag, genDate, true);
		}
Exemple #16
0
        public override void DoWindowContents(Rect inRect)
        {
            //grab before anchor/font
            GameFont   fontBefore   = Text.Font;
            TextAnchor anchorBefore = Text.Anchor;

            //top label
            Text.Font   = GameFont.Small;
            Text.Anchor = TextAnchor.MiddleCenter;

            //build outline
            Widgets.DrawMenuSection(eventsBox);


            //loop through each event
            //GoTo Here if change
            int i = 0;

            Text.Anchor = TextAnchor.MiddleCenter;
            foreach (FCEvent evt in events)
            {
                i++;
                Rect name      = new Rect();
                Rect desc      = new Rect();
                Rect location  = new Rect();
                Rect time      = new Rect();
                Rect highlight = new Rect();


                name     = eventNameBase;
                desc     = eventDescBase;
                location = eventLocationBase;
                time     = eventTimeRemaining;

                name.y     = scroll + eventHeight * i;
                desc.y     = scroll + eventHeight * i;
                location.y = scroll + eventHeight * i;
                time.y     = scroll + eventHeight * i;

                highlight = new Rect(name.x, name.y, time.x + time.width, eventHeight);



                if (i % 2 == 0)
                {
                    Widgets.DrawHighlight(highlight);
                }
                Widgets.Label(name, evt.def.label);
                //
                if (Widgets.ButtonText(desc, "Desc"))
                {
                    if (evt.hasCustomDescription == false)
                    {
                        //If desc button clicked
                        string settlementString = "";
                        foreach (SettlementFC loc in evt.settlementTraitLocations)
                        {
                            if (loc != null)
                            {
                                if (settlementString == "")
                                {
                                    settlementString = settlementString + loc.name;
                                }
                                else
                                {
                                    settlementString = settlementString + ", " + loc.name;
                                }
                            }
                        }
                        if (settlementString != "")
                        {
                            Find.WindowStack.Add(new descWindowFC(evt.def.description + "\n This event is affecting the following settlements: " + settlementString));
                        }
                        else
                        {
                            Find.WindowStack.Add(new descWindowFC(evt.def.description));
                        }
                    }
                    else
                    {
                        //has custom description
                        Find.WindowStack.Add(new descWindowFC(evt.customDescription));
                    }
                }
                //
                if (Widgets.ButtonText(location, "Location".Translate().CapitalizeFirst()))
                {
                    if (evt.hasDestination == true)
                    {
                        Find.WindowStack.Add(new settlementWindowFC(faction.returnSettlementByLocation(evt.location)));
                    }
                    else
                    {
                        if (evt.settlementTraitLocations.Count() > 0)
                        {
                            //if event affecting colonies
                            List <FloatMenuOption> list = new List <FloatMenuOption>();
                            foreach (SettlementFC settlement in evt.settlementTraitLocations)
                            {
                                if (settlement != null)
                                {
                                    list.Add(new FloatMenuOption(settlement.name, delegate { Find.WindowStack.Add(new settlementWindowFC(settlement)); }));
                                }
                            }
                            if (list.Count == 0)
                            {
                                list.Add(new FloatMenuOption("Null", null));
                            }
                            Find.WindowStack.Add(new FloatMenu(list));
                        }
                        else
                        {
                            if (evt.def == FCEventDefOf.taxColony && evt.source != -1)
                            {
                                Find.WindowStack.Add(new settlementWindowFC(faction.returnSettlementByLocation(evt.source)));
                            }
                        }
                    }
                }
                //
                Widgets.Label(time, GenDate.ToStringTicksToDays(evt.timeTillTrigger - Find.TickManager.TicksGame));
            }



            //Top label
            Widgets.ButtonTextSubtle(eventNameBase, "Name".Translate());
            Widgets.ButtonTextSubtle(eventDescBase, "Description".Translate());
            Widgets.ButtonTextSubtle(eventLocationBase, "Source".Translate());
            Widgets.ButtonTextSubtle(eventTimeRemaining, "TimeRemaining".Translate());

            //Menu Outline
            Widgets.DrawBox(eventsBox);


            //reset anchor/font
            Text.Font   = fontBefore;
            Text.Anchor = anchorBefore;


            if (Event.current.type == EventType.ScrollWheel)
            {
                scrollWindow(Event.current.delta.y);
            }
        }
        public virtual void UnlockCard(bool debugTools = false)
        {
            if (!unlocked)
            {
                unlocked = true;

                var vector = Find.WorldGrid.LongLatOf(Find.CurrentMap.Tile);
                dateUnlocked = (Prefs.DevMode || debugTools) ? "UnlockedDevMode".Translate().ToString() : GenDate.DateReadoutStringAt(Find.TickManager.TicksAbs, vector);

                Current.Game.GetComponent <AchievementPointManager>().AddPoints(def.points);
                DefDatabase <SoundDef> .GetNamed("LetterArrive_Good").PlayOneShotOnCamera();

                DebugWriter.Log($"Unlocking: {GetUniqueLoadID()} Card: {def.label}");
                if (debugTools)
                {
                    DebugWriter.Log($"[Unlocked with DebugTools]");
                }
                Current.Game.GetComponent <AchievementPointManager>().DisplayCardWindow(this);
            }
        }
		private static string GetDefaultValueForPropertyType(CellarPropertyType propertyType)
		{
			switch (propertyType)
			{
				case CellarPropertyType.Boolean:
					return "False";
				case CellarPropertyType.GenDate:
					var genDate = new GenDate();
					return string.Format("{0}{1:0000}{2:00}{3:00}{4}",
						genDate.IsAD ? "" : "-",
						genDate.Year,
						genDate.Month,
						genDate.Day,
						(int)genDate.Precision);
				case CellarPropertyType.Guid:
					return Guid.Empty.ToString();
				case CellarPropertyType.Float:
					throw new NotSupportedException("The 'Float' data type is not supported in the FW data model yet (as of 23 March 2013).");
				case CellarPropertyType.Integer:
					return "0";
				case CellarPropertyType.Time:
					var datetime = new DateTime();
					datetime = datetime.ToUniversalTime(); // Store it as UTC.
					return String.Format("{0}-{1}-{2} {3}:{4}:{5}.{6}",
						datetime.Year,
						datetime.Month,
						datetime.Day,
						datetime.Hour,
						datetime.Minute,
						datetime.Second,
						datetime.Millisecond);
				case CellarPropertyType.Numeric:
					throw new NotSupportedException("The 'Numeric' data type is not supported in the FW data model yet (as of 23 March 2013).");
				default:
					throw new InvalidOperationException("The given 'propertyType' is not a basic data type.");
			}
		}
Exemple #19
0
		public static string GetGenDateAttribute(GenDate dataProperty)
		{
			var genDateStr = "0";
			if (!dataProperty.IsEmpty)
			{
				genDateStr = String.Format("{0}{1:0000}{2:00}{3:00}{4}", dataProperty.IsAD ? "" : "-", dataProperty.Year,
					dataProperty.Month, dataProperty.Day, (int)dataProperty.Precision);
			}
			return genDateStr;
		}
Exemple #20
0
        public static void Postfix(Plant __instance, ref Graphic __result)
        {
            string id = __instance.def.defName;

            if (!__instance.def.HasModExtension <ThingWeatherReaction>())
            {
                return;
            }

            ThingWeatherReaction mod = __instance.def.GetModExtension <ThingWeatherReaction>();
            Map map = __instance.Map;

            string path = "";

            //get flowering or drought graphic if it's over 70
            if (__instance.AmbientTemperature > 21)
            {
                Watcher  watcher = map.GetComponent <Watcher>();
                cellData cell;
                if (watcher.cellWeatherAffects[__instance.Position] != null)
                {
                    cell = watcher.cellWeatherAffects[__instance.Position];
                    Vector2 location = Find.WorldGrid.LongLatOf(__instance.MapHeld.Tile);
                    Season  season   = GenDate.Season((long)Find.TickManager.TicksAbs, location);

                    if (!String.IsNullOrEmpty(mod.floweringGraphicPath) && ((cell.howWetPlants > 60 && map.weatherManager.RainRate <= .001f) || season == Season.Spring))
                    {
                        id  += "flowering";
                        path = mod.floweringGraphicPath;
                    }

                    if (!String.IsNullOrEmpty(mod.droughtGraphicPath) && cell.howWetPlants < 20)
                    {
                        id  += "drought";
                        path = mod.droughtGraphicPath;
                    }
                    else
                    if (__instance.def.plant.leaflessGraphic != null && cell.howWetPlants < 20)
                    {
                        id  += "drought";
                        path = __instance.def.plant.leaflessGraphic.path;
                    }
                }
            }
            if (path != "")
            {
                if (!map.GetComponent <Watcher>().graphicHolder.ContainsKey(id))
                {
                    //only load the image once.
                    map.GetComponent <Watcher>().graphicHolder.Add(id, GraphicDatabase.Get(__instance.def.graphicData.graphicClass, path, __instance.def.graphic.Shader, __instance.def.graphicData.drawSize, __instance.def.graphicData.color, __instance.def.graphicData.colorTwo));
                }
                if (map.GetComponent <Watcher>().graphicHolder.ContainsKey(id))
                {
                    __result = map.GetComponent <Watcher>().graphicHolder[id];
                }
                return;
            }

            if (Settings.showCold)
            {
                //get snow graphic
                if (map.snowGrid.GetDepth(__instance.Position) >= 0.5f)
                {
                    if (!String.IsNullOrEmpty(mod.snowGraphicPath))
                    {
                        id  += "snow";
                        path = mod.snowGraphicPath;
                    }
                }
                else if (map.GetComponent <FrostGrid>().GetDepth(__instance.Position) >= 0.6f)
                {
                    if (!String.IsNullOrEmpty(mod.frostGraphicPath))
                    {
                        id  += "frost";
                        path = mod.frostGraphicPath;
                    }
                }

                if (String.IsNullOrEmpty(path))
                {
                    return;
                }
                //if it's leafless
                if (__instance.def.plant.leaflessGraphic == __result)
                {
                    id   += "leafless";
                    path  = path.Replace("Frosted", "Frosted/Leafless");
                    path  = path.Replace("Snow", "Snow/Leafless");
                    path += "_Leafless";
                }
                else if (__instance.def.blockWind)
                {
                    //make it so snow doesn't fall under the tree until it's leafless.
                    //	map.snowGrid.AddDepth(__instance.Position, -.05f);
                }
            }

            if (String.IsNullOrEmpty(path)) //Need to check if the path is null/empty in case showCold is false and temp is below flower/drought temp
            {
                return;
            }

            if (!map.GetComponent <Watcher>().graphicHolder.ContainsKey(id))
            {
                //only load the image once.
                map.GetComponent <Watcher>().graphicHolder.Add(id, GraphicDatabase.Get(__instance.def.graphicData.graphicClass, path, __instance.def.graphic.Shader, __instance.def.graphicData.drawSize, __instance.def.graphicData.color, __instance.def.graphicData.colorTwo));
            }
            if (map.GetComponent <Watcher>().graphicHolder.ContainsKey(id))
            {
                __result = map.GetComponent <Watcher>().graphicHolder[id];
            }
            return;
        }
        protected override IEnumerable <Toil> MakeNewToils()
        {
            Building_FishingSpot fishingSpot = this.job.GetTarget(FishingSpotIndex).Thing as Building_FishingSpot;

            int fishingDuration = (int)(baseFishingDuration * Rand.Range(0.2f, 1.8f) * fishingSpot.MapFishTracker.DifficultyMultiplier / (ModController.Settings.FishingEfficiency));

            Thing thingCaught = null;

            yield return(Toils_Goto.GotoThing(FishingSpotIndex, fishingSpot.InteractionCell)
                         .FailOnDespawnedNullOrForbidden(FishingSpotIndex));

            Toil fishToil = new Toil()
            {
                initAction = () =>
                {
                    if (Find.TickManager.TicksGame > fishingSpot.lastFishingStartTick + 60000 * fishingSpot.FishingFrequency)
                    {
                        fishingSpot.lastFishingStartTick = Find.TickManager.TicksGame;
                    }
                },
                tickAction = () => {
                    this.pawn.skills.Learn(job.def.joySkill, job.def.joyXpPerTick);

                    if (pawn.CurJob.GetTarget(FishingSpotIndex).IsValid)
                    {
                        pawn.rotationTracker.FaceCell(pawn.CurJob.GetTarget(FishingSpotIndex).Cell);
                    }
                },
                handlingFacing      = true,
                defaultDuration     = fishingDuration,
                defaultCompleteMode = ToilCompleteMode.Delay
            };

            yield return(fishToil.FailOnDespawnedNullOrForbidden(FishingSpotIndex));

            Toil catchFishToil = new Toil()
            {
                initAction = () =>
                {
                    string eventText;
                    if (Rand.Value < pawn.GetStatValue(ResourceBank.StatDefOf.FishingChance))
                    {
                        if (fishingSpot.FishStock > 0 && fishingSpot.FishByWeight.Count > 0)
                        {
                            FishDef fishDefToCatch = fishingSpot.FishByWeight.RandomElementByWeight(item => item.Item1).Item2;


                            if (fishDefToCatch.fishProperties.CanBite && Rand.Value < pawn.GetStatValue(ResourceBank.StatDefOf.FishBiteChance))
                            {
                                float damage = Rand.Range(fishDefToCatch.fishProperties.BiteDamageRange.min, fishDefToCatch.fishProperties.BiteDamageRange.max);

                                eventText = string.Format(ResourceBank.Strings.FishingTradegyText.Translate(), this.pawn.Name.ToStringShort.CapitalizeFirst(), fishDefToCatch.label);
                                Find.LetterStack.ReceiveLetter(ResourceBank.Strings.FishingTradegyTitle.Translate(), eventText, LetterDefOf.NegativeEvent, this.pawn);
                                this.pawn.TakeDamage(new DamageInfo(fishDefToCatch.fishProperties.BiteDamageDef, damage, 0f, -1f, this.pawn, null, null, DamageInfo.SourceCategory.ThingOrUnknown, this.pawn));
                                return;
                            }

                            fishingSpot.FishCaught();

                            bool roeFish = false;
                            if (fishDefToCatch.fishProperties.HasRoe && fishDefToCatch.fishProperties.RoeDef != null && fishDefToCatch.fishProperties.SpawningYearRange != null)
                            {
                                int day = GenDate.DayOfYear(Find.TickManager.TicksAbs, Find.WorldGrid.LongLatOf(this.Map.Tile).x);
                                if (fishDefToCatch.fishProperties.SpawningYearRange.min <= day && day <= fishDefToCatch.fishProperties.SpawningYearRange.max)
                                {
                                    if (Rand.Value < ModController.Settings.roeChance)
                                    {
                                        roeFish = true;
                                    }
                                }
                            }

                            if (roeFish)
                            {
                                thingCaught = ThingMaker.MakeThing(fishDefToCatch.fishProperties.RoeDef, null);
                            }
                            else
                            {
                                thingCaught = ThingMaker.MakeThing(fishDefToCatch, null);
                            }

                            thingCaught.stackCount = 1;
                            eventText = ResourceBank.Strings.FishingSuccess.Translate(this.pawn.Name.ToStringShort.CapitalizeFirst(), fishDefToCatch.label);

                            NotifyFishingSuccess(eventText);
                        }
                        else
                        if (Rand.Value < ModController.Settings.junkChance)
                        {
                            //catch non-fish
                            float treasureChance = ModController.Settings.treasureChanceStandart;
                            if (fishingSpot.DeepTerrain)
                            {
                                treasureChance *= treasureDeepAdditionalChance;
                            }

                            ThingSetMakerParams parms = default(ThingSetMakerParams);
                            parms.countRange = new IntRange(1, 1);

                            if (Rand.Value <= treasureChance)
                            {
                                parms.maxTotalMass          = ModController.Settings.MaxTreasureMass;
                                parms.totalMarketValueRange = new FloatRange(100.0f, ModController.Settings.treasureMaxValue);
                                parms.qualityGenerator      = QualityGenerator.Reward;

                                List <Thing> list = ThingSetMakerDefOf.Reward_ItemsStandard.root.Generate(parms);
                                thingCaught = list.RandomElement();

                                eventText = ResourceBank.Strings.FishingCaughtTreasureText.Translate(this.pawn.Name.ToStringShort.CapitalizeFirst(), thingCaught.def.label);
                                NotifyCaughtTreasure(eventText);
                            }
                            else
                            {
                                parms.maxTotalMass     = ModController.Settings.MaxJunkMass;
                                parms.qualityGenerator = QualityGenerator.BaseGen;

                                List <Thing> list = ResourceBank.ThingSetMakerDefOf.Fishing_ItemJunk.root.Generate(parms);
                                thingCaught = list.RandomElement();

                                eventText = ResourceBank.Strings.FishingCaughtJunkText.Translate(this.pawn.Name.ToStringShort.CapitalizeFirst(), thingCaught.def.label);
                                NotifyCaughtJunk(eventText);
                            }
                        }
                    }
                    else
                    {
                        eventText = ResourceBank.Strings.FishingCaughtNothingText.Translate(this.pawn.Name.ToStringShort.CapitalizeFirst());
                        MoteMaker.ThrowMetaIcon(this.pawn.Position, this.Map, ThingDefOf.Mote_IncapIcon);
                        NotifyCaughtNothing(eventText);
                        this.pawn.jobs.EndCurrentJob(JobCondition.Incompletable);
                        return;
                    }
                }
            };

            yield return(catchFishToil);

            //yield return FinishAndStartHaul(fishingCatch);

            Toil toilFinishAndStartHaul = new Toil();

            toilFinishAndStartHaul.initAction = delegate
            {
                Pawn actor  = toilFinishAndStartHaul.actor;
                Job  curJob = actor.jobs.curJob;
                Bill bill   = curJob.bill;

                Log.Message(bill.recipe.defName);
                Log.Message(thingCaught.def.defName);

                if (curJob.bill.GetStoreMode() == BillStoreModeDefOf.DropOnFloor)
                {
                    if (!GenPlace.TryPlaceThing(thingCaught, actor.Position, actor.Map, ThingPlaceMode.Near))
                    {
                        Log.Error(actor + " could not drop recipe product " + thingCaught + " near " + actor.Position);
                    }

                    actor.jobs.EndCurrentJob(JobCondition.Succeeded);
                }
                else
                {
                    IntVec3 foundCell = IntVec3.Invalid;
                    if (curJob.bill.GetStoreMode() == BillStoreModeDefOf.BestStockpile)
                    {
                        StoreUtility.TryFindBestBetterStoreCellFor(thingCaught, actor, actor.Map, StoragePriority.Unstored, actor.Faction, out foundCell);
                    }
                    else if (curJob.bill.GetStoreMode() == BillStoreModeDefOf.SpecificStockpile)
                    {
                        if (curJob.bill.GetStoreZone().Accepts(thingCaught))
                        {
                            StoreUtility.TryFindBestBetterStoreCellForIn(thingCaught, actor, actor.Map, StoragePriority.Unstored, actor.Faction, curJob.bill.GetStoreZone().slotGroup, out foundCell);
                        }
                        else
                        {
                            if (!GenPlace.TryPlaceThing(thingCaught, actor.Position, actor.Map, ThingPlaceMode.Near))
                            {
                                Log.Error(actor + " could not drop recipe product " + thingCaught + " near " + actor.Position);
                            }
                            actor.jobs.EndCurrentJob(JobCondition.Succeeded);
                        }
                    }
                    else
                    {
                        Log.ErrorOnce("Unknown store mode", 9158246);
                    }

                    if (foundCell.IsValid)
                    {
                        actor.carryTracker.TryStartCarry(thingCaught);
                        curJob.SetTarget(HaulableInd, thingCaught);
                        curJob.SetTarget(StoreCellInd, foundCell);
                        curJob.count = 99999;
                    }
                    else
                    {
                        if (!GenPlace.TryPlaceThing(thingCaught, actor.Position, actor.Map, ThingPlaceMode.Near))
                        {
                            Log.Error("Bill doer could not drop product " + thingCaught + " near " + actor.Position);
                        }
                        actor.jobs.EndCurrentJob(JobCondition.Succeeded);
                    }
                }
            };
            yield return(toilFinishAndStartHaul);

            yield return(Toils_Reserve.Reserve(StoreCellInd));

            Toil carryToCell = Toils_Haul.CarryHauledThingToCell(StoreCellInd);

            yield return(carryToCell);

            yield return(Toils_Haul.PlaceHauledThingInCell(StoreCellInd, carryToCell, storageMode: true, tryStoreInSameStorageIfSpotCantHoldWholeStack: true));

            Toil recount = new Toil();

            recount.initAction = delegate
            {
                Bill_Production bill_Production = recount.actor.jobs.curJob.bill as Bill_Production;
                if (bill_Production != null && bill_Production.repeatMode == BillRepeatModeDefOf.TargetCount)
                {
                    Map.resourceCounter.UpdateResourceCounts();
                }
            };
            yield return(recount);
        }
Exemple #22
0
        public static bool WouldBeRestingAt(int tile, long ticksAbs)
        {
            float num = GenDate.HourFloat(ticksAbs, Find.WorldGrid.LongLatOf(tile).x);

            return(num < 6f || num > 22f);
        }
Exemple #23
0
            public static void Fix(Pawn_AgeTracker __instance, ref int __result)
            {
                long birthAbsTicksInt = (long)BIRTH_ABS_TICKS_INT_FIELD.GetValue(__instance);

                __result = GenDate.DayOfQuadrum(birthAbsTicksInt, 0f);
            }
        public override void Interacted(Pawn initiator, Pawn recipient, List <RulePackDef> extraSentencePacks)
        {
            PsychologyPawn realRecipient = recipient as PsychologyPawn;
            PsychologyPawn realInitiator = initiator as PsychologyPawn;
            //Choose a time that works with their schedule, based on their personality
            Dictionary <int, float> possibleHours = new Dictionary <int, float>();

            for (int i = 0; i < GenDate.HoursPerDay; i++)
            {
                possibleHours.Add(i, 0f);
            }
            foreach (PersonalityNodeDef d in DefDatabase <PersonalityNodeDef> .AllDefsListForReading)
            {
                if (d.preferredDateHours != null)
                {
                    foreach (int h in d.preferredDateHours)
                    {
                        possibleHours[h] += (Mathf.Pow(Mathf.Abs(0.5f - realInitiator.psyche.GetPersonalityRating(d)), 2) / (1.3f - realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Aggressive)) + Mathf.Pow(Mathf.Abs(0.5f - realRecipient.psyche.GetPersonalityRating(d)), 2) / (1.3f - realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Aggressive)) / 2f);
                    }
                }
            }
            int hour = possibleHours.Keys.RandomElementByWeight(h => possibleHours[h] * RendezvousUtility.TimeAssignmentFactor(initiator, h) * RendezvousUtility.TimeAssignmentFactor(recipient, h));
            //More Spontaneous couples will plan their dates sooner; possibly even immediately!
            int day = Find.TickManager.TicksGame + Mathf.RoundToInt(GenDate.TicksPerDay * 5 * (((1f - realInitiator.psyche.GetPersonalityRating(PersonalityNodeDefOf.Spontaneous)) + (1f - realRecipient.psyche.GetPersonalityRating(PersonalityNodeDefOf.Spontaneous))) / 2f));
            Hediff_PlannedDate plannedDate = HediffMaker.MakeHediff(HediffDefOfPsychology.PlannedDate, initiator) as Hediff_PlannedDate;

            plannedDate.partner = recipient;
            plannedDate.day     = day;
            plannedDate.hour    = hour;
            initiator.health.AddHediff(plannedDate);
            realInitiator.psyche.lastDateTick = day;
            realRecipient.psyche.lastDateTick = day;
            if (Prefs.DevMode && Prefs.LogVerbose)
            {
                Log.Message(initiator.LabelShort + " planned date with " + recipient.LabelShort + " for hour " + hour + " on date " + GenDate.DateFullStringAt(GenDate.TickGameToAbs(day), Find.WorldGrid.LongLatOf(initiator.Map.Tile)));
            }
        }
Exemple #25
0
        public IEnumerable <Event> GetByDate(GenDate date)
        {
            var query = GetBaseQuery().Where(GetWhereDate());

            return(GetListSql(query, new { date.From, date.To }));
        }
Exemple #26
0
        public override void MapComponentTick()
        {
            if (this.map.Biome != Util_CaveBiome.CaveBiomeDef)
            {
                return;
            }

            if (Find.TickManager.TicksGame >= nextLightCheckTick)
            {
                nextLightCheckTick = Find.TickManager.TicksGame + lightCheckPeriodInTicks;
                float gamehour           = GenDate.HoursPerDay * GenDate.DayPercent(Find.TickManager.TicksAbs, Find.WorldGrid.LongLatOf(map.Tile).x); // TODO: could refine to accommodate axial tilt, such that high latitudes will have "midnight sun" growing areas... nifty.
                float caveWellBrightness = 0.0f;

                if (this.map.gameConditionManager.ConditionIsActive(GameConditionDefOf.Eclipse))
                {
                    // Shut down light when there is an eclipse.
                    caveWellBrightness = 0.0f;
                }
                else
                {
                    if (gamehour < sunriseBeginHour)
                    {
                        caveWellBrightness = brightnessCaveWellMin;
                    }
                    else if (gamehour < sunriseEndHour)
                    {
                        float sunriseProgress = Math.Max(0f, gamehour - sunriseBeginHour) / (sunriseEndHour - sunriseBeginHour);
                        caveWellBrightness = sunriseProgress * brightnessCaveWellMax;
                    }
                    else if (gamehour < sunsetBeginHour)
                    {
                        caveWellBrightness = brightnessCaveWellMax;
                    }
                    else if (gamehour < sunsetEndHour)
                    {
                        float sunsetProgress = Math.Max(0f, gamehour - sunsetBeginHour) / (sunsetEndHour - sunsetBeginHour);
                        caveWellBrightness = 1 - sunsetProgress * brightnessCaveWellMax;
                    }
                    else
                    {
                        caveWellBrightness = brightnessCaveWellMin;
                    }
                }

                currentGlowColor.r = (int)(caveWellBrightness * caveWellBrightness * baseGlowColor.r);
                currentGlowColor.g = (int)(caveWellBrightness * caveWellBrightness * baseGlowColor.g);
                currentGlowColor.b = (int)(caveWellBrightness * caveWellBrightness * baseGlowColor.b);

                List <Thing> caveWellsList = map.listerThings.ThingsOfDef(Util_CaveBiome.CaveWellDef);
                foreach (Thing caveWell in caveWellsList)
                {
                    SetCaveWellBrightness(caveWell, caveWellBrightness);
                }

                if ((MapComponent_CaveWellLight.plantsMessageHasBeenSent == false) &&
                    (gamehour >= sunriseBeginHour + 1))
                {
                    Find.LetterStack.ReceiveLetter("CaveBiome.LetterLabelCavePlants".Translate(), "CaveBiome.CavePlants".Translate(),
                                                   LetterDefOf.Good);
                    MapComponent_CaveWellLight.plantsMessageHasBeenSent = true;
                }
                if ((MapComponent_CaveWellLight.growingMessageHasBeenSent == false) &&
                    (gamehour >= sunriseBeginHour + 2))
                {
                    if (MapGenerator.PlayerStartSpot.IsValid &&
                        (MapGenerator.PlayerStartSpot != IntVec3.Zero))    // Checking PlayerStartSpot validity will still raise an error message if it is invalid.
                    {
                        Find.LetterStack.ReceiveLetter("CaveBiome.LetterLabelGrowingInCave".Translate(), "CaveBiome.GrowingInCave".Translate(),
                                                       LetterDefOf.Good, new RimWorld.Planet.GlobalTargetInfo(MapGenerator.PlayerStartSpot, this.map));
                    }
                    else
                    {
                        Find.LetterStack.ReceiveLetter("CaveBiome.LetterLabelGrowingInCave".Translate(), "CaveBiome.GrowingInCave".Translate(),
                                                       LetterDefOf.Good);
                    }
                    MapComponent_CaveWellLight.growingMessageHasBeenSent = true;
                }
            }
        }
        public override void DoWindowContents(Rect inRect)
        {
            //Detect changes
            if (refreshAndroidPortrait)
            {
                newSleeve.Drawer.renderer.graphics.ResolveAllGraphics();
                PortraitsCache.SetDirty(newSleeve);
                PortraitsCache.PortraitsCacheUpdate();
                refreshAndroidPortrait = false;
            }

            Rect pawnRect = new Rect(inRect);

            pawnRect.width  = PawnPortraitSize.x + 16f;
            pawnRect.height = PawnPortraitSize.y + 16f;
            pawnRect        = inRect.RightHalf();
            pawnRect        = inRect.RightHalf();
            pawnRect.x     += 16f;
            pawnRect.y     += 16f;

            //Draw Pawn stuff.
            if (newSleeve != null)
            {
                //Pawn
                Rect pawnRenderRect = new Rect(pawnRect.xMin + (pawnRect.width - PawnPortraitSize.x) / 2f - 10f, pawnRect.yMin + 20f, PawnPortraitSize.x, PawnPortraitSize.y);
                //GUI.DrawTexture(pawnRenderRect, PortraitsCache.Get(newSleeve, PawnPortraitSize, default(Vector3), 1f));

                Text.Font = GameFont.Medium;

                Text.Anchor = TextAnchor.MiddleCenter;
                Widgets.Label(new Rect(0f, 0f, inRect.width, 32f), "AlteredCarbon.SleeveCustomization".Translate());

                Text.Font   = GameFont.Small;
                Text.Anchor = TextAnchor.MiddleCenter;

                //Saakra's Code

                //Gender
                Text.Anchor = TextAnchor.MiddleLeft;
                Widgets.Label(lblGender, "Gender".Translate() + ":");
                if (Widgets.ButtonText(btnGenderMale, "Male".Translate().CapitalizeFirst()))
                {
                    newSleeve = GetNewPawn(Gender.Male);
                }
                if (Widgets.ButtonText(btnGenderFemale, "Female".Translate().CapitalizeFirst()))
                {
                    newSleeve = GetNewPawn(Gender.Female);
                }

                //Skin Colour
                Text.Anchor = TextAnchor.MiddleLeft;
                Widgets.Label(lblSkinColour, "SkinColour".Translate().CapitalizeFirst() + ":");
                Widgets.DrawMenuSection(btnSkinColourOutline);
                Widgets.DrawShadowAround(btnSkinColourOutline);
                if (Widgets.ButtonInvisible(btnSkinColour1))
                {
                    newSleeve.story.melanin = 0.1f;
                    UpdateSleeveGraphic();
                }
                Widgets.DrawBoxSolid(btnSkinColour1, rgbConvert(242, 237, 224));

                if (Widgets.ButtonInvisible(btnSkinColour2))
                {
                    newSleeve.story.melanin = 0.3f;
                    UpdateSleeveGraphic();
                }
                Widgets.DrawBoxSolid(btnSkinColour2, rgbConvert(255, 239, 213));

                if (Widgets.ButtonInvisible(btnSkinColour3))
                {
                    newSleeve.story.melanin = 0.5f;
                    UpdateSleeveGraphic();
                }
                Widgets.DrawBoxSolid(btnSkinColour3, rgbConvert(255, 239, 189));

                if (Widgets.ButtonInvisible(btnSkinColour4))
                {
                    newSleeve.story.melanin = 0.7f;
                    UpdateSleeveGraphic();
                }
                Widgets.DrawBoxSolid(btnSkinColour4, rgbConvert(228, 158, 90));

                if (Widgets.ButtonInvisible(btnSkinColour5))
                {
                    newSleeve.story.melanin = 0.9f;
                    UpdateSleeveGraphic();
                }
                Widgets.DrawBoxSolid(btnSkinColour5, rgbConvert(130, 91, 48));

                //Head Shape
                Widgets.Label(lblHeadShape, "HeadShape".Translate().CapitalizeFirst() + ":");
                Widgets.DrawHighlight(btnHeadShapeOutline);
                if (ButtonTextSubtleCentered(btnHeadShapeArrowLeft, "<"))
                {
                    if (newSleeve.gender == Gender.Male)
                    {
                        if (maleHeadTypeIndex == 0)
                        {
                            maleHeadTypeIndex = GraphicDatabaseHeadRecords.maleHeads.Count - 1;
                        }
                        else
                        {
                            maleHeadTypeIndex--;
                        }

                        typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(newSleeve.story,
                                                                                                                                       GraphicDatabaseHeadRecords.maleHeads.ElementAt(maleHeadTypeIndex).graphicPath);
                    }
                    else if (newSleeve.gender == Gender.Female)
                    {
                        if (femaleHeadTypeIndex == 0)
                        {
                            femaleHeadTypeIndex = GraphicDatabaseHeadRecords.femaleHeads.Count - 1;
                        }
                        else
                        {
                            femaleHeadTypeIndex--;
                        }

                        typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(newSleeve.story,
                                                                                                                                       GraphicDatabaseHeadRecords.femaleHeads.ElementAt(femaleHeadTypeIndex).graphicPath);
                    }

                    UpdateSleeveGraphic();
                }
                if (ButtonTextSubtleCentered(btnHeadShapeSelection, "HeadTypeReplace".Translate()))
                {
                    if (newSleeve.gender == Gender.Male)
                    {
                        FloatMenuUtility.MakeMenu <GraphicDatabaseHeadRecords.HeadGraphicRecord>(GraphicDatabaseHeadRecords.maleHeads, head => ExtractHeadLabels(head.graphicPath),
                                                                                                 (GraphicDatabaseHeadRecords.HeadGraphicRecord head) => delegate
                        {
                            typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(newSleeve.story,
                                                                                                                                           head.graphicPath);
                            UpdateSleeveGraphic();
                        });
                    }
                    else if (newSleeve.gender == Gender.Female)
                    {
                        FloatMenuUtility.MakeMenu <GraphicDatabaseHeadRecords.HeadGraphicRecord>(GraphicDatabaseHeadRecords.femaleHeads, head => ExtractHeadLabels(head.graphicPath),
                                                                                                 (GraphicDatabaseHeadRecords.HeadGraphicRecord head) => delegate
                        {
                            typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(newSleeve.story,
                                                                                                                                           head.graphicPath);
                            UpdateSleeveGraphic();
                        });
                    }
                }
                if (ButtonTextSubtleCentered(btnHeadShapeArrowRight, ">"))
                {
                    if (newSleeve.gender == Gender.Male)
                    {
                        if (maleHeadTypeIndex == GraphicDatabaseHeadRecords.maleHeads.Count - 1)
                        {
                            maleHeadTypeIndex = 0;
                        }
                        else
                        {
                            maleHeadTypeIndex++;
                        }
                        typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(newSleeve.story,
                                                                                                                                       GraphicDatabaseHeadRecords.maleHeads.ElementAt(maleHeadTypeIndex).graphicPath);
                    }
                    else if (newSleeve.gender == Gender.Female)
                    {
                        if (femaleHeadTypeIndex == GraphicDatabaseHeadRecords.femaleHeads.Count - 1)
                        {
                            femaleHeadTypeIndex = 0;
                        }
                        else
                        {
                            femaleHeadTypeIndex++;
                        }
                        typeof(Pawn_StoryTracker).GetField("headGraphicPath", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(newSleeve.story,
                                                                                                                                       GraphicDatabaseHeadRecords.femaleHeads.ElementAt(femaleHeadTypeIndex).graphicPath);
                    }
                    UpdateSleeveGraphic();
                }


                //Body Shape
                Widgets.Label(lblBodyShape, "BodyShape".Translate().CapitalizeFirst() + ":");
                Widgets.DrawHighlight(btnBodyShapeOutline);
                if (ButtonTextSubtleCentered(btnBodyShapeArrowLeft, "<"))
                {
                    if (newSleeve.gender == Gender.Male)
                    {
                        if (maleBodyTypeIndex == 0)
                        {
                            maleBodyTypeIndex = DefDatabase <BodyTypeDef> .AllDefs.Where(x => x != BodyTypeDefOf.Female).Count() - 1;
                        }
                        else
                        {
                            maleBodyTypeIndex--;
                        }
                        newSleeve.story.bodyType = DefDatabase <BodyTypeDef> .AllDefs.Where(x => x != BodyTypeDefOf.Female).ElementAt(maleBodyTypeIndex);
                    }
                    else if (newSleeve.gender == Gender.Female)
                    {
                        if (femaleBodyTypeIndex == 0)
                        {
                            femaleBodyTypeIndex = DefDatabase <BodyTypeDef> .AllDefs.Where(x => x != BodyTypeDefOf.Male).Count() - 1;
                        }
                        else
                        {
                            femaleBodyTypeIndex--;
                        }
                        newSleeve.story.bodyType = DefDatabase <BodyTypeDef> .AllDefs.Where(x => x != BodyTypeDefOf.Male).ElementAt(femaleBodyTypeIndex);
                    }

                    UpdateSleeveGraphic();
                }
                if (ButtonTextSubtleCentered(btnBodyShapeSelection, "BodyTypeReplace".Translate()))
                {
                    if (newSleeve.gender == Gender.Male)
                    {
                        IEnumerable <BodyTypeDef> bodyTypes = from bodyType in DefDatabase <BodyTypeDef>
                                                              .AllDefs.Where(x => x != BodyTypeDefOf.Female) select bodyType;

                        FloatMenuUtility.MakeMenu <BodyTypeDef>(bodyTypes, bodyType => bodyType.defName, (BodyTypeDef bodyType) => delegate
                        {
                            newSleeve.story.bodyType = bodyType;
                            UpdateSleeveGraphic();
                        });
                    }
                    else if (newSleeve.gender == Gender.Female)
                    {
                        IEnumerable <BodyTypeDef> bodyTypes = from bodyType in DefDatabase <BodyTypeDef>
                                                              .AllDefs.Where(x => x != BodyTypeDefOf.Male)
                                                              select bodyType;

                        FloatMenuUtility.MakeMenu <BodyTypeDef>(bodyTypes, bodyType => bodyType.defName, (BodyTypeDef bodyType) => delegate
                        {
                            newSleeve.story.bodyType = bodyType;
                            UpdateSleeveGraphic();
                        });
                    }
                }
                if (ButtonTextSubtleCentered(btnBodyShapeArrowRight, ">"))
                {
                    if (newSleeve.gender == Gender.Male)
                    {
                        if (maleBodyTypeIndex == DefDatabase <BodyTypeDef> .AllDefs.Where(x => x != BodyTypeDefOf.Female).Count() - 1)
                        {
                            maleBodyTypeIndex = 0;
                        }
                        else
                        {
                            maleBodyTypeIndex++;
                        }
                        newSleeve.story.bodyType = DefDatabase <BodyTypeDef> .AllDefs.Where(x => x != BodyTypeDefOf.Female).ElementAt(maleBodyTypeIndex);
                    }
                    else if (newSleeve.gender == Gender.Female)
                    {
                        if (femaleBodyTypeIndex == DefDatabase <BodyTypeDef> .AllDefs.Where(x => x != BodyTypeDefOf.Male).Count() - 1)
                        {
                            femaleBodyTypeIndex = 0;
                        }
                        else
                        {
                            femaleBodyTypeIndex++;
                        }
                        newSleeve.story.bodyType = DefDatabase <BodyTypeDef> .AllDefs.Where(x => x != BodyTypeDefOf.Male).ElementAt(femaleBodyTypeIndex);
                    }
                    UpdateSleeveGraphic();
                }


                //Hair Colour
                Text.Anchor = TextAnchor.MiddleLeft;
                Widgets.Label(lblHairColour, "HairColour".Translate().CapitalizeFirst() + ":");

                Widgets.DrawMenuSection(btnHairColourOutlinePremade);
                Widgets.DrawShadowAround(btnHairColourOutlinePremade);


                Widgets.DrawBoxSolid(btnHairColour1, rgbConvert(51, 51, 51));
                Widgets.DrawBoxSolid(btnHairColour2, rgbConvert(79, 71, 66));
                Widgets.DrawBoxSolid(btnHairColour3, rgbConvert(64, 51, 38));
                Widgets.DrawBoxSolid(btnHairColour4, rgbConvert(77, 51, 26));
                Widgets.DrawBoxSolid(btnHairColour5, rgbConvert(90, 58, 32));
                Widgets.DrawBoxSolid(btnHairColour6, rgbConvert(132, 83, 47));
                Widgets.DrawBoxSolid(btnHairColour7, rgbConvert(193, 146, 85));
                Widgets.DrawBoxSolid(btnHairColour8, rgbConvert(237, 202, 156));



                if (Widgets.ButtonInvisible(btnHairColour1))
                {
                    setHair(rgbConvert(51, 51, 51));
                }
                else
                if (Widgets.ButtonInvisible(btnHairColour2))
                {
                    setHair(rgbConvert(79, 71, 66));
                }
                else
                if (Widgets.ButtonInvisible(btnHairColour3))
                {
                    setHair(rgbConvert(64, 51, 38));
                }
                else
                if (Widgets.ButtonInvisible(btnHairColour4))
                {
                    setHair(rgbConvert(77, 51, 26));
                }
                else
                if (Widgets.ButtonInvisible(btnHairColour5))
                {
                    setHair(rgbConvert(90, 58, 32));
                }
                else
                if (Widgets.ButtonInvisible(btnHairColour6))
                {
                    setHair(rgbConvert(132, 83, 47));
                }
                else
                if (Widgets.ButtonInvisible(btnHairColour7))
                {
                    setHair(rgbConvert(193, 146, 85));
                }
                else
                if (Widgets.ButtonInvisible(btnHairColour8))
                {
                    setHair(rgbConvert(237, 202, 156));
                }

                Widgets.DrawMenuSection(btnHairColourOutline);
                Widgets.DrawTextureFitted(btnHairColourOutline, texColor, 1);
                Widgets.DrawMenuSection(btnHairColourOutline2);
                Widgets.DrawTextureFitted(btnHairColourOutline2, texDarkness, 1);

                //if click in texColour box
                if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && Mouse.IsOver(btnHairColourOutline))
                {
                    Vector2 mPos = Event.current.mousePosition;
                    float   x    = mPos.x - btnHairColourOutline.x;
                    float   y    = mPos.y - btnHairColourOutline.y;
                    //Log.Message(x.ToString());
                    //Log.Message(y.ToString());

                    setHair(texColor.GetPixel(Convert.ToInt32(x), Convert.ToInt32(btnHairColourOutline.height - y)));
                    Event.current.Use();
                }

                //if click in Darkness box
                if (Event.current.type == EventType.MouseDown && Event.current.button == 0 && Mouse.IsOver(btnHairColourOutline2))
                {
                    Vector2 mPos = Event.current.mousePosition;
                    float   x    = mPos.x - btnHairColourOutline2.x;
                    float   y    = mPos.y - btnHairColourOutline2.y;
                    //Log.Message(x.ToString());
                    //Log.Message(y.ToString());

                    selectedColorFinal = texDarkness.GetPixel(Convert.ToInt32(x), Convert.ToInt32(btnHairColourOutline2.height - y));
                    updateColors();
                    newSleeve.story.hairColor = selectedColorFinal;
                    refreshAndroidPortrait    = true;
                    Event.current.Use();
                }

                //Hair Type
                Text.Anchor = TextAnchor.MiddleLeft;
                Widgets.Label(lblHairType, "HairType".Translate().CapitalizeFirst() + ":");
                Widgets.DrawHighlight(btnHairTypeOutline);
                if (ButtonTextSubtleCentered(btnHairTypeArrowLeft, "<"))
                {
                    if (hairTypeIndex == 0)
                    {
                        hairTypeIndex = DefDatabase <HairDef> .AllDefs.Count() - 1;
                    }
                    else
                    {
                        hairTypeIndex--;
                    }
                    newSleeve.story.hairDef = DefDatabase <HairDef> .AllDefs.ElementAt(hairTypeIndex);

                    UpdateSleeveGraphic();
                }
                if (ButtonTextSubtleCentered(btnHairTypeSelection, newSleeve.story.hairDef.LabelCap))
                {
                    IEnumerable <HairDef> hairs =
                        from hairdef in DefDatabase <HairDef> .AllDefs select hairdef;
                    FloatMenuUtility.MakeMenu <HairDef>(hairs, hairDef => hairDef.LabelCap, (HairDef hairDef) => delegate
                    {
                        newSleeve.story.hairDef = hairDef;
                        UpdateSleeveGraphic();
                    });
                }
                if (ButtonTextSubtleCentered(btnHairTypeArrowRight, ">"))
                {
                    if (hairTypeIndex == DefDatabase <HairDef> .AllDefs.Count() - 1)
                    {
                        hairTypeIndex = 0;
                    }
                    else
                    {
                        hairTypeIndex++;
                    }
                    newSleeve.story.hairDef = DefDatabase <HairDef> .AllDefs.ElementAt(hairTypeIndex);

                    UpdateSleeveGraphic();
                }

                //Time to Grow
                Widgets.Label(lblTimeToGrow, "TimeToGrow".Translate().CapitalizeFirst() + ": " + GenDate.ToStringTicksToDays(baseTicksToGrow + baseTicksToGrow2 + baseTicksToGrow3));//PUT TIME TO GROW INFO HERE

                //Require Biomass
                Widgets.Label(lblRequireBiomass, "RequireBiomass".Translate().CapitalizeFirst() + ": " + (baseMeatCost + baseMeatCost2 + baseMeatCost3));//PUT REQUIRED BIOMASS HERE

                //Vertical Divider
                //Widgets.DrawLineVertical((pawnBox.x + (btnGenderFemale.x + btnGenderFemale.width)) / 2, pawnBox.y, InitialSize.y - pawnBox.y - (buttonHeight + 53));

                //Pawn Box
                Widgets.DrawMenuSection(pawnBox);
                Widgets.DrawShadowAround(pawnBox);
                GUI.DrawTexture(pawnBoxPawn, PortraitsCache.Get(newSleeve, pawnBoxPawn.size, default(Vector3), 1f));

                //Levels of Beauty
                Text.Anchor = TextAnchor.MiddleCenter;
                Widgets.Label(lblLevelOfBeauty, "LevelOfBeauty".Translate().CapitalizeFirst() + ": " + beautyLevel);
                if (Widgets.ButtonText(btnLevelOfBeauty1, "1"))
                {
                    RemoveAllTraits(newSleeve);
                    newSleeve.story.traits.GainTrait(new Trait(TraitDefOf.Beauty, -2));
                    baseTicksToGrow2 = -420000;
                    baseMeatCost2    = -50;
                    beautyLevel      = 1;
                }
                if (Widgets.ButtonText(btnLevelOfBeauty2, "2"))
                {
                    RemoveAllTraits(newSleeve);
                    baseTicksToGrow2 = 0;
                    baseMeatCost2    = 0;
                    beautyLevel      = 2;
                }
                if (Widgets.ButtonText(btnLevelOfBeauty3, "3"))
                {
                    RemoveAllTraits(newSleeve);
                    newSleeve.story.traits.GainTrait(new Trait(TraitDefOf.Beauty, 2));
                    baseTicksToGrow2 = 420000;
                    baseTicksToGrow2 = 420;

                    baseMeatCost2 = 50;
                    beautyLevel   = 3;
                }

                //Levels of Quality

                Widgets.Label(lblLevelOfQuality, "LevelofQuality".Translate().CapitalizeFirst() + ": " + qualityLevel);
                if (Widgets.ButtonText(btnLevelOfQuality1, "1"))
                {
                    baseTicksToGrow3 = -420000;
                    baseMeatCost3    = -50;
                    RemoveAllHediffs(newSleeve);
                    newSleeve.health.AddHediff(AlteredCarbonDefOf.AC_Sleeve_Quality_Low, null);
                    qualityLevel = 1;
                }
                if (Widgets.ButtonText(btnLevelOfQuality2, "2"))
                {
                    baseTicksToGrow3 = 0;
                    baseMeatCost3    = 0;
                    RemoveAllHediffs(newSleeve);
                    newSleeve.health.AddHediff(AlteredCarbonDefOf.AC_Sleeve_Quality_Standart, null);
                    qualityLevel = 2;
                }
                if (Widgets.ButtonText(btnLevelOfQuality3, "3"))
                {
                    baseTicksToGrow3 = 420000;
                    baseTicksToGrow3 = 420;
                    baseMeatCost3    = 50;
                    RemoveAllHediffs(newSleeve);
                    newSleeve.health.AddHediff(AlteredCarbonDefOf.AC_Sleeve_Quality_High, null);
                    qualityLevel = 3;
                }

                if (Widgets.ButtonText(btnAccept, "Accept".Translate().CapitalizeFirst()))
                {
                    sleeveGrower.StartGrowth(newSleeve, baseTicksToGrow + baseTicksToGrow2 + baseTicksToGrow3, baseMeatCost + baseMeatCost2 + baseMeatCost3);
                    this.Close();
                }
                if (Widgets.ButtonText(btnCancel, "Cancel".Translate().CapitalizeFirst()))
                {
                    this.Close();
                }
            }
            Text.Anchor = TextAnchor.UpperLeft;
        }
Exemple #28
0
        public override void DoWindowContents(Rect inRect)
        {
            //grab before anchor/font
            GameFont   fontBefore   = Text.Font;
            TextAnchor anchorBefore = Text.Anchor;



            //Buildings
            int i = 0;

            foreach (BuildingFCDef building in buildingList)
            {
                newBuildingWindow = new Rect(BaseBuildingWindow.x, BaseBuildingWindow.y + (i * (rowHeight)) + scroll, BaseBuildingWindow.width, BaseBuildingWindow.height);
                newBuildingIcon   = new Rect(BaseBuildingIcon.x, BaseBuildingIcon.y + (i * (rowHeight)) + scroll, BaseBuildingIcon.width, BaseBuildingIcon.height);
                newBuildingLabel  = new Rect(BaseBuildingLabel.x, BaseBuildingLabel.y + (i * (rowHeight)) + scroll, BaseBuildingLabel.width, BaseBuildingLabel.height);
                newBuildingDesc   = new Rect(BaseBuildingDesc.x, BaseBuildingDesc.y + (i * (rowHeight)) + scroll, BaseBuildingDesc.width, BaseBuildingDesc.height);

                if (Widgets.ButtonInvisible(newBuildingWindow))
                {
                    //If click on building
                    List <FloatMenuOption> list = new List <FloatMenuOption>();

                    if (building == buildingDef)
                    {
                        //if the same building
                        list.Add(new FloatMenuOption("Destroy".Translate(), delegate
                        {
                            settlement.deconstructBuilding(buildingSlot);
                            Find.WindowStack.TryRemove(this);
                            Find.WindowStack.WindowOfType <settlementWindowFC>().WindowUpdateFC();
                        }));
                    }
                    else
                    {
                        //if not the same building
                        list.Add(new FloatMenuOption("Build".Translate(), delegate
                        {
                            if (settlement.validConstructBuilding(building, buildingSlot, settlement))
                            {
                                FCEvent tmpEvt         = new FCEvent(true);
                                tmpEvt.def             = FCEventDefOf.constructBuilding;
                                tmpEvt.source          = settlement.mapLocation;
                                tmpEvt.building        = building;
                                tmpEvt.buildingSlot    = buildingSlot;
                                tmpEvt.timeTillTrigger = Find.TickManager.TicksGame + building.constructionDuration;
                                Find.World.GetComponent <FactionFC>().addEvent(tmpEvt);

                                PaymentUtil.paySilver(Convert.ToInt32(building.cost));
                                settlement.deconstructBuilding(buildingSlot);
                                Messages.Message(building.label + " " + "WillBeConstructedIn".Translate() + " " + GenDate.ToStringTicksToDays(tmpEvt.timeTillTrigger - Find.TickManager.TicksGame), MessageTypeDefOf.PositiveEvent);
                                settlement.buildings[buildingSlot] = BuildingFCDefOf.Construction;
                                Find.WindowStack.TryRemove(this);
                                Find.WindowStack.WindowOfType <settlementWindowFC>().WindowUpdateFC();
                            }
                        }));
                    }



                    FloatMenu menu = new FloatMenu(list);
                    Find.WindowStack.Add(menu);
                }


                Widgets.DrawMenuSection(newBuildingWindow);
                Widgets.DrawMenuSection(newBuildingIcon);
                Widgets.DrawLightHighlight(newBuildingIcon);
                Widgets.ButtonImage(newBuildingIcon, building.icon);

                Text.Font = GameFont.Small;
                Widgets.ButtonTextSubtle(newBuildingLabel, "");
                Widgets.Label(newBuildingLabel, "  " + building.LabelCap + " - " + "Cost".Translate() + ": " + building.cost);

                Text.Font = GameFont.Tiny;
                Widgets.Label(newBuildingDesc, building.desc);



                i++;
            }


            //Top Window
            Widgets.DrawMenuSection(TopWindow);
            Widgets.DrawHighlight(TopWindow);
            Widgets.DrawMenuSection(TopIcon);
            Widgets.DrawLightHighlight(TopIcon);

            Widgets.DrawBox(new Rect(0, 0, 400, 500));
            Widgets.ButtonImage(TopIcon, buildingDef.icon);

            Widgets.ButtonTextSubtle(TopName, "");
            Text.Font   = GameFont.Medium;
            Text.Anchor = TextAnchor.UpperLeft;
            Widgets.Label(new Rect(TopName.x + 5, TopName.y, TopName.width, TopName.height), buildingDef.LabelCap);

            Widgets.DrawMenuSection(new Rect(TopDescription.x - 5, TopDescription.y - 5, TopDescription.width, TopDescription.height));
            Text.Font = GameFont.Small;
            Widgets.Label(TopDescription, buildingDef.desc);

            Widgets.DrawLineHorizontal(0, TopWindow.y + TopWindow.height, 400);



            //reset anchor/font
            Text.Font   = fontBefore;
            Text.Anchor = anchorBefore;

            if (Event.current.type == EventType.ScrollWheel)
            {
                scrollWindow(Event.current.delta.y);
            }
        }
Exemple #29
0
        public void DoWindowContents(Rect wrect)
        {
            var options = new Listing_Standard();

            options.ColumnWidth = (wrect.width - Listing.ColumnSpacing) / 2;
            options.Begin(wrect);
            TextAnchor anchor = Text.Anchor;

            options.Label("TD.SettingIslandDays".Translate() + String.Format("{0:0.0}", islandAddedDays));
            islandAddedDays = options.Slider(islandAddedDays, 0f, 20f);

            options.Label("TD.SettingRemotenessSpeed".Translate());
            distanceFactor = options.Slider(distanceFactor, .05f, .5f);

            options.Label("TD.SettingRemotenessFactor".Translate() + String.Format("{0:0.0}x", visitDiminishingFactor));
            visitDiminishingFactor = options.Slider(visitDiminishingFactor, 0.1f, 5);

            int  totalDays = 10;
            Rect graphLine = options.GetRect(Text.LineHeight * 12);
            Rect graphRect = graphLine.LeftPartPixels(graphLine.height);

            TDWidgets.DrawGraph(graphRect, "TD.DaysTravel".Translate(), "TD.DaysAdded".Translate(), "{0:0}", "{0:0}", 0, totalDays, DelayDays.AddedDays, null, null, 5);

            Map map = Find.CurrentMap;

            if (map != null && (Prefs.DevMode || Harmony.DEBUG))             //That's one roundabout way to check DEBUG
            {
                int gameTicks = GenTicks.TicksGame;
                options.Label("TD.GameTicks".Translate() + gameTicks);

                FieldInfo lastThreatBigTickInfo = AccessTools.Field(typeof(StoryState), "lastThreatBigTick");


                int lastThreatTick = (int)lastThreatBigTickInfo.GetValue(map.storyState);
                options.Label("TD.ForMap".Translate() + map.info.parent.LabelShortCap);
                options.Label("TD.BigThreatsDelayed".Translate() + lastThreatTick);

                float days = GenDate.TicksToDays(lastThreatTick - gameTicks);
                if (days >= 0)
                {
                    options.Label("TD.XDaysInFuture".Translate());
                }
                if (options.ButtonText("TD.ResetToNOW".Translate()))
                {
                    lastThreatBigTickInfo.SetValue(map.StoryState, GenTicks.TicksGame);
                }

                options.Label(String.Format("TD.ThreatWillDelay".Translate(), DelayDays.DelayRaidDays(map)));
                options.Label(String.Format("TD.GuestWillDelay".Translate(), DelayDays.DelayAllyDays(map)));
            }

            options.NewColumn();

            options.CheckboxLabeled("TD.WriteLogs".Translate(), ref logResults);

            options.Label(String.Format("TD.SettingMinimumWealth".Translate(), wealthLimit));
            wealthLimit = options.Slider(wealthLimit, 1, 1000000);

            options.Label(String.Format("TD.SettingMaximumWealth".Translate(), wealthMax));
            wealthMax = options.Slider(wealthMax, 1, 1000000);

            options.Label(String.Format("TD.SettingWealthFactor".Translate(), wealthFactor));
            wealthFactor = options.Slider(wealthFactor, 0f, 1f);

            options.Label("TD.SettingCurvinessFactor".Translate());
            wealthCurvy = options.Slider(wealthCurvy, 0f, 50f);

            graphLine = options.GetRect(Text.LineHeight * 16);
            graphRect = graphLine.LeftPartPixels(graphLine.height);
            TDWidgets.DrawGraph(graphRect, "TD.ColonyWealth".Translate(), "TD.PercentDelayReduced".Translate(), "{0:0}", "{0:P0}", 0, 1000000, DelayDays.WealthReduction, 0, 1f);

            Text.Anchor = anchor;
            options.End();
        }
        private void DrawTemperatureForecast()
        {
            DrawEntryHeader("PLMWT2T_TemperatureForecast".Translate(), backgroundColor: Color.magenta);

            var tileId = Find.WorldSelector.selectedTile;

            if (!Find.WorldSelector.AnyObjectOrTileSelected || tileId < 0)
            {
                var labelRect = ListingStandard.GetRect(DefaultElementHeight);
                Widgets.Label(labelRect, "PLMWT2T_TempPickTileOnWorldMap".Translate());
                _selectedTileIdForTemperatureForecast = -1;
                return;
            }

            ListingStandard.LabelDouble($"{"PLMWT2T_TempSelectedTile".Translate()}: ", tileId.ToString());
            _selectedTileIdForTemperatureForecast = tileId;

            ListingStandard.GapLine(DefaultGapLineHeight);

            /*
             * Day / Quadrum / Year selector
             */
            var backupAnchor = Text.Anchor;

            Text.Anchor = TextAnchor.MiddleLeft;

            // day
            var daySelector  = ListingStandard.GetRect(30f);
            var dayLabelRect = daySelector.LeftPart(0.70f);
            var dayFieldRect = daySelector.RightPart(0.30f);

            Widgets.Label(dayLabelRect, $"{"PLMWT2T_QuadrumDay".Translate()} [1, 15]: ");
            Widgets.TextFieldNumeric(dayFieldRect, ref _dayOfQuadrum, ref _dayOfQuadrumString, 1,
                                     GenDate.DaysPerQuadrum);

            ListingStandard.Gap(6f);

            // quadrum
            var quadrumRect       = ListingStandard.GetRect(30f);
            var quadrumButtonRect = quadrumRect.LeftHalf();

            if (Widgets.ButtonText(quadrumButtonRect, "PLMWT2T_SelectQuadrum".Translate()))
            {
                // get all possible enumeration values for hilliness
                var quadrumList = Enum.GetValues(typeof(Quadrum)).Cast <Quadrum>().ToList();

                var floatMenuOptions = new List <FloatMenuOption>();
                foreach (var quadrum in quadrumList)
                {
                    if (quadrum == Quadrum.Undefined)
                    {
                        continue;
                    }

                    var label = quadrum.Label();

                    var menuOption = new FloatMenuOption(label,
                                                         delegate { _quadrum = quadrum; });
                    floatMenuOptions.Add(menuOption);
                }

                var floatMenu = new FloatMenu(floatMenuOptions, "PLMWT2T_SelectQuadrum".Translate());
                Find.WindowStack.Add(floatMenu);
            }
            var quadrumLabelRect = quadrumRect.RightHalf();

            Widgets.Label(quadrumLabelRect, _quadrum.ToString());

            ListingStandard.Gap(6f);

            // year
            var yearSelector  = ListingStandard.GetRect(30f);
            var yearLabelRect = yearSelector.LeftPart(0.7f);
            var yearFieldRect = yearSelector.RightPart(0.3f);

            Widgets.Label(yearLabelRect, $"{"ClockYear".Translate()} [{GenDate.DefaultStartingYear}, {GenDate.DefaultStartingYear + 50}]: ");
            Widgets.TextFieldNumeric(yearFieldRect, ref _year, ref _yearString, GenDate.DefaultStartingYear,
                                     GenDate.DefaultStartingYear + 50);

            // translate day, quadrum and year to ticks
            _dateTicks = WorldData.DateToTicks(_dayOfQuadrum - 1, _quadrum, _year);

            // date display
            var dateNowRect       = ListingStandard.GetRect(30f);
            var labelDateLeftRect = dateNowRect.LeftPart(0.20f);

            Widgets.Label(labelDateLeftRect, $"{"ClockDate".Translate()}: ");
            var labelDateRightRect = dateNowRect.RightPart(0.60f);
            var dateString         = GenDate.DateReadoutStringAt(_dateTicks,
                                                                 Find.WorldGrid.LongLatOf(_selectedTileIdForTemperatureForecast));

            Widgets.Label(labelDateRightRect, dateString);

            Text.Anchor = backupAnchor;

            ListingStandard.GapLine(DefaultGapLineHeight);

            /*
             * Forecast
             */
            if (ListingStandard.ButtonText("PLMWT2T_ViewTemperatureForecast".Translate()))
            {
                ViewTemperatureForecast(_selectedTileIdForTemperatureForecast, _dateTicks);
            }
        }
Exemple #31
0
        public static void Draw(Rect rect)
        {
            rect.yMin += 17f;
            GUI.BeginGroup(rect);
            Rect graphRect  = new Rect(0f, 0f, rect.width, rect.height - 100f);
            Rect legendRect = new Rect(468f, graphRect.yMax, rect.width - 468f, 80f);
            Rect rect2      = new Rect(0f, legendRect.yMin + 44f, rect.width, 40f);

            if (RecordGraphUtility.CurRecordGroup != null)
            {
                RecordGraphUtility.marks.Clear();
                List <Tale> allTalesListForReading = Find.TaleManager.AllTalesListForReading;
                for (int i = 0; i < allTalesListForReading.Count; i++)
                {
                    Tale tale = allTalesListForReading[i];
                    if (tale.def.type == TaleType.PermanentHistorical)
                    {
                        float x = (float)GenDate.TickAbsToGame(tale.date) / 60000f;
                        RecordGraphUtility.marks.Add(new CurveMark(x, tale.ShortSummary, tale.def.historyGraphColor));
                    }
                }
                RecordGraphUtility.CurRecordGroup.DrawGraph(graphRect, legendRect, RecordGraphUtility.graphSection, RecordGraphUtility.marks);
            }
            Text.Font = GameFont.Small;
            float num = (float)Find.TickManager.TicksGame / 60000f;

            if (Widgets.ButtonText(new Rect(0f, legendRect.yMin, 110f, 40f), "Last30Days".Translate(), true, true, true))
            {
                RecordGraphUtility.graphSection = new FloatRange(Mathf.Max(0f, num - 30f), num);
                SoundDefOf.Click.PlayOneShotOnCamera(null);
            }
            if (Widgets.ButtonText(new Rect(114f, legendRect.yMin, 110f, 40f), "Last100Days".Translate(), true, true, true))
            {
                RecordGraphUtility.graphSection = new FloatRange(Mathf.Max(0f, num - 100f), num);
                SoundDefOf.Click.PlayOneShotOnCamera(null);
            }
            if (Widgets.ButtonText(new Rect(228f, legendRect.yMin, 110f, 40f), "Last300Days".Translate(), true, true, true))
            {
                RecordGraphUtility.graphSection = new FloatRange(Mathf.Max(0f, num - 300f), num);
                SoundDefOf.Click.PlayOneShotOnCamera(null);
            }
            if (Widgets.ButtonText(new Rect(342f, legendRect.yMin, 110f, 40f), "AllDays".Translate(), true, true, true))
            {
                RecordGraphUtility.graphSection = new FloatRange(0f, num);
                SoundDefOf.Click.PlayOneShotOnCamera(null);
            }
            if (Widgets.ButtonText(new Rect(rect2.x, rect2.y, 110f, 40f), "SelectGraph".Translate(), true, true, true))
            {
                List <FloatMenuOption> list = new List <FloatMenuOption>();
                foreach (RecordIdentifier recordID in RecordGraphUtility.comp.NumericRecords)
                {
                    RecordIdentifier localRecordID = recordID;
                    list.Add(new FloatMenuOption(localRecordID.Label, delegate() {
                        RecordGraphUtility.CurRecordID = localRecordID;
                    }, MenuOptionPriority.Default, null, null, 0f, null, null));
                }
                FloatMenu window = new FloatMenu(list, "SelectGraph".Translate(), false);
                Find.WindowStack.Add(window);
            }
            if (RecordGraphUtility.CurRecordID.IsVaild)
            {
                Text.Anchor = TextAnchor.MiddleLeft;
                Widgets.Label(new Rect(rect2.x + 118f, rect2.y, 300f, 40f), RecordGraphUtility.CurRecordID.Label);
                Text.Anchor = TextAnchor.UpperLeft;
            }
            GUI.EndGroup();
        }
        public static void ViewTemperatureForecast(int tileId, int dateTicks)
        {
            /*
             * Forecast for twelves of year.
             */
            var tempsForTwelves = TemperatureData.TemperaturesForTwelfth(tileId);
            var twelvesGetters  = new List <ColumnData <TemperatureForecastForTwelfth> >
            {
                new ColumnData <TemperatureForecastForTwelfth>("PLTFW_Quadrum".Translate(), "PLTFW_QuadrumToolTip".Translate(),
                                                               tfft => $"{tfft.Twelfth.GetQuadrum()}"),
                new ColumnData <TemperatureForecastForTwelfth>("PLTFW_Season".Translate(), "PLTFW_SeasonToolTip".Translate(),
                                                               tfft => $"{tfft.Twelfth.GetQuadrum().GetSeason(tfft.Latitude)}"),
                new ColumnData <TemperatureForecastForTwelfth>("PLTFW_Twelfth".Translate(), "PLTFW_TwelfthToolTip".Translate(),
                                                               tfft => $"{tfft.Twelfth}"),
                new ColumnData <TemperatureForecastForTwelfth>("PLTFW_AvgTemp".Translate(), "PLTFW_AvgTempToolTip".Translate(),
                                                               tfft => $"{tfft.AverageTemperatureForTwelfth:F2}")
            };
            var tableViewTempForTwelves =
                new TableView <TemperatureForecastForTwelfth>("PLTFW_ForecastForTwelves".Translate(), tempsForTwelves,
                                                              twelvesGetters);


            var dateString = GenDate.DateReadoutStringAt(dateTicks, Find.WorldGrid.LongLatOf(tileId));

            /*
             * Forecast for hours of day
             */
            var temperaturesForHoursOfDay =
                TemperatureData.TemperaturesForDay(tileId, dateTicks);
            var temperaturesForHoursGetters = new List <ColumnData <TemperatureForecastForDay> >
            {
                new ColumnData <TemperatureForecastForDay>("PLTFW_Hour".Translate(), "PLTFW_HourToolTip".Translate(), tffd => $"{tffd.Hour}"),
                new ColumnData <TemperatureForecastForDay>("PLTFW_OutdoorTemp".Translate(), "PLTFW_OutdoorTempToolTip".Translate(),
                                                           tffd => $"{tffd.OutdoorTemperature:F1}"),
                //new ColumnData<TemperatureForecastForDay>("RandomVar", "Daily Random Variation", tffd => $"{tffd.DailyRandomVariation:F1}"),
                new ColumnData <TemperatureForecastForDay>("PLTFW_OffDRV".Translate(), "PLTFW_OffDRVToolTip".Translate(),
                                                           tffd => $"{tffd.OffsetFromDailyRandomVariation:F1}"),
                new ColumnData <TemperatureForecastForDay>("PLTFW_OffSeason".Translate(), "PLTFW_OffSeasonToolTip".Translate(),
                                                           tffd => $"{tffd.OffsetFromSeasonCycle:F1}"),
                new ColumnData <TemperatureForecastForDay>("PLTFW_SunEff".Translate(), "PLTFW_SunEffToolTip".Translate(),
                                                           tffd => $"{tffd.OffsetFromSunCycle:F1}")
            };

            var tableName           = string.Format("PLTFW_ForecastForHours".Translate(), GenDate.HoursPerDay, dateString);
            var tableViewTempForDay =
                new TableView <TemperatureForecastForDay>(tableName, temperaturesForHoursOfDay,
                                                          temperaturesForHoursGetters);

            /*
             * Forecast for days or year
             */
            var tempsForDaysOfYear =
                TemperatureData.TemperaturesForYear(tileId, dateTicks);
            var temperaturesForDaysOfYearGetters = new List <ColumnData <TemperatureForecastForYear> >
            {
                new ColumnData <TemperatureForecastForYear>("PLTFW_Day".Translate(), "PLTFW_DayToolTip".Translate(), tffy => $"{tffy.Day}"),
                new ColumnData <TemperatureForecastForYear>("PLTFW_Min".Translate(), "PLTFW_MinToolTip".Translate(),
                                                            tffy => $"{tffy.MinTemp:F2}"),
                new ColumnData <TemperatureForecastForYear>("PLTFW_Max".Translate(), "PLTFW_MaxToolTip".Translate(),
                                                            tffy => $"{tffy.MaxTemp:F2}"),
                new ColumnData <TemperatureForecastForYear>("PLTFW_OffSeason".Translate(), "PLTFW_OffSeasonToolTip".Translate(),
                                                            tffy => $"{tffy.OffsetFromSeasonCycle:F2}"),
                new ColumnData <TemperatureForecastForYear>("PLTFW_OffDRV".Translate(), "PLTFW_OffDRVToolTip".Translate(),
                                                            tffy => $"{tffy.OffsetFromDailyRandomVariation:F2}")
            };
            var tableViewTempForYear =
                new TableView <TemperatureForecastForYear>("PLTFW_ForecastForNextYear".Translate(), tempsForDaysOfYear,
                                                           temperaturesForDaysOfYearGetters);

            /*
             * Window and views
             */
            var temperatureWindow = new TableWindow(tileId, dateTicks, 0.33f);

            temperatureWindow.ClearTables();
            temperatureWindow.AddTable(tableViewTempForDay);
            temperatureWindow.AddTable(tableViewTempForTwelves);
            temperatureWindow.AddTable(tableViewTempForYear);

            Find.WindowStack.Add(temperatureWindow);
        }
        private static void GenerateRandomAge(Pawn pawn, PawnGenerationRequest request)
        {
            if (request.FixedBiologicalAge.HasValue && request.FixedChronologicalAge.HasValue)
            {
                float?fixedBiologicalAge    = request.FixedBiologicalAge;
                bool  arg_46_0              = fixedBiologicalAge.HasValue;
                float?fixedChronologicalAge = request.FixedChronologicalAge;
                if ((arg_46_0 & fixedChronologicalAge.HasValue) && fixedBiologicalAge.GetValueOrDefault() > fixedChronologicalAge.GetValueOrDefault())
                {
                    Log.Warning(string.Concat(new object[]
                    {
                        "Tried to generate age for pawn ",
                        pawn,
                        ", but pawn generation request demands biological age (",
                        request.FixedBiologicalAge,
                        ") to be greater than chronological age (",
                        request.FixedChronologicalAge,
                        ")."
                    }));
                }
            }
            if (request.Newborn)
            {
                pawn.ageTracker.AgeBiologicalTicks = 0L;
            }
            else if (request.FixedBiologicalAge.HasValue)
            {
                pawn.ageTracker.AgeBiologicalTicks = (long)(request.FixedBiologicalAge.Value * 3600000f);
            }
            else
            {
                int   num = 0;
                float num2;
                while (true)
                {
                    if (pawn.RaceProps.ageGenerationCurve != null)
                    {
                        num2 = (float)Mathf.RoundToInt(Rand.ByCurve(pawn.RaceProps.ageGenerationCurve, 200));
                    }
                    else if (pawn.RaceProps.IsMechanoid)
                    {
                        num2 = (float)Rand.Range(0, 2500);
                    }
                    else
                    {
                        num2 = Rand.ByCurve(PawnGenerator.DefaultAgeGenerationCurve, 200) * pawn.RaceProps.lifeExpectancy;
                    }
                    num++;
                    if (num > 300)
                    {
                        break;
                    }
                    if (num2 <= (float)pawn.kindDef.maxGenerationAge && num2 >= (float)pawn.kindDef.minGenerationAge)
                    {
                        goto IL_1D9;
                    }
                }
                Log.Error("Tried 300 times to generate age for " + pawn);
IL_1D9:
                pawn.ageTracker.AgeBiologicalTicks = (long)(num2 * 3600000f) + (long)Rand.Range(0, 3600000);
            }
            if (request.Newborn)
            {
                pawn.ageTracker.AgeChronologicalTicks = 0L;
            }
            else if (request.FixedChronologicalAge.HasValue)
            {
                pawn.ageTracker.AgeChronologicalTicks = (long)(request.FixedChronologicalAge.Value * 3600000f);
            }
            else
            {
                int num3;
                if (request.CertainlyBeenInCryptosleep || Rand.Value < pawn.kindDef.backstoryCryptosleepCommonality)
                {
                    float value = Rand.Value;
                    if (value < 0.7f)
                    {
                        num3 = Rand.Range(0, 100);
                    }
                    else if (value < 0.95f)
                    {
                        num3 = Rand.Range(100, 1000);
                    }
                    else
                    {
                        int max = GenDate.Year((long)GenTicks.TicksAbs, 0f) - 2026 - pawn.ageTracker.AgeBiologicalYears;
                        num3 = Rand.Range(1000, max);
                    }
                }
                else
                {
                    num3 = 0;
                }
                int  ticksAbs = GenTicks.TicksAbs;
                long num4     = (long)ticksAbs - pawn.ageTracker.AgeBiologicalTicks;
                num4 -= (long)num3 * 3600000L;
                pawn.ageTracker.BirthAbsTicks = num4;
            }
            if (pawn.ageTracker.AgeBiologicalTicks > pawn.ageTracker.AgeChronologicalTicks)
            {
                pawn.ageTracker.AgeChronologicalTicks = pawn.ageTracker.AgeBiologicalTicks;
            }
        }
        public static DiaNode PrologueNode()
        {
            TravelingIncidentCaravan caravan = DialogUtilities.tempCaravan;
            Pawn pawn = DialogUtilities.tempPawn;
            InterceptedIncident_HumanCrowd_RaidEnemy incident = caravan.incident as InterceptedIncident_HumanCrowd_RaidEnemy;
            RaidingGoal goal = incident.goal;

            if (incident == null)
            {
                return(null);
            }
            if (incident.raidGoalType == RaidGoalType.Smite)
            {
                return(null);
            }

            if (incident.SourceFaction == Faction.OfMechanoids)
            {
                return(DialogMaker_TryToContact.MechanoidAnswers());
            }

            StringBuilder sb = new StringBuilder("PES_RaidNeg_Proglog".Translate(caravan.CaravanTitle, incident.SourceFaction));

            sb.AppendLine();
            sb.AppendLine();

            bool polite = false;

            if (incident.raidGoalType == RaidGoalType.Rescue)
            {
                if (new FloatRange(0f, 1f).RandomInRange < 0.5f)
                {
                    polite = true;
                }
            }
            if (incident.raidGoalType == RaidGoalType.Extortion)
            {
                if (new FloatRange(0f, 1f).RandomInRange < 0.2f)
                {
                    polite = true;
                }
            }

            if (polite)
            {
                sb.Append("PES_RaidNeg_Attitude_Polite".Translate());
            }
            else
            {
                sb.Append("PES_RaidNeg_Attitude_Rude".Translate());
            }
            sb.AppendLine(goal.GoalExpStr);
            sb.AppendLine();

            if (polite)
            {
                sb.AppendLine("PES_RaidNeg_DemandSurrender_Polite".Translate());
            }
            else
            {
                sb.AppendLine("PES_RaidNeg_DemandSurrender_rude".Translate());
            }

            DiaNode diaNode = new DiaNode(sb.ToString());

            DiaOption option;

            string rebuffStr = "PES_RaidNeg_Rebuff_Head".Translate() + ("PES_RaidNeg_Rebuff_" + incident.raidGoalType.ToString()).Translate() + "\n";

            option      = new DiaOption(rebuffStr);
            option.link = RebuffNode();
            diaNode.options.Add(option);

            option      = new DiaOption("PES_RaidNeg_NegDeeper".Translate() + "\n");
            option.link = NegotiateDeepNode();

            diaNode.options.Add(option);

            option      = new DiaOption("PES_RaidNeg_Delay".Translate() + "\n");
            option.link = DelayNode();
            if (caravan.stageRemainingTick > 0)
            {
                option.Disable("PES_RaidNeg_Delay_Staging".Translate(GenDate.ToStringTicksToPeriod(caravan.stageRemainingTick)));
            }
            else if (caravan.StagedBefore)
            {
                option.Disable("PES_RaidNeg_Delay_DoneBefore".Translate());
            }
            else if (caravan.delayCoolDownTick > 0)
            {
                option.Disable("PES_RaidNeg_Delay_CoolDown".Translate(GenDate.ToStringTicksToPeriod(caravan.delayCoolDownTick)));
            }
            diaNode.options.Add(option);

            diaNode.options.Add(DialogUtilities.CurtOption("PES_Cancel", null, null, true));
            return(diaNode);
        }
Exemple #35
0
 public override void Tick(int currentTick)
 {
     //Performance reporting tick
     if (EnablePerformanceTesting() && currentTick % GenDate.TicksPerDay == 0 && PerformanceSetup.performanceTotals.Keys.Count > 0)
     {
         Dictionary <string, float> averages = PerformanceSetup.performanceTotals.ToDictionary(x => x.Key, x => (float)x.Value / (float)PerformanceSetup.performanceCalls[x.Key]);
         int topAmt = Math.Min(10, averages.Count);
         List <KeyValuePair <string, float> > avgTicks = (from avg in averages orderby avg.Value descending select avg).Take(topAmt).ToList();
         List <KeyValuePair <string, float> > topTicks = (from avg in averages orderby avg.Value * PerformanceSetup.performanceCalls[avg.Key] descending select avg).Take(topAmt).ToList();
         StringBuilder avgString = new StringBuilder();
         foreach (KeyValuePair <string, float> t in avgTicks)
         {
             avgString.AppendLine(t.Key + " (" + t.Value + ")");
         }
         StringBuilder topString = new StringBuilder();
         foreach (KeyValuePair <string, float> t in topTicks)
         {
             topString.AppendLine(t.Key + " (" + avgTicks.Find(x => x.Key == t.Key).Value + ")");
         }
         Log.Message("Psychology :: Performance Report :: Top " + topAmt + " average tick consumers:\n" + avgString.ToString() + "\nTop " + topAmt + " weighted tick consumers: " + topString.ToString());
     }
     //Constituent tick
     if (currentTick % GenDate.TicksPerHour * 2 == 0)
     {
         Map playerFactionMap            = Find.WorldObjects.SettlementBases.Find(b => b.Faction.IsPlayer).Map;
         IEnumerable <Pawn> constituents = (from p in playerFactionMap.mapPawns.FreeColonistsSpawned
                                            where !p.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && p.GetLord() == null && p.GetTimeAssignment() != TimeAssignmentDefOf.Work && p.Awake()
                                            select p);
         if (constituents.Count() > 0)
         {
             Pawn potentialConstituent       = constituents.RandomElementByWeight(p => 0.0001f + Mathf.Pow(Mathf.Abs(0.7f - p.needs.mood.CurLevel), 2));
             IEnumerable <Pawn> activeMayors = (from m in playerFactionMap.mapPawns.FreeColonistsSpawned
                                                where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == potentialConstituent.Map.Tile &&
                                                m.GetTimeAssignment() != TimeAssignmentDefOf.Work && m.GetTimeAssignment() != TimeAssignmentDefOf.Sleep && m.GetLord() == null && m.Awake() && m.GetLord() == null
                                                select m);
             if (potentialConstituent != null && !potentialConstituent.Downed && !potentialConstituent.Drafted && potentialConstituent.health.summaryHealth.SummaryHealthPercent >= 1f && potentialConstituent.GetTimeAssignment() != TimeAssignmentDefOf.Work && activeMayors.Count() > 0)
             {
                 Pawn    mayor  = activeMayors.RandomElement(); //There should only be one.
                 IntVec3 gather = default(IntVec3);
                 String  found  = null;
                 if (mayor.Map.GetComponent <OfficeTableMapComponent>().officeTable != null)
                 {
                     gather = mayor.Map.GetComponent <OfficeTableMapComponent>().officeTable.parent.Position;
                     found  = "office";
                 }
                 else if (mayor.ownership != null && mayor.ownership.OwnedBed != null)
                 {
                     gather = mayor.ownership.OwnedBed.Position;
                     found  = "bed";
                 }
                 if (PsycheHelper.PsychologyEnabled(potentialConstituent) && Rand.Chance((1f - PsycheHelper.Comp(potentialConstituent).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Independent)) / 5f) && (found != null || RCellFinder.TryFindPartySpot(mayor, out gather)) &&
                     (!mayor.Drafted && !mayor.Downed && mayor.health.summaryHealth.SummaryHealthPercent >= 1f && mayor.GetTimeAssignment() != TimeAssignmentDefOf.Work && (mayor.CurJob == null || mayor.CurJob.def != JobDefOf.TendPatient)))
                 {
                     List <Pawn> pawns = new List <Pawn>();
                     pawns.Add(mayor);
                     pawns.Add(potentialConstituent);
                     Lord meeting = LordMaker.MakeNewLord(mayor.Faction, new LordJob_VisitMayor(gather, potentialConstituent, mayor, (potentialConstituent.needs.mood.CurLevel < (potentialConstituent.mindState.mentalBreaker.BreakThresholdMinor * 1.25f))), mayor.Map, pawns);
                     mayor.jobs.EndCurrentJob(Verse.AI.JobCondition.InterruptForced);
                     potentialConstituent.jobs.EndCurrentJob(Verse.AI.JobCondition.InterruptForced);
                     if (found == "bed")
                     {
                         mayor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MayorNoOffice);
                     }
                     else if (found == null)
                     {
                         mayor.needs.mood.thoughts.memories.TryGainMemory(ThoughtDefOfPsychology.MayorNoBedroom);
                     }
                 }
             }
         }
     }
     //Election tick
     if (currentTick % (GenDate.TicksPerDay / 4f) == 0)
     {
         foreach (Settlement settlement in Find.WorldObjects.Settlements)
         {
             //Self-explanatory.
             if (!PsychologyBase.ActivateElections())
             {
                 continue;
             }
             //If the base isn't owned or named by the player, no election can be held.
             if (!settlement.Faction.IsPlayer || !settlement.namedByPlayer)
             {
                 continue;
             }
             //If the base is not at least a year old, no election will be held.
             if ((Find.TickManager.TicksGame - settlement.creationGameTicks) / GenDate.TicksPerYear < 1)
             {
                 continue;
             }
             //A base must have at least 7 people in it to hold an election.
             if (settlement.Map.mapPawns.FreeColonistsSpawnedCount < 7)
             {
                 continue;
             }
             //If an election is already being held, don't start a new one.
             if (settlement.Map.gameConditionManager.ConditionIsActive(GameConditionDefOfPsychology.Election) || settlement.Map.lordManager.lords.Find(l => l.LordJob is LordJob_Joinable_Election) != null)
             {
                 continue;
             }
             //Elections are held in Septober (because I guess some maps don't have fall?) and during the day.
             if (GenDate.Quadrum(Find.TickManager.TicksAbs, Find.WorldGrid.LongLatOf(settlement.Tile).x) != Quadrum.Septober || (GenLocalDate.HourOfDay(settlement.Map) < 7 || GenLocalDate.HourOfDay(settlement.Map) > 20))
             {
                 continue;
             }
             //If an election has already been completed this year, don't start a new one.
             IEnumerable <Pawn> activeMayors = (from m in settlement.Map.mapPawns.FreeColonistsSpawned
                                                where !m.Dead && m.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).worldTileElectedOn == settlement.Map.Tile && ((Hediff_Mayor)m.health.hediffSet.GetFirstHediffOfDef(HediffDefOfPsychology.Mayor)).yearElected == GenLocalDate.Year(settlement.Map.Tile)
                                                select m);
             if (activeMayors.Count() > 0)
             {
                 continue;
             }
             //Try to space out the elections so they don't all proc at once.
             if (Rand.RangeInclusive(1, 15 - GenLocalDate.DayOfQuadrum(settlement.Map.Tile)) > 1)
             {
                 continue;
             }
             IncidentParms parms = new IncidentParms();
             parms.target  = settlement.Map;
             parms.faction = settlement.Faction;
             FiringIncident fi = new FiringIncident(IncidentDefOfPsychology.Election, null, parms);
             Find.Storyteller.TryFire(fi);
         }
     }
 }
        public static DiaNode NegotiateDeepNode()
        {
            TravelingIncidentCaravan caravan = DialogUtilities.tempCaravan;
            Pawn pawn = DialogUtilities.tempPawn;
            InterceptedIncident_HumanCrowd_RaidEnemy incident = caravan.incident as InterceptedIncident_HumanCrowd_RaidEnemy;
            RaidingGoal goal = incident.goal;

            if (incident == null)
            {
                return(null);
            }
            if (incident.raidGoalType == RaidGoalType.Smite)
            {
                return(null);
            }

            DiaNode       diaNode = new DiaNode("PES_RaidNeg_NegDeeper_Prolog".Translate());
            DiaOption     option;
            StringBuilder sb;
            string        failReason;

            //surrender
            option = new DiaOption("PES_RaidNeg_NegDeeper_Surrender".Translate() + "\n");
            if (!goal.IsAchievable(out failReason))
            {
                option.disabled       = true;
                option.disabledReason = failReason;
            }
            else
            {
                DiaNode surrenderConfirmation()
                {
                    DiaNode cnode = new DiaNode("PES_RaidNeg_NegDeeper_Surrender_Comfirmation".Translate());

                    cnode.options.Add(DialogUtilities.CurtOption("PES_SimpleConfirm", null, () => { goal.Achieve(); }, true));
                    cnode.options.Add(DialogUtilities.CurtOption("PES_Cancel", null, null, true));
                    return(cnode);
                }

                option.link = surrenderConfirmation();
            }
            diaNode.options.Add(option);

            //bargain
            option = new DiaOption("PES_RaidNeg_NegDeeper_Bargain".Translate() + "\n");
            if (!goal.CanBargain(out failReason))
            {
                option.disabled       = true;
                option.disabledReason = failReason;
            }
            else if (caravan.negotiateCoolDownTick > 0)
            {
                option.Disable("PES_RaidNeg_NegCoolDown".Translate(GenDate.ToStringTicksToPeriod(caravan.negotiateCoolDownTick)));
            }
            else
            {
                DiaNode BargainNode()
                {
                    DiaNode bNode = new DiaNode("PES_RaidNeg_NegDeeper_Bargain_Intro".Translate());

                    foreach (var x in goal.BargainChoices())
                    {
                        bNode.options.Add(x);
                    }
                    bNode.options.Add(DialogUtilities.CurtOption("PES_Cancel", null, null, true));
                    return(bNode);
                }

                option.link = BargainNode();
            }
            diaNode.options.Add(option);

            //Remedy
            option = new DiaOption("PES_RaidNeg_NegDeeper_Remedy".Translate());
            if (caravan.negotiateCoolDownTick > 0)
            {
                option.Disable("PES_RaidNeg_NegCoolDown".Translate(GenDate.ToStringTicksToPeriod(caravan.negotiateCoolDownTick)));
            }
            else
            {
                DiaNode RemedyNode()
                {
                    DiaNode   rNode = new DiaNode("PES_RaidNeg_Sub_Intro".Translate());
                    DiaOption rOption;

                    if (incident.raidGoalType != RaidGoalType.Rescue)
                    {
                        rOption = new DiaOption("PES_RaidNeg_Sub_Rescue".Translate());
                        if (!RaidingGoal_Rescue.IsAvailableToIncident(incident, out failReason))
                        {
                            rOption.Disable(failReason);
                        }
                        rOption.link = RemedyDetail(() => { (new RaidingGoal_Rescue()).ApplyToIncident(incident); });
                        rNode.options.Add(rOption);
                    }

                    if (incident.raidGoalType != RaidGoalType.Extortion)
                    {
                        rOption      = new DiaOption("PES_RaidNeg_Sub_Extortion".Translate());
                        rOption.link = RemedyDetail(() => { (new RaidingGoal_Extortion()).ApplyToIncident(incident); });
                        rNode.options.Add(rOption);
                        rNode.options.Add(DialogUtilities.CurtOption("PES_Cancel", null, null, true));
                    }
                    rNode.options.Add(DialogUtilities.CurtOption("PES_Cancel", null, null, true));
                    return(rNode);
                }

                option.link = RemedyNode();
            }
            diaNode.options.Add(option);

            diaNode.options.Add(DialogUtilities.CurtOption("PES_Cancel", null, null, true));

            return(diaNode);
        }
		private bool TryParseGenDate(string sData, List<string> rgsFmt, out GenDate gdt)
		{
			GenDate.PrecisionType prec = GenDate.PrecisionType.Exact;
			if (sData[0] == '~')
			{
				prec = GenDate.PrecisionType.Approximate;
				sData = sData.Substring(1).Trim();
			}
			else if (sData[0] == '<')
			{
				prec = GenDate.PrecisionType.Before;
				sData = sData.Substring(1).Trim();
			}
			else if (sData[0] == '>')
			{
				prec = GenDate.PrecisionType.After;
				sData = sData.Substring(1).Trim();
			}
			if (sData.Length == 0)
			{
				gdt = new GenDate();
				return false;
			}
			int year = 0;
			bool fAD = true;
			DateTime dt;
			if (DateTime.TryParseExact(sData, rgsFmt.ToArray(), null, DateTimeStyles.None, out dt))
			{
				if (dt.Year > 0)
				{
					year = dt.Year;
				}
				else
				{
					year = -dt.Year;
					fAD = false;
				}
				gdt = new GenDate(prec, dt.Month, dt.Day, year, fAD);
				return true;
			}
			foreach (string sFmt in rgsFmt)
			{
				GenDateInfo gdi;
				string sResidue = ParseFormattedDate(sData, sFmt, out gdi);
				if (!gdi.error)
				{
					year = gdi.year;
					if (prec == GenDate.PrecisionType.Exact)
					{
						if (sResidue.Trim().StartsWith("?"))
							prec = GenDate.PrecisionType.Approximate;
						else
							prec = gdi.prec;
					}
					if (year < 0)
					{
						year = -year;
						fAD = false;
					}
					gdt = new GenDate(prec, gdi.ymon, gdi.mday, year, fAD);
					return true;
				}
			}
			gdt = new GenDate();
			return false;
		}
Exemple #38
0
        //Drawing
        public override void DoWindowContents(Rect inRect)
        {
            FactionFC faction = Find.World.GetComponent <FactionFC>();

            if (Find.WorldSelector.selectedTile != -1 && Find.WorldSelector.selectedTile != currentTileSelected)
            {
                currentTileSelected = Find.WorldSelector.selectedTile;
                //Log.Message("Current: " + currentTileSelected + ", Selected: " + Find.WorldSelector.selectedTile);
                currentBiomeSelected = DefDatabase <BiomeResourceDef> .GetNamed(Find.WorldGrid.tiles[currentTileSelected].biome.ToString(), false);

                //default biome
                if (currentBiomeSelected == default(BiomeResourceDef))
                {
                    //Log Modded Biome
                    currentBiomeSelected = BiomeResourceDefOf.defaultBiome;
                }
                currentHillinessSelected = DefDatabase <BiomeResourceDef> .GetNamed(Find.WorldGrid.tiles[currentTileSelected].hilliness.ToString());

                if (currentBiomeSelected.canSettle == true && currentHillinessSelected.canSettle == true && currentTileSelected != 1)
                {
                    timeToTravel = FactionColonies.ReturnTicksToArrive(Find.World.GetComponent <FactionFC>().capitalLocation, currentTileSelected);
                }
                else
                {
                    timeToTravel = 0;
                }
            }


            //grab before anchor/font
            GameFont   fontBefore   = Text.Font;
            TextAnchor anchorBefore = Text.Anchor;


            int silverToCreateSettlement = (int)(traitUtilsFC.cycleTraits(new double(), "createSettlementMultiplier", Find.World.GetComponent <FactionFC>().traits, "multiply") * (FactionColonies.silverToCreateSettlement + (500 * (Find.World.GetComponent <FactionFC>().settlements.Count() + Find.World.GetComponent <FactionFC>().settlementCaravansList.Count())) + (traitUtilsFC.cycleTraits(new double(), "createSettlementBaseCost", Find.World.GetComponent <FactionFC>().traits, "add"))));



            //Draw Label
            Text.Font   = GameFont.Medium;
            Text.Anchor = TextAnchor.MiddleCenter;
            Widgets.Label(new Rect(0, 0, 268, 40), "SettleANewColony".Translate());

            //hori line
            Widgets.DrawLineHorizontal(0, 40, 300);


            //Upper menu
            Widgets.DrawMenuSection(new Rect(5, 45, 258, 220));

            DrawLabelBox(10, 50, 100, 100, "TravelTime".Translate(), GenDate.ToStringTicksToDays(timeToTravel));
            DrawLabelBox(153, 50, 100, 100, "InitialCost".Translate(), silverToCreateSettlement + " " + "Silver".Translate());


            //Lower Menu label
            Text.Font   = GameFont.Medium;
            Text.Anchor = TextAnchor.MiddleCenter;
            Widgets.Label(new Rect(0, 270, 268, 40), "BaseProductionStats".Translate());


            //Lower menu
            Widgets.DrawMenuSection(new Rect(5, 310, 258, 220));


            //Draw production
            Text.Font   = GameFont.Small;
            Text.Anchor = TextAnchor.MiddleCenter;

            //Production headers
            Widgets.Label(new Rect(40, 310, 60, 25), "Base".Translate());
            Widgets.Label(new Rect(110, 310, 60, 25), "Modifier".Translate());
            Widgets.Label(new Rect(180, 310, 60, 25), "Final".Translate());

            if (currentTileSelected != -1)
            {
                for (int i = 0; i < Find.World.GetComponent <FactionFC>().returnNumberResource(); i++)
                {
                    int height = 15;
                    if (Widgets.ButtonImage(new Rect(20, 335 + i * (5 + height), height, height), faction.returnResourceByInt(i).getIcon()))
                    {
                        Find.WindowStack.Add(new descWindowFC("SettlementProductionOf".Translate() + ": " + faction.returnResourceByInt(i).label, char.ToUpper(faction.returnResourceByInt(i).label[0]) + faction.returnResourceByInt(i).label.Substring(1)));
                    }
                    Widgets.Label(new Rect(40, 335 + i * (5 + height), 60, height + 2), (currentBiomeSelected.BaseProductionAdditive[i] + currentHillinessSelected.BaseProductionAdditive[i]).ToString());
                    Widgets.Label(new Rect(110, 335 + i * (5 + height), 60, height + 2), (currentBiomeSelected.BaseProductionMultiplicative[i] * currentHillinessSelected.BaseProductionMultiplicative[i]).ToString());
                    Widgets.Label(new Rect(180, 335 + i * (5 + height), 60, height + 2), ((currentBiomeSelected.BaseProductionAdditive[i] + currentHillinessSelected.BaseProductionAdditive[i]) * (currentBiomeSelected.BaseProductionMultiplicative[i] * currentHillinessSelected.BaseProductionMultiplicative[i])).ToString());
                }
            }



            //Settle button
            Text.Font   = GameFont.Small;
            Text.Anchor = TextAnchor.MiddleCenter;
            int buttonLength = 130;

            if (Widgets.ButtonText(new Rect((InitialSize.x - 32 - buttonLength) / 2f, 535, buttonLength, 32), "Settle".Translate() + ": (" + silverToCreateSettlement + ")")) //add inital cost
            {                                                                                                                                                                 //if click button to settle
                if (PaymentUtil.getSilver() >= silverToCreateSettlement)                                                                                                      //if have enough monies to make new settlement
                {
                    StringBuilder reason = new StringBuilder();
                    if (!TileFinder.IsValidTileForNewSettlement(currentTileSelected, reason) || currentTileSelected == -1 || Find.World.GetComponent <FactionFC>().checkSettlementCaravansList(currentTileSelected.ToString()))
                    {
                        //Alert Error to User
                        Messages.Message(reason.ToString() ?? "CaravanOnWay".Translate() + "!", MessageTypeDefOf.NegativeEvent);
                    }
                    else
                    {   //Else if valid tile
                        PaymentUtil.paySilver(silverToCreateSettlement);
                        //if PROCESS MONEY HERE

                        //create settle event
                        FCEvent tmp = FCEventMaker.MakeEvent(FCEventDefOf.settleNewColony);
                        tmp.location        = currentTileSelected;
                        tmp.timeTillTrigger = Find.TickManager.TicksGame + timeToTravel;
                        tmp.source          = Find.World.GetComponent <FactionFC>().capitalLocation;
                        Find.World.GetComponent <FactionFC>().addEvent(tmp);

                        Find.World.GetComponent <FactionFC>().settlementCaravansList.Add(tmp.location.ToString());
                        Messages.Message("CaravanSentToLocation".Translate() + " " + GenDate.ToStringTicksToDays((tmp.timeTillTrigger - Find.TickManager.TicksGame)) + "!", MessageTypeDefOf.PositiveEvent);
                        // when event activate FactionColonies.createPlayerColonySettlement(currentTileSelected);
                    }
                }
                else
                {  //if don't have enough monies to make settlement
                    Messages.Message("NotEnoughSilverToSettle".Translate() + "!", MessageTypeDefOf.NeutralEvent);
                }
            }



            //reset anchor/font
            Text.Font   = fontBefore;
            Text.Anchor = anchorBefore;
        }
		/// <summary>
		/// Set the generic date property.
		/// </summary>
		/// <param name="hvo">The hvo.</param>
		/// <param name="tag">The tag.</param>
		/// <param name="genDate">The generic date.</param>
		public virtual void SetGenDate(int hvo, int tag, GenDate genDate)
		{
			throw new NotImplementedException();
		}
Exemple #40
0
        /// <summary>
        /// Writes a GenDate value to an attribute.
        /// </summary>
        /// <param name="writer">The writer.</param>
        /// <param name="attrName">Name of the attribute.</param>
        /// <param name="dataProperty">The GenDate.</param>
        internal static void WriteGenDateAttribute(XmlWriter writer, string attrName, GenDate dataProperty)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }
            if (string.IsNullOrEmpty(attrName))
            {
                throw new ArgumentNullException("attrName");
            }

            var genDateStr = "0";

            if (!dataProperty.IsEmpty)
            {
                genDateStr = string.Format("{0}{1:0000}{2:00}{3:00}{4}", dataProperty.IsAD ? "" : "-", dataProperty.Year,
                                           dataProperty.Month, dataProperty.Day, (int)dataProperty.Precision);
            }
            writer.WriteAttributeString(attrName, genDateStr);
        }
		public void set_GenDatePropTest()
		{
			var person2 = Cache.LanguageProject.PeopleOA.PossibilitiesOS[1] as ICmPerson;
			var genDate = new GenDate(GenDate.PrecisionType.Exact, 0, 0, 300, false);
			m_sda.SetGenDate(person2.Hvo, CmPersonTags.kflidDateOfBirth, genDate);
			Assert.AreEqual(genDate, person2.DateOfBirth);
		}
        public override void Init()
        {
            base.Init();
            //Make sure the election occurs during the day if possible.
            int plannedStart = GenDate.HourOfDay(this.Duration + Find.TickManager.TicksAbs, Find.WorldGrid.LongLatOf(this.SingleMap.Tile).x);

            if (plannedStart < 7)
            {
                this.Duration += (7 - plannedStart) * GenDate.TicksPerHour;
            }
            else if (plannedStart > 18)
            {
                this.Duration -= (plannedStart - 18) * GenDate.TicksPerHour;
            }
            IEnumerable <Pawn> psychologyColonists = (from p in this.SingleMap.mapPawns.FreeColonistsSpawned
                                                      where PsycheHelper.PsychologyEnabled(p)
                                                      select p);
            int   maxCandidatesThisColonySupports = Mathf.RoundToInt(psychologyColonists.Count() * 0.3f);
            float totalOutspoken = 0f;

            foreach (Pawn p in psychologyColonists)
            {
                totalOutspoken += PsycheHelper.Comp(p).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Outspoken);
            }
            int numCandidates = Rand.RangeInclusive(Mathf.Min(maxCandidatesThisColonySupports, 1 + Mathf.RoundToInt(totalOutspoken * 0.1f)), maxCandidatesThisColonySupports);
            int tries         = 0;

            while (this.candidates.Count < numCandidates && tries < 500)
            {
                Pawn candidate = psychologyColonists.RandomElementByWeight(p => (p.ageTracker.CurLifeStageIndex >= 3) ? PsycheHelper.Comp(p).Psyche.GetPersonalityRating(PersonalityNodeDefOf.Outspoken) * 2 + (p.health.hediffSet.HasHediff(HediffDefOfPsychology.Mayor) ? p.needs.mood.CurLevel - 0.5f : 0f) : 0f);
                List <PersonalityNodeDef> issues = new List <PersonalityNodeDef>();
                int tries2 = 0;
                while (issues.Count < 5 && tries2 < 500)
                {
                    PersonalityNodeDef issue = (from node in PsycheHelper.Comp(candidate).Psyche.PersonalityNodes
                                                where !node.Core
                                                select node.def).RandomElementByWeight(n => Mathf.Pow(Mathf.Abs(0.5f - PsycheHelper.Comp(candidate).Psyche.GetPersonalityRating(n)), 4) * Mathf.Pow(2, n.controversiality));
                    if (!issues.Contains(issue))
                    {
                        issues.Add(issue);
                    }
                    else
                    {
                        tries2++;
                    }
                }
                if (issues.Count >= 5 && this.candidates.Find(c => c.pawn == candidate) == null)
                {
                    this.candidates.Add(new Candidate(candidate, issues));
                }
                else
                {
                    if (issues.Count < 5)
                    {
                        Log.Error("[Psychology] Could not find five unique issues for " + candidate.LabelShort + "'s platform.");
                    }
                    tries++;
                }
            }
            if (candidates.Count == 0)
            {
                this.End();
                Log.Error("[Psychology] Tried to start election but could not find anyone to run.");
                return;
            }
            foreach (Candidate candidate in candidates)
            {
                StringBuilder issuesString = new StringBuilder();
                for (int i = 0; i < candidate.nodes.Count; i++)
                {
                    issuesString.AppendFormat("{0}) {1}{2}", i + 1, PsycheHelper.Comp(candidate.pawn).Psyche.GetPersonalityNodeOfDef(candidate.nodes[i]).PlatformIssue, (i != candidate.nodes.Count - 1 ? "\n" : ""));
                }
                Find.LetterStack.ReceiveLetter("LetterLabelElectionCandidate".Translate(candidate.pawn), "LetterElectionCandidate".Translate(candidate.pawn, Find.WorldObjects.ObjectsAt(candidate.pawn.Map.Tile).OfType <SettlementBase>().First().Label, issuesString.ToString()), LetterDefOf.NeutralEvent, candidate.pawn, null);
            }
        }
		public void kcptGenDateTests()
		{
			var firstPerson = (ICmPerson)Cache.LanguageProject.PeopleOA.PossibilitiesOS[0];
			var startValue = firstPerson.DateOfBirth;
			var newValue = new GenDate(GenDate.PrecisionType.Before, 1, 1, 3000, true);
			using (var undoHelper = new UndoableUnitOfWorkHelper(m_actionHandler, "set DOB"))
			{
				firstPerson.DateOfBirth = newValue;
				undoHelper.RollBack = false;
			}

			Assert.AreEqual(UndoResult.kuresSuccess, m_actionHandler.Undo());
			Assert.AreEqual(startValue, firstPerson.DateOfBirth, "Wrong starting DOB");
			Assert.AreEqual(UndoResult.kuresSuccess, m_actionHandler.Redo());
			Assert.AreEqual(newValue, firstPerson.DateOfBirth, "Wrong undone DOB");
		}
		public void kcptGenDateTests()
		{
			var firstPerson = (ICmPerson)Cache.LanguageProject.PeopleOA.PossibilitiesOS[0];
			var startValue = firstPerson.DateOfBirth;
			var newValue = new GenDate(GenDate.PrecisionType.Before, 1, 1, 3000, true);
			firstPerson.DateOfBirth = newValue;
			Assert.AreEqual(newValue, firstPerson.DateOfBirth);
			// Reset it to original value.
			firstPerson.DateOfBirth = startValue;
			Assert.AreEqual(startValue, firstPerson.DateOfBirth);
		}