예제 #1
0
	public void Initialize(Path path, float min, float max) {
		this.path = path;
		xRange = new FloatRange(min, max);
		CalculateDists();
		CalculatePoints();
		initialized = true;
	}
예제 #2
0
    public KittySet()
    {
        hp = 70;
        souls = 20;

        idleTime = new FloatRange(1f, 2f);

        KittyThrust.actDuration = SkillSetting.frameToSeconds(7, 12);
        KittyThrust.cd = 5f;
        KittyThrust.damage = 2f;
        KittyThrust.range = 1.4f;
        KittyThrust.attackDuration = 0.2f;
        KittyThrust.freezenTime = 0.8f;
        KittyThrust.targetForce = new Vector2(500, 0);

        enrageTrigger = hp * 0.7f;
        KittyEnrage.actDuration = 1f;
        KittyEnrage.cd = 2000f;
        KittyEnrage.damage = 0f;
        KittyEnrage.range = 5f;
        KittyEnrage.targetForce = new Vector2(100, 0);

        SummonWolf.actDuration = SkillSetting.frameToSeconds(7, 12);
        SummonWolf.cd = 18f;
        SummonWolf.damage = 3f;
        SummonWolf.range = 10f;
        SummonWolf.attackDuration = 0f;
        SummonWolf.freezenTime = 0.3f;

        Leap.actDuration = SkillSetting.frameToSeconds(13, 24);
        Leap.cd = 2f;
        Leap.range = 2f;
        LeapAngle = 45f;
        idleProAfterLeap = 0.7f;

        slash.actDuration = SkillSetting.frameToSeconds(41, 40);
        slash.cd = 7f;
        slash.damage = 1.5f;
        slash.range = 1.3f;
        slash.freezenTime = 0.5f;
        slash.attackDuration = 0.2f;
        slashMoveDist = 2.5f;
        slash.targetForce = new Vector2(300f, 0);

        shadowAttack.actDuration = float.PositiveInfinity;
        shadowAttack.damage = 5f;
        shadowAttack.cd = 25f;
        shadowAttack.freezenTime = 1f;
        shadowAttack.attackDuration = 0;
        shadowAttack.targetForce = new Vector2(400f, 0);

        shadowFadeOutTime = 1f;
        shadowFadeInTime = 1f;
        shadowSilenceTime = new FloatRange(1, 3);
        shadowAttackTimes = new IntRange(2, 4);
        shadowAttackFadeOutTime = 0.3f;
        shadowPosition = new Vector2(6, 4);
        shadowAttackSpeed = 18f;
        idleTimeAfterShadow = new FloatRange(4, 6);
    }
예제 #3
0
 /// <summary>
 /// Creates a VersionRange with the given min and max.
 /// </summary>
 /// <param name="minVersion">Lower bound of the version range.</param>
 /// <param name="includeMinVersion">True if minVersion satisfies the condition.</param>
 /// <param name="maxVersion">Upper bound of the version range.</param>
 /// <param name="includeMaxVersion">True if maxVersion satisfies the condition.</param>
 /// <param name="includePrerelease">True if prerelease versions should satisfy the condition.</param>
 /// <param name="floatRange">The floating range subset used to find the best version match.</param>
 /// <param name="originalString">The original string being parsed to this object.</param>
 public VersionRange(NuGetVersion minVersion = null, bool includeMinVersion = true, NuGetVersion maxVersion = null,
     bool includeMaxVersion = false, bool? includePrerelease = null, FloatRange floatRange = null, string originalString = null)
     : base(minVersion, includeMinVersion, maxVersion, includeMaxVersion, includePrerelease)
 {
     _floatRange = floatRange;
     _originalString = originalString;
 }
예제 #4
0
	protected override void OnPatternAdded(FloatRange distRange) {
		if (UnityEngine.Random.value > probability) return;

		float distPercent = UnityEngine.Random.Range(0.05f, 0.95f);
		float dist = distRange.Lerp(distPercent);
		float verticalPercent = UnityEngine.Random.Range(0.1f, 0.9f);
		GenerateItem(dist, verticalPercent);
	}
예제 #5
0
	private void CalculateDists() {
		distRangeBottom = new FloatRange();
		distRangeBottom.min = path.bottomContour.GetDistAtX(xRange.min);
		distRangeBottom.max = path.bottomContour.GetDistAtX(xRange.max);

		distRangeTop = new FloatRange();
		distRangeTop.min = path.topContour.GetDistAtX(xRange.min);
		distRangeTop.max = path.topContour.GetDistAtX(xRange.max);
	}
        /// <summary>
        ///     Spawns the setup.
        /// </summary>
        public override void SpawnSetup()
        {
            base.SpawnSetup();

            // Get base trap damage.
            _baseDamageStat = this.GetStatValue(StatDefOf.TrapMeleeDamage);

            // Get base damage range.
            _damageRange = new FloatRange(_baseDamageStat - damageVariation, _baseDamageStat + damageVariation);
        }
예제 #7
0
	//handle progression of entity, attributes, and resources
    public void Awake() {
        attr = new FloatRange(0);
        attr.SetModifier("Mod1", FloatModifier.Value(1));
        attr.SetModifier("Mod2", FloatModifier.Value(3));
        attr.SetModifier("Mod3", FloatModifier.Value(6));
        attr2 = new FloatRange(0);
        attr2.SetModifier("Mod1", FloatModifier.Value(5));
        attr2.SetModifier("Mod2", FloatModifier.Percent(0.2f));
        attr2.SetModifier("Mod3", FloatModifier.Value(5));

        resourceManager = new ResourceManager(this);
        statusManager = new StatusEffectManager(this);
        abilityManager = new AbilityManager(this);
		emitter = new EventEmitter();
        EntityManager.Instance.Register(this);
        //gameObject.layer = LayerMask.NameToLayer("Entity");
    }
예제 #8
0
    public WaspSet()
    {
        hpBarOffset = new Vector2(0, 1.5f);
        hp = 3;
        moveSpeed = 5f;
        souls = 4;
        highFartingTime = new FloatRange(1, 3);
        lowFartingTime = new FloatRange(2, 4);
        refLowHeight = 1.5f;
        fartingRadius = 1f;

        attack.actDuration = float.PositiveInfinity;
        attack.cd = 6f;
        attack.damage = 1.5f;
        attack.range = 3f;
        attack.attackDuration = 0;
        attackMoveSpeed = 13f;

        high.actDuration = 0.2f;
        high.cd = 1f;
        low.actDuration = 0.2f;
        low.cd = 1f;
    }
예제 #9
0
        /// <summary>
        /// Produces a secondary explosion on impact using the explosion values from the projectile's projectile def. Requires the projectile's launcher to be passed on due to protection level.
        /// Intended use is for HEAT and similar weapons that spawn secondary explosions while also penetrating, NOT explosive ammo of anti-materiel rifles as the explosion just spawns
        /// on top of the pawn, not inside the hit body part.
        ///
        /// Additionally handles fragmentation effects if defined.
        /// </summary>
        /// <param name="instigator">Launcher of the projectile calling the method</param>
        public virtual void Explode(Thing instigator, Vector3 pos, Map map, float scaleFactor = 1)
        {
            var posIV = pos.ToIntVec3();

            if (map == null)
            {
                Log.Warning("Tried to do explodeCE in a null map.");
                return;
            }
            if (!posIV.InBounds(map))
            {
                Log.Warning("Tried to explodeCE out of bounds");
                return;
            }

            // Fragmentation stuff
            if (!Props.fragments.NullOrEmpty() && GenGrid.InBounds(posIV, map))
            {
                float   edificeHeight = (new CollisionVertical(posIV.GetEdifice(map))).Max;
                Vector2 exactOrigin   = new Vector2(pos.x, pos.z);
                float   height;

                //Fragments fly from a 0 to 45 degree angle away from the explosion
                var range = new FloatRange(0, Mathf.PI / 8f);

                var projCE = parent as ProjectileCE;

                if (projCE != null)
                {
                    height = Mathf.Max(edificeHeight, pos.y);
                    if (edificeHeight < height)
                    {
                        //If the projectile exploded above the ground, they can fly 45 degree away at the bottom as well
                        range.min = -Mathf.PI / 8f;
                    }
                    // TODO : Check for hitting the bottom or top of a roof
                }
                else
                {
                    height = edificeHeight;
                }

                foreach (ThingCountClass fragment in Props.fragments)
                {
                    for (int i = 0; i < fragment.count; i++)
                    {
                        ProjectileCE projectile = (ProjectileCE)ThingMaker.MakeThing(fragment.thingDef, null);
                        GenSpawn.Spawn(projectile, posIV, map);

                        projectile.canTargetSelf   = true;
                        projectile.minCollisionSqr = 1f;
                        //TODO : Don't hardcode at FragmentShadowChance, make XML-modifiable
                        projectile.castShadow = (UnityEngine.Random.value < FragmentShadowChance);
                        projectile.Launch(instigator, exactOrigin, range.RandomInRange, UnityEngine.Random.Range(0, 360), height, Props.fragSpeedFactor * projectile.def.projectile.speed);
                    }
                }
            }
            // Regular explosion stuff
            if (Props.explosionRadius > 0 && Props.explosionDamage > 0 && parent.def != null && GenGrid.InBounds(posIV, map))
            {
                // Can't use GenExplosion because it no longer allows setting damage amount

                // Copy-paste from GenExplosion
                Explosion explosion = new Explosion();
                explosion.position   = posIV;
                explosion.radius     = Props.explosionRadius * scaleFactor;
                explosion.damType    = Props.explosionDamageDef;
                explosion.instigator = instigator;
                explosion.damAmount  = GenMath.RoundRandom(Props.explosionDamage * scaleFactor);
                explosion.weaponGear = null;
                explosion.preExplosionSpawnThingDef            = Props.preExplosionSpawnThingDef;
                explosion.preExplosionSpawnChance              = Props.explosionSpawnChance;
                explosion.preExplosionSpawnThingCount          = Props.preExplosionSpawnThingCount;
                explosion.postExplosionSpawnThingDef           = Props.postExplosionSpawnThingDef;
                explosion.postExplosionSpawnChance             = Props.postExplosionSpawnChance;
                explosion.postExplosionSpawnThingCount         = Props.postExplosionSpawnThingCount;
                explosion.applyDamageToExplosionCellsNeighbors = Props.applyDamageToExplosionCellsNeighbors;
                map.GetComponent <ExplosionManager>().StartExplosion(explosion, Props.soundExplode ?? Props.explosionDamageDef.soundExplosion);
            }
        }
예제 #10
0
        public override StateGraph CreateGraph()
        {
            StateGraph stateGraph = new StateGraph();
            LordToil   lordToil   = null;

            if (this.sappers)
            {
                lordToil = new LordToil_AssaultColonySappers();
                if (this.useAvoidGridSmart)
                {
                    lordToil.useAvoidGrid = true;
                }
                stateGraph.AddToil(lordToil);
                Transition transition = new Transition(lordToil, lordToil, true, true);
                transition.AddTrigger(new Trigger_PawnLost());
                stateGraph.AddTransition(transition, false);
                Transition transition2 = new Transition(lordToil, lordToil, true, false);
                transition2.AddTrigger(new Trigger_PawnHarmed(1f, false, null));
                transition2.AddPostAction(new TransitionAction_CheckForJobOverride());
                stateGraph.AddTransition(transition2, false);
            }
            LordToil lordToil2 = new LordToil_AssaultColony(false);

            if (this.useAvoidGridSmart)
            {
                lordToil2.useAvoidGrid = true;
            }
            stateGraph.AddToil(lordToil2);
            LordToil_ExitMap lordToil_ExitMap = new LordToil_ExitMap(LocomotionUrgency.Jog, false);

            lordToil_ExitMap.useAvoidGrid = true;
            stateGraph.AddToil(lordToil_ExitMap);
            if (this.sappers)
            {
                Transition transition3 = new Transition(lordToil, lordToil2, false, true);
                transition3.AddTrigger(new Trigger_NoFightingSappers());
                stateGraph.AddTransition(transition3, false);
            }
            if (this.assaulterFaction.def.humanlikeFaction)
            {
                if (this.canTimeoutOrFlee)
                {
                    Transition transition4 = new Transition(lordToil2, lordToil_ExitMap, false, true);
                    if (lordToil != null)
                    {
                        transition4.AddSource(lordToil);
                    }
                    transition4.AddTrigger(new Trigger_TicksPassed((!this.sappers) ? LordJob_AssaultColony.AssaultTimeBeforeGiveUp.RandomInRange : LordJob_AssaultColony.SapTimeBeforeGiveUp.RandomInRange));
                    transition4.AddPreAction(new TransitionAction_Message("MessageRaidersGivenUpLeaving".Translate(this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), this.assaulterFaction.Name), null, 1f));
                    stateGraph.AddTransition(transition4, false);
                    Transition transition5 = new Transition(lordToil2, lordToil_ExitMap, false, true);
                    if (lordToil != null)
                    {
                        transition5.AddSource(lordToil);
                    }
                    FloatRange floatRange    = new FloatRange(0.25f, 0.35f);
                    float      randomInRange = floatRange.RandomInRange;
                    transition5.AddTrigger(new Trigger_FractionColonyDamageTaken(randomInRange, 900f));
                    transition5.AddPreAction(new TransitionAction_Message("MessageRaidersSatisfiedLeaving".Translate(this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), this.assaulterFaction.Name), null, 1f));
                    stateGraph.AddTransition(transition5, false);
                }
                if (this.canKidnap)
                {
                    LordToil   startingToil = stateGraph.AttachSubgraph(new LordJob_Kidnap().CreateGraph()).StartingToil;
                    Transition transition6  = new Transition(lordToil2, startingToil, false, true);
                    if (lordToil != null)
                    {
                        transition6.AddSource(lordToil);
                    }
                    transition6.AddPreAction(new TransitionAction_Message("MessageRaidersKidnapping".Translate(this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), this.assaulterFaction.Name), null, 1f));
                    transition6.AddTrigger(new Trigger_KidnapVictimPresent());
                    stateGraph.AddTransition(transition6, false);
                }
                if (this.canSteal)
                {
                    LordToil   startingToil2 = stateGraph.AttachSubgraph(new LordJob_Steal().CreateGraph()).StartingToil;
                    Transition transition7   = new Transition(lordToil2, startingToil2, false, true);
                    if (lordToil != null)
                    {
                        transition7.AddSource(lordToil);
                    }
                    transition7.AddPreAction(new TransitionAction_Message("MessageRaidersStealing".Translate(this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), this.assaulterFaction.Name), null, 1f));
                    transition7.AddTrigger(new Trigger_HighValueThingsAround());
                    stateGraph.AddTransition(transition7, false);
                }
            }
            Transition transition8 = new Transition(lordToil2, lordToil_ExitMap, false, true);

            if (lordToil != null)
            {
                transition8.AddSource(lordToil);
            }
            transition8.AddTrigger(new Trigger_BecameNonHostileToPlayer());
            transition8.AddPreAction(new TransitionAction_Message("MessageRaidersLeaving".Translate(this.assaulterFaction.def.pawnsPlural.CapitalizeFirst(), this.assaulterFaction.Name), null, 1f));
            stateGraph.AddTransition(transition8, false);
            return(stateGraph);
        }
예제 #11
0
        public static bool Prefix()
        {
            int num = 0;
            int actualFactionCount = 0;

            Controller.factionCenters.Clear();

            foreach (CustomFaction cf in Main.CustomFactions)
            {
                cf.FactionDef.requiredCountAtGameStart = (int)cf.RequiredCount;
                if (cf.RequiredCount == 0)
                {
                    cf.FactionDef.maxCountAtGameStart = 0;
                }
                else
                {
                    cf.FactionDef.maxCountAtGameStart = (int)cf.MaxCountAtStart;
                }
            }

            foreach (FactionDef def in DefDatabase <FactionDef> .AllDefs)
            {
                if (def.isPlayer)
                {
                    continue;
                }

                switch (def.defName)
                {
                case "OutlanderCivil":
                    SetFactionCount(def, (int)Controller_FactionOptions.Settings.outlanderCivilMin);
                    break;

                case "OutlanderRough":
                    SetFactionCount(def, (int)Controller_FactionOptions.Settings.outlanderHostileMin);
                    break;

                case "TribeCivil":
                    SetFactionCount(def, (int)Controller_FactionOptions.Settings.tribalCivilMin);
                    break;

                case "TribeRough":
                    SetFactionCount(def, (int)Controller_FactionOptions.Settings.tribalHostileMin);
                    break;

                case "TribeSavage":
                    SetFactionCount(def, (int)Controller_FactionOptions.Settings.tribalSavageMin);
                    break;

                case "Empire":
                    SetFactionCount(def, (int)Controller_FactionOptions.Settings.empireMin);
                    break;

                case "Pirate":
                    SetFactionCount(def, (int)Controller_FactionOptions.Settings.pirateMin);
                    break;
                }

                actualFactionCount += def.requiredCountAtGameStart;
                for (int i = 0; i < def.requiredCountAtGameStart; i++)
                {
                    Faction faction = FactionGenerator.NewGeneratedFaction(def);
                    Find.FactionManager.Add(faction);
                    if (!def.hidden)
                    {
                        num++;
                    }
                }
            }

            if (Controller_FactionOptions.Settings.MinFactionCount == 0 &&
                Main.CustomFactions.Count == 0)
            {
                /*Log.Error("Faction Control: No factions were selected. To prevent the game from going into an infinite loop a tribe was added.");
                 * FactionDef def = DefDatabase<FactionDef>.GetNamed("TribeCivil");
                 * def.requiredCountAtGameStart = 1;
                 * Controller.maxFactionSprawl = 1;
                 * Faction faction = FactionGenerator.NewGeneratedFaction(def);
                 * Find.FactionManager.Add(faction);
                 * actualFactionCount = 1;*/
                return(false);
            }

            double sqrtTiles        = Math.Sqrt(Find.WorldGrid.TilesCount);
            double sqrtFactionCount = Math.Sqrt(actualFactionCount);

            Controller.minFactionSeparation = sqrtTiles / (sqrtFactionCount * 2);
            Controller.maxFactionSprawl     = sqrtTiles / (sqrtFactionCount * Controller.Settings.factionGrouping);
            Controller.pirateSprawl         = Controller.maxFactionSprawl;
            if (Controller.Settings.spreadPirates)
            {
                Controller.pirateSprawl = sqrtTiles / (sqrtFactionCount * 0.5f);
            }

            while (num < (int)Controller_FactionOptions.Settings.factionCount)
            {
                FactionDef facDef = (from fa in DefDatabase <FactionDef> .AllDefs
                                     where fa.canMakeRandomly && Find.FactionManager.AllFactions.Count((Faction f) => f.def == fa) < fa.maxCountAtGameStart
                                     select fa).RandomElement <FactionDef>();
                Faction faction2 = FactionGenerator.NewGeneratedFaction(facDef);
                Find.World.factionManager.Add(faction2);
                num++;
            }
            float      tilesCount = (float)Find.WorldGrid.TilesCount / 100000f;
            float      minBP100K  = 75f * Controller.Settings.factionDensity;
            float      maxBP100K  = 85f * Controller.Settings.factionDensity;
            FloatRange factionBasesPer100kTiles = new FloatRange(minBP100K, maxBP100K);
            int        maxCount = 0;
            int        count    = GenMath.RoundRandom(tilesCount * factionBasesPer100kTiles.RandomInRange);

            count -= Find.WorldObjects.SettlementBases.Count;
            for (int j = 0; j < count && maxCount < 2000; j++)
            {
                Faction faction2 = (
                    from x in Find.World.factionManager.AllFactionsListForReading
                    where !x.def.isPlayer && !x.def.hidden
                    select x).RandomElementByWeight <Faction>((Faction x) => x.def.settlementGenerationWeight);
                Settlement factionBase = (Settlement)WorldObjectMaker.MakeWorldObject(WorldObjectDefOf.Settlement);
                factionBase.SetFaction(faction2);
                factionBase.Tile = TileFinder.RandomSettlementTileFor(faction2, false, null);
                if (factionBase.Tile < 1)
                {
                    j--;
                }
                else
                {
                    factionBase.Name = SettlementNameGenerator.GenerateSettlementName(factionBase);
                    Find.WorldObjects.Add(factionBase);
                }
                ++maxCount;
            }
            return(false);
        }
예제 #12
0
        public static void GiveVitaeEffects(Pawn receiver, Pawn donor)
        {
            var pawn = receiver;

            //Give Vitae High Effect
            Hediff vitaeHighHediff = HediffMaker.MakeHediff(VampDefOf.ROMV_VitaeHigh, pawn, null);
            float  numHigh         = 0.75f;

            AddictionUtility.ModifyChemicalEffectForToleranceAndBodySize(pawn, VampDefOf.ROMV_VitaeChemical, ref numHigh);
            vitaeHighHediff.Severity = numHigh;
            pawn.health.AddHediff(vitaeHighHediff, null, null);

            //Give Vitae Tolerance Effect
            Hediff vitaeToleranceHediff = HediffMaker.MakeHediff(VampDefOf.ROMV_VitaeTolerance, pawn, null);
            float  numTol = 0.035f;

            numTol /= receiver.BodySize;
            AddictionUtility.ModifyChemicalEffectForToleranceAndBodySize(pawn, VampDefOf.ROMV_VitaeChemical, ref numTol);
            vitaeToleranceHediff.Severity = numTol;
            pawn.health.AddHediff(vitaeToleranceHediff, null, null);

            const float addictiveness                   = 1.0f;
            const float minToleranceToAddict            = 0.01f;
            const float existingAddictionSeverityOffset = 0.2f;

            var needLevelOffset        = 1f;
            var overdoseSeverityOffset = new FloatRange(0.18f, 0.35f);
            var chemical = VampDefOf.ROMV_VitaeChemical;

            var addictionHediffDef = VampDefOf.ROMV_VitaeAddiction;
            var lookTarget         = receiver;
            var hediff             = AddictionUtility.FindToleranceHediff(lookTarget, VampDefOf.ROMV_VitaeChemical);
            var num             = hediff?.Severity ?? 0f;
            var hediffAddiction = AddictionUtility.FindAddictionHediff(lookTarget, VampDefOf.ROMV_VitaeChemical);

            if (hediffAddiction != null)
            {
                hediffAddiction.Severity += existingAddictionSeverityOffset;
            }
            else if (Rand.Value < addictiveness && num >= minToleranceToAddict)
            {
                lookTarget.health.AddHediff(addictionHediffDef, null, null);
                if (PawnUtility.ShouldSendNotificationAbout(lookTarget))
                {
                    Find.LetterStack.ReceiveLetter("LetterLabelNewlyAddicted".Translate(chemical.label).CapitalizeFirst(),
                                                   "LetterNewlyAddicted".Translate(lookTarget.LabelShort, chemical.label, lookTarget.Named("PAWN"))
                                                   .AdjustedFor(lookTarget, "PAWN").CapitalizeFirst(), LetterDefOf.NegativeEvent, lookTarget, null, null);
                }
                AddictionUtility.CheckDrugAddictionTeachOpportunity(lookTarget);
            }

            if (addictionHediffDef.causesNeed != null)
            {
                var need = lookTarget.needs.AllNeeds.Find((Need x) => x.def == addictionHediffDef.causesNeed);
                if (need != null)
                {
                    AddictionUtility.ModifyChemicalEffectForToleranceAndBodySize(lookTarget, chemical,
                                                                                 ref needLevelOffset);
                    need.CurLevel += needLevelOffset;
                }
            }
//            var firstHediffOfDef = lookTarget.health.hediffSet.GetFirstHediffOfDef(HediffDefOf.DrugOverdose, false);
//            var num2 = firstHediffOfDef?.Severity ?? 0f;
//            if (num2 < 0.9f && Rand.Value < largeOverdoseChance)
//            {
//                var num3 = Rand.Range(0.85f, 0.99f);
//                HealthUtility.AdjustSeverity(lookTarget, HediffDefOf.DrugOverdose, num3 - num2);
//                if (lookTarget.Faction == Faction.OfPlayer)
//                {
//                    Messages.Message("MessageAccidentalOverdose".Translate(new object[]
//                    {
//                        lookTarget.LabelIndefinite(),
//                        chemical.LabelCap
//                    }).CapitalizeFirst(), MessageTypeDefOf.NegativeHealthEvent);
//                }
//            }
//            else
//            {
//                var num4 = overdoseSeverityOffset.RandomInRange / lookTarget.BodySize;
//                if (num4 > 0f)
//                {
//                    HealthUtility.AdjustSeverity(lookTarget, HediffDefOf.DrugOverdose, num4);
//                }
//            }
        }
        /// <summary>
        ///     Spawns the setup.
        /// </summary>
        public override void SpawnSetup()
        {
            base.SpawnSetup();

            if (_trapTriggerCells == null || _trapTriggerCells.Count == 0)
            {
                _trapTriggerCells = CalculateTriggerCells(Position, Rotation).ToList();

                // Spawn triggers to handle pathing.
                SpawnTrapTriggers();
            }

            // Get base trap damage.
            _baseDamageStat = this.GetStatValue(StatDefOf.TrapMeleeDamage);

            // Get base damage range.
            _damageRange = new FloatRange(_baseDamageStat - DamageVariation, _baseDamageStat + DamageVariation);
        }
예제 #14
0
    public static float Lerp(float val_t, FloatRange t, FloatRange r, AnimationCurve curve)
    {
        float p = (val_t - t.min) / (t.max - t.min);

        return(r.min + (r.max - r.min) * curve.Evaluate(p));
    }
예제 #15
0
 /// <summary>
 /// Sets the positive bounds from a given Vector2.
 /// </summary>
 /// <param name="positiveBounds">The new positive bounds.</param>
 public virtual void SetPositiveBounds(Vector2 positiveBounds)
 {
     this.positiveBounds = new FloatRange(positiveBounds);
 }
 public void UpdateTemperatureIfNecessary( bool force = false )
 {
     if ( Find.TickManager.TicksGame - _lastTempUpdate > 1900 || force )
     {
         // get desired temperatures
         if ( !targetTemperaturesOverride )
         {
             _targetTemperatures = new FloatRange( Math.Max( GenTemperature.SeasonalTemp - 10f, ApparelStatsHelper.MinMaxTemperatureRange.min),
                                                   Math.Min( GenTemperature.SeasonalTemp + 10f, ApparelStatsHelper.MinMaxTemperatureRange.max) );
         }
         _temperatureWeight = GenTemperature.SeasonAcceptableFor( _pawn.def ) ? 1f : 5f;
     }
 }
예제 #17
0
 protected override float CalculateValue(DriveAxis.Axis driveAxis, FloatRange limits)
 {
     return(Mathf.Clamp(currentPseudoRotation, limits.minimum, limits.maximum));
 }
예제 #18
0
 /// <summary>
 /// Sets the positive bounds.
 /// </summary>
 /// <param name="positiveBounds">The new positive bounds.</param>
 public virtual void SetPositiveBounds(FloatRange positiveBounds)
 {
     this.positiveBounds = new FloatRange(positiveBounds.minimum, positiveBounds.maximum);
 }
        public static Toil DoWeaponRepairWork(int duration, string soundDefName, float maxAllowedRepair)
        {
            float expPerSecond = 25f;

            FloatRange gainHitpointRange = new FloatRange(0.6f, 0.95f);  // Note: result = gainHitpointRange * skillRecord.Level / 12
            SkillDef   skillDef          = SkillDefOf.Crafting;
            int        maxSkillLevel     = 12;

            Toil toil = new Toil();

            //toil.initAction = delegate
            //{

            //};
            toil.tickAction = delegate
            {
                Pawn        actor       = toil.actor;
                Job         curJob      = actor.jobs.curJob;
                SkillRecord skillRecord = actor.skills.GetSkill(skillDef);

                // actor learns something
                actor.skills.Learn(SkillDefOf.Crafting, expPerSecond / 60);
            };

            toil.AddFinishAction(delegate
            {
                Pawn actor = toil.actor;
                Job curJob = actor.jobs.curJob;

                // Calculate possible hitpoint gain multiplicator
                SkillRecord skillRecord = actor.skills.GetSkill(skillDef);
                float gainHitpointMulti = gainHitpointRange.RandomInRange * Mathf.Clamp(skillRecord.Level, 1, maxSkillLevel) / maxSkillLevel;  //20;

                // Get the target hitpoint to use
                Thing master            = curJob.GetTarget(WeaponMasterIndex).Thing;
                int hitpointsMasterMax  = master.MaxHitPoints;
                int hitpointsMaster     = master.HitPoints;
                Thing ingredient        = curJob.GetTarget(WeaponIngredientIndex).Thing;
                int hitpointsIngredient = ingredient.HitPoints;

                // Hitpoints will only be increased to XX% of the ingredient hitpoints
                int newHitpoints = hitpointsMaster + (int)(hitpointsIngredient * gainHitpointMulti);

                if (newHitpoints > hitpointsMasterMax * maxAllowedRepair)
                {
                    newHitpoints = (int)(hitpointsMasterMax * maxAllowedRepair) + 1;
                }

                // repair master
                master.HitPoints = newHitpoints;
                // vanish ingredient
                ingredient.Destroy(DestroyMode.Vanish);
            });

            toil.handlingFacing      = true;
            toil.defaultCompleteMode = ToilCompleteMode.Delay;
            toil.defaultDuration     = duration;
            toil.WithProgressBarToilDelay(WorkbenchIndex, false, -0.5f);
            //toil.WithEffect(() => toil.actor.CurJob.bill.recipe.effectWorking, WorkbenchIndex);
            toil.PlaySustainerOrSound(() => SoundDef.Named(soundDefName));

            return(toil);
        }
예제 #20
0
 public ScattererValues(FloatRange fr)
 {
     this.CountPer10kCellsRange = new FloatRange(fr.min, fr.max);
 }
예제 #21
0
        internal Scale(GameObject inGameObject, float inTargetScale, bool inIsRelative)
        {
            Transform t = GetComponent(inGameObject);

            _range = new FloatRange(t.Scale, inIsRelative ? t.Scale * inTargetScale : inTargetScale);
        }
예제 #22
0
 /// <summary>
 /// Check if the specified range overlaps with the range.
 /// </summary>
 /// 
 /// <param name="range">Range to check for overlapping.</param>
 /// 
 /// <returns><b>True</b> if the specified range overlaps with the range or
 /// <b>false</b> otherwise.</returns>
 /// 
 public bool IsOverlapping(FloatRange range)
 {
     return ((IsInside(range.min)) || (IsInside(range.max)));
 }
예제 #23
0
    //todo this might also be responsible for cast time / channel time / tick time

    public Charge()
    {
        cooldown = new FloatRange();
        lastUsed = -1;
    }
예제 #24
0
	private void GenerateCoinPattern(FloatRange distRange) {
		CoinCluster coinPattern = GenerateItem<CoinCluster>(distRange.GetRandom(), 0.2f);
		coinPattern.Initialize(GetCoinPatternData());
	}
예제 #25
0
 static public Vector2 GetInArc(Vector2 center, FloatRange angle, FloatRange radius)
 {
     return(SOURCE.GetInArc(center, angle, radius));
 }
예제 #26
0
파일: Range.cs 프로젝트: Zylann/GGJ14
 public void CopyFrom(FloatRange other)
 {
     min = other.min;
     max = other.max;
 }
예제 #27
0
 static public Vector2 GetInCircle(Vector2 center, FloatRange radius)
 {
     return(SOURCE.GetInCircle(center, radius));
 }
예제 #28
0
	/// <summary>
	/// Decreases the health from the enemy.
	/// </summary>
	/// <returns>The health.</returns>
	/// <param name="damage">Damage.</param>
	public void DecreaseHealth(float damage)
	{
		GameObject damagelabel = Resources.Load("DamageLabel") as GameObject;
		damagelabel.GetComponent<DamageLabel>().Text = "" + damage;
		MonoBehaviour.Instantiate(damagelabel.gameObject,
		                          new Vector3(this.transform.position.x, this.transform.position.y, -2),
									Quaternion.identity);
		
		float criticalHitRate = new FloatRange(0, 100).Random;
		bool criticalHit = (!(criticalHitRate % 2).Equals(0) && criticalHitRate > 30 && criticalHitRate < 50) ? true : false;

		if (criticalHit)
			Health.Value -= damage * 1.5f;
		else
			Health.Value -= damage;


		if (criticalHit)
		{
			if (GameObject.Find("DamageLabel(Clone)") != null)
			{
				GameObject.Find("DamageLabel(Clone)").GetComponent<TextMesh>().color = Color.yellow;
			}
		}
	}
예제 #29
0
 static public Vector2 GetInArc(FloatRange angle, float low_radius, float high_radius)
 {
     return(SOURCE.GetInArc(angle, low_radius, high_radius));
 }
예제 #30
0
 public void SetActivationRange(FloatRange newRange)
 {
     PositiveBounds = newRange;
 }
예제 #31
0
 static public Vector2 GetInArc(float low_angle, float high_angle, FloatRange radius)
 {
     return(SOURCE.GetInArc(low_angle, high_angle, radius));
 }
 /// <summary>
 /// Sets the <see cref="Range"/> from a given Vector2.
 /// </summary>
 /// <param name="range">The new range.</param>
 public virtual void SetRange(Vector2 range)
 {
     Range = new FloatRange(range);
 }
예제 #33
0
    public Resource() : base() {
        adjusters = new List<ResourceAdjuster>();
        watchers = delegate (float a, float b) { };
		regenerationRate = new FloatRange();
    }
예제 #34
0
        /// <summary>
        /// Produces a secondary explosion on impact using the explosion values from the projectile's projectile def. Requires the projectile's launcher to be passed on due to protection level.
        /// Intended use is for HEAT and similar weapons that spawn secondary explosions while also penetrating, NOT explosive ammo of anti-materiel rifles as the explosion just spawns
        /// on top of the pawn, not inside the hit body part.
        ///
        /// Additionally handles fragmentation effects if defined.
        /// </summary>
        /// <param name="instigator">Launcher of the projectile calling the method</param>
        public virtual void Explode(Thing instigator, Vector3 pos, Map map, float scaleFactor = 1)
        {
            var posIV = pos.ToIntVec3();

            if (map == null)
            {
                Log.Warning("Tried to do explodeCE in a null map.");
                return;
            }
            if (!posIV.InBounds(map))
            {
                Log.Warning("Tried to explodeCE out of bounds");
                return;
            }

            var projCE = parent as ProjectileCE;

            #region Fragmentation
            if (!Props.fragments.NullOrEmpty())
            {
                float   edificeHeight = (new CollisionVertical(posIV.GetEdifice(map))).Max;
                Vector2 exactOrigin   = new Vector2(pos.x, pos.z);
                float   height;

                //Fragments fly from a 0 (half of a circle) to 45 (3/4 of a circle) degree angle away from the explosion
                var range = new FloatRange(0.5f, 0.75f);

                if (projCE != null)
                {
                    height = Mathf.Max(edificeHeight, pos.y);
                    if (edificeHeight < height)
                    {
                        //If the projectile exploded above the ground, they can fly 45 degree away (1/4 of a circle) at the bottom as well
                        range.min = 0.25f;
                    }
                    // TODO : Check for hitting the bottom or top of a roof
                }
                else
                {
                    //Height is not tracked on non-CE projectiles, so we assume this one's on top of the edifice
                    height = edificeHeight;
                }

                foreach (ThingDefCountClass fragment in Props.fragments)
                {
                    for (int i = 0; i < fragment.count; i++)
                    {
                        ProjectileCE projectile = (ProjectileCE)ThingMaker.MakeThing(fragment.thingDef, null);
                        GenSpawn.Spawn(projectile, posIV, map);

                        projectile.canTargetSelf   = true;
                        projectile.minCollisionSqr = 1f;
                        //TODO : Don't hardcode at FragmentShadowChance, make XML-modifiable
                        projectile.castShadow = (UnityEngine.Random.value < FragmentShadowChance);
                        projectile.logMisses  = false;
                        projectile.Launch(
                            instigator,
                            exactOrigin,
                            Mathf.Acos(2 * range.RandomInRange - 1),
                            UnityEngine.Random.Range(0, 360),
                            height,
                            Props.fragSpeedFactor * projectile.def.projectile.speed,
                            projCE
                            );
                    }
                }
            }
            #endregion

            // Regular explosion stuff
            if (Props.explosionRadius > 0 && Props.explosionDamage > 0 && parent.def != null && GenGrid.InBounds(posIV, map))
            {
                // Copy-paste from GenExplosion
                ExplosionCE explosion = GenSpawn.Spawn(CE_ThingDefOf.ExplosionCE, posIV, map) as ExplosionCE;
                explosion.height     = pos.y;
                explosion.radius     = Props.explosionRadius * scaleFactor;
                explosion.damType    = Props.explosionDamageDef;
                explosion.instigator = instigator;
                explosion.damAmount  = GenMath.RoundRandom(Props.explosionDamage * scaleFactor);
                explosion.weapon     = null;
                explosion.projectile = parent.def;
                explosion.preExplosionSpawnThingDef            = Props.preExplosionSpawnThingDef;
                explosion.preExplosionSpawnChance              = Props.preExplosionSpawnChance;
                explosion.preExplosionSpawnThingCount          = Props.preExplosionSpawnThingCount;
                explosion.postExplosionSpawnThingDef           = Props.postExplosionSpawnThingDef;
                explosion.postExplosionSpawnChance             = Props.postExplosionSpawnChance;
                explosion.postExplosionSpawnThingCount         = Props.postExplosionSpawnThingCount;
                explosion.applyDamageToExplosionCellsNeighbors = Props.applyDamageToExplosionCellsNeighbors;

                // TODO: for some reason projectile goes to null
                if (parent.def.projectile != null)
                {
                    explosion.chanceToStartFire = parent.def.projectile.explosionChanceToStartFire;
                    explosion.damageFalloff     = parent.def.projectile.explosionDamageFalloff;
                }
                explosion.StartExplosion(Props.explosionDamageDef.soundExplosion);
            }
        }
        private static void CalculateHeightRange(Thing thing, out FloatRange heightRange, out float shotHeight)
        {
            shotHeight = 0;
            if (thing == null)
            {
                heightRange = new FloatRange(0, 0);
                return;
            }
            if (thing is Building)
            {
                if (thing.def.Fillage == FillCategory.Full)
                {
                    heightRange = new FloatRange(0, WallCollisionHeight);
                    return;
                }
                if (thing.IsTree())
                {
                    heightRange = new FloatRange(0, TreeCollisionHeight);    // Check for trees
                    return;
                }
                float fillPercent = thing.def.fillPercent;
                heightRange = new FloatRange(Mathf.Min(0f, fillPercent), Mathf.Max(0f, fillPercent));
                shotHeight  = fillPercent;
                return;
            }
            float collisionHeight  = 0f;
            float shotHeightOffset = 0;
            var   pawn             = thing as Pawn;

            if (pawn != null)
            {
                collisionHeight  = pawn.BodySize * CE_Utility.GetCollisionBodyFactors(pawn).Second;
                shotHeightOffset = collisionHeight * (1 - BodyRegionMiddleHeight);

                // Humanlikes in combat crouch to reduce their profile
                if (pawn.IsCrouching())
                {
                    float crouchHeight = BodyRegionBottomHeight * collisionHeight;  // Minimum height we can crouch down to

                    // Find the highest adjacent cover
                    Map map = pawn.Map;
                    foreach (IntVec3 curCell in GenAdjFast.AdjacentCells8Way(pawn.Position))
                    {
                        if (curCell.InBounds(map))
                        {
                            Thing cover = curCell.GetCover(map);
                            if (cover != null && cover.def.Fillage == FillCategory.Partial && !cover.IsTree())
                            {
                                var coverHeight = new CollisionVertical(cover).Max;
                                if (coverHeight > crouchHeight)
                                {
                                    crouchHeight = coverHeight;
                                }
                            }
                        }
                    }
                    collisionHeight = Mathf.Min(collisionHeight, crouchHeight + 0.01f + shotHeightOffset);  // We crouch down only so far that we can still shoot over our own cover and never beyond our own body size
                }
            }
            else
            {
                collisionHeight = thing.def.fillPercent;
            }
            var edificeHeight = 0f;

            if (thing.Map != null)
            {
                var edifice = thing.Position.GetCover(thing.Map);
                if (edifice != null && edifice.GetHashCode() != thing.GetHashCode() && !edifice.IsTree())
                {
                    edificeHeight = new CollisionVertical(edifice).heightRange.max;
                }
            }
            float fillPercent2 = collisionHeight;

            heightRange = new FloatRange(Mathf.Min(edificeHeight, edificeHeight + fillPercent2), Mathf.Max(edificeHeight, edificeHeight + fillPercent2));
            shotHeight  = heightRange.max - shotHeightOffset;
        }
예제 #36
0
        public void ToVector2()
        {
            FloatRange range = new FloatRange(1f, 2f);

            Assert.AreEqual(new Vector2(1f, 2f), range.ToVector2());
        }
예제 #37
0
        public static void TrySpawnWeaponOnRack(Thing rack)
        {
            Building_Storage storage = rack as Building_Storage;
            QualityRange qualityRange = new QualityRange(QualityCategory.Good, QualityCategory.Legendary);
            storage.settings.filter.AllowedQualityLevels = qualityRange;
            FloatRange hitPointsRange = new FloatRange(0.8f, 1f);
            storage.settings.filter.AllowedHitPointsPercents = hitPointsRange;
            foreach (IntVec3 cell in rack.OccupiedRect())
            {
                if (Rand.Value < 0.33f)
                {
                    float weaponSelector = Rand.Value;
                    ThingDef thingDef = ThingDefOf.Gun_Pistol;
                    const float weaponsRatio = 1f / 7f;
                    if (weaponSelector < weaponsRatio * 1f)
                    {
                        thingDef = ThingDef.Named("Gun_PumpShotgun");
                    }
                    else if (weaponSelector < weaponsRatio * 2f)
                    {
                        thingDef = ThingDef.Named("Gun_AssaultRifle");
                    }
                    else if (weaponSelector < weaponsRatio * 3f)
                    {
                        thingDef = ThingDef.Named("Gun_SniperRifle");
                    }
                    else if (weaponSelector < weaponsRatio * 4f)
                    {
                        thingDef = ThingDef.Named("Gun_IncendiaryLauncher");
                    }
                    else if (weaponSelector < weaponsRatio * 5f)
                    {
                        thingDef = ThingDef.Named("Gun_LMG");
                    }
                    else if (weaponSelector < weaponsRatio * 6f)
                    {
                        thingDef = ThingDef.Named("Gun_ChargeRifle");
                    }
                    else
                    {
                        thingDef = ThingDefOf.Gun_Pistol;
                    }

                    Thing weapon = ThingMaker.MakeThing(thingDef);
                    CompQuality qualityComp = weapon.TryGetComp<CompQuality>();
                    if (qualityComp != null)
                    {
                        QualityCategory quality = (QualityCategory)Rand.RangeInclusive((int)QualityCategory.Normal, (int)QualityCategory.Excellent);
                        qualityComp.SetQuality(quality, ArtGenerationContext.Outsider);
                    }
                    GenSpawn.Spawn(weapon, cell);
                }
            }
        }
 public ScriptPackageReference(string name, string version, FloatRange floatRange, ScriptFileContent content) : base(name, version, floatRange)
 {
     referenceDirectivePattern = $@"^(\s*#r\s*""nuget:\s*)({name})(,\s*)(.*)(\s*""$)";
     loadDirectivePattern      = $@"^(\s*#load\s*""nuget:\s*)({name})(,\s*)(.*)(\s*""$)";
     this.content = content;
 }
예제 #39
0
 /// <summary>
 /// Check if the specified range is inside of the range.
 /// </summary>
 /// 
 /// <param name="range">Range to check.</param>
 /// 
 /// <returns><b>True</b> if the specified range is inside of the range or
 /// <b>false</b> otherwise.</returns>
 /// 
 public bool IsInside(FloatRange range)
 {
     return ((IsInside(range.min)) && (IsInside(range.max)));
 }
예제 #40
0
        /// <summary>
        /// Creates a range that is greater than or equal to the minVersion with the given float behavior.
        /// </summary>
        /// <param name="minVersion">Lower bound of the version range.</param>
        public VersionRange(NuGetVersion minVersion, FloatRange floatRange)
            : this(minVersion, true, null, false, null, floatRange)
        {

        }
예제 #41
0
	void OnTriggerEnter2D(Collider2D other)
	{
		if (other.tag.Equals("Wall"))
		{
			Destroy(this.gameObject);
		}

		// Launched by player
		if (Launcher != null && Launcher.tag.Equals("Player"))
		{
			if ((other.tag.Equals("Enemy") || other.tag.Equals("Boss")) && other is BoxCollider2D)
			{
				// Do damage to the enemy
				other.GetComponent<Enemy>().Health.Value -= Damage.Value;

				// Create a damage label object to display how much damage was done to the enemy.
				GameObject damagelabel = Resources.Load("DamageLabel") as GameObject;
				damagelabel.GetComponent<DamageLabel>().Text = "" + Damage.Value;
				Instantiate(damagelabel,
							new Vector3(other.transform.position.x, other.transform.position.y, -2),
							Quaternion.identity);


				// If this is a poison arrow then calculate the chance of poisoning the enemy
				if (this.gameObject.name.Equals("Poison Arrow(Clone)"))
				{
					float number = new FloatRange(0, 100).Random;
					bool willPoisonEnemy = (!(number % 2).Equals(0) && number < 20) ? true : false;

					if (willPoisonEnemy == true)
					{
						if (other.GetComponent<Enemy>() != null)
						{
							other.GetComponent<Enemy>().Poisoned = true;
						}
					}
				}


				Destroy(this.gameObject);
			}
		} else if(Launcher != null && (Launcher.tag.Equals("Enemy") || Launcher.tag.Equals("Boss"))) {
			if (other.tag.Equals("Player") && other is BoxCollider2D)
			{
				// Do damage to the enemy
				Healthbar.DecreaseHP(Damage.Value);

				Destroy(this.gameObject);
			}
		}
	}
예제 #42
0
 static public Vector2 GetInArc(FloatRange angle, FloatRange radius)
 {
     return(SOURCE.GetInArc(angle, radius));
 }
예제 #43
0
	private void FigureOutWeaponExtras(ItemType itemType, Enemy enem)
	{
		if (itemType == ItemType.ElectricSword)
		{
			// Calculate the added effect of stunning the enemy
			float number = new FloatRange(0, 100).Random;
			bool willStunEnemy = (!(number % 2).Equals(0) && number < 20) ? true : false;

			// Chanec of stunning
			if (willStunEnemy == true)
			{
				if (enem != null)
				{
					enem.stunTime = 5f;
				}
			}
		}

		if (itemType == ItemType.FlamingSword)
		{
			// Chance of burning the nemey
			float number = new FloatRange(0, 100).Random;
			bool willBurnEnemy = (!(number % 2).Equals(0) && number < 20) ? true : false;

			if (willBurnEnemy == true)
			{
				if (enem != null)
				{
					enem.Burned = true;
				}
			}
		}

		if (itemType == ItemType.IceSword)
		{
			// Chance of freezing the nemey
			float number = new FloatRange(0, 100).Random;
			bool willFreezeEnemy = (!(number % 2).Equals(0) && number < 20) ? true : false;

			if (willFreezeEnemy == true)
			{
				if (enem != null)
				{
					enem.Frozen = true;
				}
			}
		}
	}
예제 #44
0
    //todo this might also be responsible for cast time / channel time / tick time

    public Charge() {
        cooldown = new FloatRange();
        lastUsed = -1;
    }
예제 #45
0
 static public Vector2 GetInCircle(FloatRange radius)
 {
     return(SOURCE.GetInCircle(radius));
 }
예제 #46
0
        /// <summary>
        /// Clones a version range and applies a new float range.
        /// </summary>
        public VersionRange(VersionRange range, FloatRange floatRange)
            : this(range.MinVersion, range.IsMinInclusive, range.MaxVersion, range.IsMaxInclusive, range.IncludePrerelease, floatRange)
        {

        }
예제 #47
0
        public static void FloatRange(Rect canvas, int id, ref FloatRange range, FloatRange sliderRange, ToStringStyle valueStyle = ToStringStyle.FloatTwo, string labelKey = null)
        {
            // margin
            canvas.xMin += 8f;
            canvas.xMax -= 8f;

            // label
            Color mainColor = GUI.color;

            GUI.color = new Color(0.4f, 0.4f, 0.4f);
            string text = range.min.ToStringByStyle(valueStyle) + " - " + range.max.ToStringByStyle(valueStyle);

            if (labelKey != null)
            {
                text = labelKey.Translate(text);
            }
            Text.Font = GameFont.Tiny;
            Rect labelRect = new Rect(canvas.x, canvas.y, canvas.width, 19f);

            Text.Anchor = TextAnchor.UpperCenter;
            Widgets.Label(labelRect, text);
            Text.Anchor = TextAnchor.UpperLeft;

            // background line
            Rect sliderRect = new Rect(canvas.x, labelRect.yMax, canvas.width, 2f);

            GUI.DrawTexture(sliderRect, BaseContent.WhiteTex);
            GUI.color = mainColor;

            // slider handle positions
            float pxPerUnit    = sliderRect.width / sliderRange.Span;
            float minHandlePos = sliderRect.xMin + (range.min - sliderRange.min) * pxPerUnit;
            float maxHandlePos = sliderRect.xMin + (range.max - sliderRange.min) * pxPerUnit;

            // draw handles
            Rect minHandleRect = new Rect(minHandlePos - 16f, sliderRect.center.y - 8f, 16f, 16f);

            GUI.DrawTexture(minHandleRect, FloatRangeSliderTex);
            Rect maxHandleRect = new Rect(maxHandlePos + 16f, sliderRect.center.y - 8f, -16f, 16f);

            GUI.DrawTexture(maxHandleRect, FloatRangeSliderTex);

            // interactions
            Rect interactionRect = canvas;

            interactionRect.xMin -= 8f;
            interactionRect.xMax += 8f;
            bool dragging = false;

            if (Mouse.IsOver(interactionRect) || draggingId == id)
            {
                if (Event.current.type == EventType.MouseDown && Event.current.button == 0)
                {
                    draggingId = id;
                    float x = Event.current.mousePosition.x;
                    if (x < minHandleRect.xMax)
                    {
                        draggingHandle = Handle.Min;
                    }
                    else if (x > maxHandleRect.xMin)
                    {
                        draggingHandle = Handle.Max;
                    }
                    else
                    {
                        float distToMin = Mathf.Abs(x - minHandleRect.xMax);
                        float distToMax = Mathf.Abs(x - (maxHandleRect.x - 16f));
                        draggingHandle = distToMin >= distToMax ? Handle.Max : Handle.Min;
                    }
                    dragging = true;
                    Event.current.Use();
                }
                if (dragging || (draggingHandle != Handle.None && Event.current.type == EventType.MouseDrag))
                {
                    // NOTE: this deviates from vanilla, vanilla seemed to assume that max == span?
                    float curPosValue = (Event.current.mousePosition.x - canvas.x) / canvas.width * sliderRange.Span + sliderRange.min;
                    curPosValue = Mathf.Clamp(curPosValue, sliderRange.min, sliderRange.max);
                    if (draggingHandle == Handle.Min)
                    {
                        range.min = curPosValue;
                        if (range.max < range.min)
                        {
                            range.max = range.min;
                        }
                    }
                    else if (draggingHandle == Handle.Max)
                    {
                        range.max = curPosValue;
                        if (range.min > range.max)
                        {
                            range.min = range.max;
                        }
                    }
                    Event.current.Use();
                }
            }
            if (draggingHandle != Handle.None && Event.current.type == EventType.MouseUp)
            {
                draggingId     = 0;
                draggingHandle = Handle.None;
                Event.current.Use();
            }
        }
예제 #48
0
 public FloatRangeBoundry(FloatRange parent, float baseValue = 0f) : base(baseValue) {
     this.parent = parent;
 }
        private void DoGraphPage(Rect rect)
        {
            rect.yMin += 17f;
            GUI.BeginGroup(rect);
            Rect graphRect  = new Rect(0f, 0f, rect.width, 450f);
            Rect legendRect = new Rect(0f, graphRect.yMax, rect.width / 2f, 40f);
            Rect rect2      = new Rect(0f, legendRect.yMax, rect.width, 40f);

            if (historyAutoRecorderGroup != null)
            {
                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;
                        marks.Add(new CurveMark(x, tale.ShortSummary, tale.def.historyGraphColor));
                    }
                }
                historyAutoRecorderGroup.DrawGraph(graphRect, legendRect, graphSection, marks);
            }
            Text.Font = GameFont.Small;
            float num = (float)Find.TickManager.TicksGame / 60000f;

            if (Widgets.ButtonText(new Rect(legendRect.xMin + legendRect.width, legendRect.yMin, 110f, 40f), "Last30Days".Translate()))
            {
                graphSection = new FloatRange(Mathf.Max(0f, num - 30f), num);
                SoundDefOf.Click.PlayOneShotOnCamera();
            }
            if (Widgets.ButtonText(new Rect(legendRect.xMin + legendRect.width + 110f + 4f, legendRect.yMin, 110f, 40f), "Last100Days".Translate()))
            {
                graphSection = new FloatRange(Mathf.Max(0f, num - 100f), num);
                SoundDefOf.Click.PlayOneShotOnCamera();
            }
            if (Widgets.ButtonText(new Rect(legendRect.xMin + legendRect.width + 228f, legendRect.yMin, 110f, 40f), "Last300Days".Translate()))
            {
                graphSection = new FloatRange(Mathf.Max(0f, num - 300f), num);
                SoundDefOf.Click.PlayOneShotOnCamera();
            }
            if (Widgets.ButtonText(new Rect(legendRect.xMin + legendRect.width + 342f, legendRect.yMin, 110f, 40f), "AllDays".Translate()))
            {
                graphSection = new FloatRange(0f, num);
                SoundDefOf.Click.PlayOneShotOnCamera();
            }
            if (Widgets.ButtonText(new Rect(rect2.x, rect2.y, 110f, 40f), "SelectGraph".Translate()))
            {
                List <FloatMenuOption>          list  = new List <FloatMenuOption>();
                List <HistoryAutoRecorderGroup> list2 = Find.History.Groups();
                for (int j = 0; j < list2.Count; j++)
                {
                    HistoryAutoRecorderGroup groupLocal = list2[j];
                    if (!groupLocal.def.devModeOnly || Prefs.DevMode)
                    {
                        list.Add(new FloatMenuOption(groupLocal.def.LabelCap, delegate
                        {
                            historyAutoRecorderGroup = groupLocal;
                        }));
                    }
                }
                FloatMenu window = new FloatMenu(list, "SelectGraph".Translate());
                Find.WindowStack.Add(window);
                PlayerKnowledgeDatabase.KnowledgeDemonstrated(ConceptDefOf.HistoryTab, KnowledgeAmount.Total);
            }
            GUI.EndGroup();
        }
예제 #50
0
	protected override void OnPatternAdded(FloatRange distRange) {
		if (UnityEngine.Random.value > probability) return;
		GenerateCoinPattern(distRange);
	}
예제 #51
0
        private static Region ClosestRegionWithinTemperatureRange(IntVec3 root, Map map, FloatRange tempRange, TraverseParms traverseParms, RegionType traversableRegionTypes = RegionType.Set_Passable)
        {
            Region region = root.GetRegion(map, traversableRegionTypes);

            if (region == null)
            {
                return(null);
            }
            RegionEntryPredicate entryCondition = (Region from, Region r) => r.Allows(traverseParms, isDestination: false);
            Region          foundReg            = null;
            RegionProcessor regionProcessor     = delegate(Region r)
            {
                if (r.IsDoorway)
                {
                    return(false);
                }
                if (tempRange.Includes(r.Room.Temperature))
                {
                    foundReg = r;
                    return(true);
                }
                return(false);
            };

            RegionTraverser.BreadthFirstTraverse(region, entryCondition, regionProcessor, 9999, traversableRegionTypes);
            return(foundReg);
        }
예제 #52
0
파일: Range.cs 프로젝트: Zylann/GGJ14
 public FloatRange(FloatRange other)
 {
     min = other.min;
     max = other.max;
 }
    private void CreateRagdoll(float3 positionOffset, quaternion rotationOffset, int ragdollIndex = 1, bool internalCollisions = false)
    {
        var entities = new NativeList <Entity>(Allocator.Temp);

        // Head
        float  headRadius   = 0.1f;
        float3 headPosition = new float3(0, 1.8f, 0);
        Entity head;

        {
            CollisionFilter filter = internalCollisions ? layerFilter(layer.Head, layer.Torso) : groupFilter(-ragdollIndex);
            BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.SphereCollider.Create(new SphereGeometry
            {
                Center = float3.zero,
                Radius = headRadius
            }, filter);
            head = CreateDynamicBody(headPosition, quaternion.identity, collider, float3.zero, float3.zero, 5.0f);
        }
        entities.Add(head);

        // Torso
        float3 torsoSize;
        float3 torsoPosition;
        Entity torso;

        {
            //UnityEngine.Mesh torsoMesh = (UnityEngine.Mesh)Resources.Load("torso", typeof(UnityEngine.Mesh));
            torsoSize     = torsoMesh.bounds.size;
            torsoPosition = headPosition - new float3(0, headRadius * 3.0f / 4.0f + torsoSize.y, 0);

            CollisionFilter filter = internalCollisions ? layerFilter(layer.Torso, layer.Thigh | layer.Head | layer.UpperArm | layer.Pelvis) : groupFilter(-ragdollIndex);

            NativeArray <float3> points = new NativeArray <float3>(torsoMesh.vertices.Length, Allocator.TempJob);
            for (int i = 0; i < torsoMesh.vertices.Length; i++)
            {
                points[i] = torsoMesh.vertices[i];
            }
            BlobAssetReference <Unity.Physics.Collider> collider = ConvexCollider.Create(
                points, ConvexHullGenerationParameters.Default, CollisionFilter.Default
                );
            points.Dispose();
            collider.Value.Filter = filter;
            torso = CreateDynamicBody(torsoPosition, quaternion.identity, collider, float3.zero, float3.zero, 20.0f);
        }
        entities.Add(torso);

        // Neck
        {
            float3 pivotHead          = new float3(0, -headRadius, 0);
            float3 pivotBody          = math.transform(math.inverse(GetBodyTransform(torso)), math.transform(GetBodyTransform(head), pivotHead));
            float3 axis               = new float3(0, 1, 0);
            float3 perpendicular      = new float3(0, 0, 1);
            float  coneAngle          = (float)math.PI / 5.0f;
            var    perpendicularAngle = new FloatRange {
                Max = math.PI
            };                                                         // unlimited
            var twistAngle = new FloatRange(-math.PI / 3f, math.PI / 3f);

            var headFrame = new JointFrame {
                Axis = axis, PerpendicularAxis = perpendicular, Position = pivotHead
            };
            var bodyFrame = new JointFrame {
                Axis = axis, PerpendicularAxis = perpendicular, Position = pivotBody
            };
            BlobAssetReference <JointData> ragdoll0, ragdoll1;
            JointData.CreateRagdoll(headFrame, bodyFrame, coneAngle, perpendicularAngle, twistAngle, out ragdoll0, out ragdoll1);
            CreateJoint(ragdoll0, head, torso);
            CreateJoint(ragdoll1, head, torso);
        }

        // Arms
        {
            float           armLength      = 0.25f;
            float           armRadius      = 0.05f;
            CollisionFilter armUpperFilter = internalCollisions ? layerFilter(layer.UpperArm, layer.Torso | layer.Forearm) : groupFilter(-ragdollIndex);
            CollisionFilter armLowerFilter = internalCollisions ? layerFilter(layer.Forearm, layer.UpperArm | layer.Hand) : groupFilter(-ragdollIndex);

            BlobAssetReference <Unity.Physics.Collider> upperArmCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(-armLength / 2, 0, 0),
                Vertex1 = new float3(armLength / 2, 0, 0),
                Radius  = armRadius
            }, armUpperFilter);
            BlobAssetReference <Unity.Physics.Collider> foreArmCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(-armLength / 2, 0, 0),
                Vertex1 = new float3(armLength / 2, 0, 0),
                Radius  = armRadius
            }, armLowerFilter);

            float           handLength = 0.025f;
            float           handRadius = 0.055f;
            CollisionFilter handFilter = internalCollisions ? layerFilter(layer.Hand, layer.Forearm) : groupFilter(-ragdollIndex);

            BlobAssetReference <Unity.Physics.Collider> handCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(-handLength / 2, 0, 0),
                Vertex1 = new float3(handLength / 2, 0, 0),
                Radius  = handRadius
            }, handFilter);

            for (int i = 0; i < 2; i++)
            {
                float s = i * 2 - 1.0f;

                float3 upperArmPosition = torsoPosition + new float3(s * (torsoSize.x + armLength) / 2.0f, 0.9f * torsoSize.y - armRadius, 0.0f);
                Entity upperArm         = CreateDynamicBody(upperArmPosition, quaternion.identity, upperArmCollider, float3.zero, float3.zero, 10.0f);
                float3 foreArmPosition  = upperArmPosition + new float3(armLength * s, 0, 0);
                Entity foreArm          = CreateDynamicBody(foreArmPosition, quaternion.identity, foreArmCollider, float3.zero, float3.zero, 5.0f);
                float3 handPosition     = foreArmPosition + new float3((armLength + handLength) / 2.0f * s, 0, 0);
                Entity hand             = CreateDynamicBody(handPosition, quaternion.identity, handCollider, float3.zero, float3.zero, 2.0f);

                entities.Add(upperArm);
                entities.Add(foreArm);
                entities.Add(hand);

                // shoulder
                {
                    float3 pivotArm           = new float3(-s * armLength / 2.0f, 0, 0);
                    float3 pivotBody          = math.transform(math.inverse(GetBodyTransform(torso)), math.transform(GetBodyTransform(upperArm), pivotArm));
                    float3 axis               = new float3(s, 0, 0);
                    float3 perpendicular      = new float3(0, 0, 1);
                    float  coneAngle          = (float)math.PI / 2.0f;
                    var    perpendicularAngle = new FloatRange {
                        Max = math.PI / 2f
                    };
                    var twistAngle = new FloatRange(-math.PI / 4f, math.PI / 4f);

                    var armFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotArm
                    };
                    var bodyFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotBody
                    };
                    BlobAssetReference <JointData> ragdoll0, ragdoll1;
                    JointData.CreateRagdoll(armFrame, bodyFrame, coneAngle, perpendicularAngle, twistAngle, out ragdoll0, out ragdoll1);
                    CreateJoint(ragdoll0, upperArm, torso);
                    CreateJoint(ragdoll1, upperArm, torso);
                }

                // elbow
                {
                    float3 pivotUpper    = new float3(s * armLength / 2.0f, 0, 0);
                    float3 pivotFore     = -pivotUpper;
                    float3 axis          = new float3(0, -s, 0);
                    float3 perpendicular = new float3(s, 0, 0);

                    var lowerArmFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotFore
                    };
                    var upperArmFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotUpper
                    };
                    BlobAssetReference <JointData> hinge =
                        JointData.CreateLimitedHinge(lowerArmFrame, upperArmFrame, new FloatRange {
                        Max = 3f
                    });
                    CreateJoint(hinge, foreArm, upperArm);
                }

                // wrist
                {
                    float3 pivotFore     = new float3(s * armLength / 2.0f, 0, 0);
                    float3 pivotHand     = new float3(-s * handLength / 2.0f, 0, 0);
                    float3 axis          = new float3(0, -s, 0);
                    float3 perpendicular = new float3(s, 0, 0);

                    var handFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotHand
                    };
                    var forearmFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotFore
                    };
                    BlobAssetReference <JointData> hinge =
                        JointData.CreateLimitedHinge(handFrame, forearmFrame, new FloatRange(-0.3f, 0.6f));
                    CreateJoint(hinge, hand, foreArm);
                }
            }
        }

        // Pelvis
        float  pelvisRadius   = 0.08f;
        float  pelvisLength   = 0.22f;
        float3 pelvisPosition = torsoPosition - new float3(0, pelvisRadius * 0.75f, 0.0f);
        Entity pelvis;

        {
            CollisionFilter filter = internalCollisions ? layerFilter(layer.Pelvis, layer.Torso | layer.Thigh) : groupFilter(-ragdollIndex);
            BlobAssetReference <Unity.Physics.Collider> collider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(-pelvisLength / 2, 0, 0),
                Vertex1 = new float3(pelvisLength / 2, 0, 0),
                Radius  = pelvisRadius
            }, filter);
            pelvis = CreateDynamicBody(pelvisPosition, quaternion.identity, collider, float3.zero, float3.zero, 15.0f);
        }
        entities.Add(pelvis);

        // Waist
        {
            float3 pivotTorso         = float3.zero;
            float3 pivotPelvis        = math.transform(math.inverse(GetBodyTransform(pelvis)), math.transform(GetBodyTransform(torso), pivotTorso));
            float3 axis               = new float3(0, -1, 0);
            float3 perpendicular      = new float3(0, 0, 1);
            float  coneAngle          = 0.1f;
            var    perpendicularAngle = new FloatRange(-0.1f, math.PI);
            var    twistAngle         = new FloatRange(-0.1f, 0.1f);

            BlobAssetReference <JointData> ragdoll0, ragdoll1;
            var pelvisFrame = new JointFrame {
                Axis = axis, PerpendicularAxis = perpendicular, Position = pivotPelvis
            };
            var torsoFrame = new JointFrame {
                Axis = axis, PerpendicularAxis = perpendicular, Position = pivotTorso
            };
            JointData.CreateRagdoll(pelvisFrame, torsoFrame, coneAngle, perpendicularAngle, twistAngle, out ragdoll0, out ragdoll1);
            CreateJoint(ragdoll0, pelvis, torso);
            CreateJoint(ragdoll1, pelvis, torso);
        }

        // Legs
        {
            float           thighLength = 0.32f;
            float           thighRadius = 0.08f;
            CollisionFilter thighFilter = internalCollisions ? layerFilter(layer.Thigh, layer.Pelvis | layer.Calf) : groupFilter(-ragdollIndex);
            BlobAssetReference <Unity.Physics.Collider> thighCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(0, -thighLength / 2, 0),
                Vertex1 = new float3(0, thighLength / 2, 0),
                Radius  = thighRadius
            }, thighFilter);

            float           calfLength = 0.32f;
            float           calfRadius = 0.06f;
            CollisionFilter calfFilter = internalCollisions ? layerFilter(layer.Calf, layer.Thigh | layer.Foot) : groupFilter(-ragdollIndex);
            BlobAssetReference <Unity.Physics.Collider> calfCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(0, -calfLength / 2, 0),
                Vertex1 = new float3(0, calfLength / 2, 0),
                Radius  = calfRadius
            }, calfFilter);

            float           footLength = 0.08f;
            float           footRadius = 0.06f;
            CollisionFilter footFilter = internalCollisions ? layerFilter(layer.Foot, layer.Calf) : groupFilter(-ragdollIndex);
            BlobAssetReference <Unity.Physics.Collider> footCollider = Unity.Physics.CapsuleCollider.Create(new CapsuleGeometry
            {
                Vertex0 = new float3(0),
                Vertex1 = new float3(0, 0, footLength),
                Radius  = footRadius
            }, footFilter);

            for (int i = 0; i < 2; i++)
            {
                float s = i * 2 - 1.0f;

                float3 thighPosition = pelvisPosition + new float3(s * pelvisLength / 2.0f, -thighLength / 2.0f, 0.0f);
                Entity thigh         = CreateDynamicBody(thighPosition, quaternion.identity, thighCollider, float3.zero, float3.zero, 10.0f);
                float3 calfPosition  = thighPosition + new float3(0, -(thighLength + calfLength) / 2.0f, 0);
                Entity calf          = CreateDynamicBody(calfPosition, quaternion.identity, calfCollider, float3.zero, float3.zero, 5.0f);
                float3 footPosition  = calfPosition + new float3(0, -calfLength / 2.0f, 0);
                Entity foot          = CreateDynamicBody(footPosition, quaternion.identity, footCollider, float3.zero, float3.zero, 2.0f);

                entities.Add(thigh);
                entities.Add(calf);
                entities.Add(foot);

                // hip
                {
                    float3 pivotThigh    = new float3(0, thighLength / 2.0f, 0);
                    float3 pivotBody     = math.transform(math.inverse(GetBodyTransform(torso)), math.transform(GetBodyTransform(thigh), pivotThigh));
                    float3 axis          = new float3(0, -1, 0);
                    float3 perpendicular = new float3(s, 0, 0);
                    float  coneAngle     = (float)math.PI / 4.0f;

                    var perpendicularAngle = new FloatRange {
                        Max = 0.2f + math.PI / 2.0f
                    };
                    var twistAngle = new FloatRange(-0.2f, 0.2f);

                    var upperLegFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotThigh
                    };
                    var bodyFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotBody
                    };
                    BlobAssetReference <JointData> ragdoll0, ragdoll1;
                    JointData.CreateRagdoll(upperLegFrame, bodyFrame, coneAngle, perpendicularAngle, twistAngle, out ragdoll0, out ragdoll1);
                    CreateJoint(ragdoll0, thigh, torso);
                    CreateJoint(ragdoll1, thigh, torso);
                }

                // knee
                {
                    float3 pivotThigh    = new float3(0, -thighLength / 2.0f, 0);
                    float3 pivotCalf     = math.transform(math.inverse(GetBodyTransform(calf)), math.transform(GetBodyTransform(thigh), pivotThigh));
                    float3 axis          = new float3(-1, 0, 0);
                    float3 perpendicular = new float3(0, 0, 1);

                    var lowerLegFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotCalf
                    };
                    var upperLegFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotThigh
                    };
                    BlobAssetReference <JointData> hinge =
                        JointData.CreateLimitedHinge(lowerLegFrame, upperLegFrame, new FloatRange {
                        Min = -1.2f
                    });
                    CreateJoint(hinge, calf, thigh);
                }

                // ankle
                {
                    float3 pivotCalf     = new float3(0, -calfLength / 2.0f, 0);
                    float3 pivotFoot     = float3.zero;
                    float3 axis          = new float3(-1, 0, 0);
                    float3 perpendicular = new float3(0, 0, 1);

                    var footFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotFoot
                    };
                    var lowerLegFrame = new JointFrame {
                        Axis = axis, PerpendicularAxis = perpendicular, Position = pivotCalf
                    };
                    BlobAssetReference <JointData> hinge =
                        JointData.CreateLimitedHinge(footFrame, lowerLegFrame, new FloatRange(-0.4f, 0.1f));
                    CreateJoint(hinge, foot, calf);
                }
            }
        }

        var entityManager = BasePhysicsDemo.DefaultWorld.EntityManager;

        // reposition with offset information
        if (entities.Length > 0)
        {
            float3 center = float3.zero;
            for (int i = 0; i < entities.Length; i++)
            {
                var e = entities[i];
                center += entityManager.GetComponentData <Translation>(e).Value;
            }
            center /= entities.Length;
            for (int i = 0; i < entities.Length; i++)
            {
                var         e = entities[i];
                Translation positionComponent = entityManager.GetComponentData <Translation>(e);
                Rotation    rotationComponent = entityManager.GetComponentData <Rotation>(e);

                float3     position = positionComponent.Value;
                quaternion rotation = rotationComponent.Value;

                float3 localPosition = position - center;
                localPosition = math.rotate(rotationOffset, localPosition);

                position = localPosition + center + positionOffset;
                rotation = math.mul(rotation, rotationOffset);

                positionComponent.Value = position;
                rotationComponent.Value = rotation;

                entityManager.SetComponentData <Translation>(e, positionComponent);
                entityManager.SetComponentData <Rotation>(e, rotationComponent);
            }
        }
    }
예제 #54
0
파일: Range.cs 프로젝트: Zylann/GGJ14
 public void SetFromMix(FloatRange a, FloatRange b, float t)
 {
     min = Mathf.Lerp(a.min, b.min, t);
     max = Mathf.Lerp(a.max, b.max, t);
 }
        void CompareConfigurations(PTZConfiguration configuration1, PTZConfiguration configuration2)
        {
            bool          ok = true;
            bool          currentOk;
            StringBuilder sb = new StringBuilder();

            //Name
            if (configuration1.Name != configuration2.Name)
            {
                ok = false;
                sb.AppendLine("'Name' properties are different");
            }

            //Name
            if (configuration1.token != configuration2.token)
            {
                ok = false;
                sb.AppendLine("'token' properties are different");
            }

            //UseCount
            if (configuration1.UseCount != configuration2.UseCount)
            {
                ok = false;
                sb.AppendLine("'UseCount' properties are different");
            }

            //DefaultAbsolutePantTiltPositionSpace
            currentOk = StringsAreEqual(configuration1.DefaultAbsolutePantTiltPositionSpace,
                                        configuration2.DefaultAbsolutePantTiltPositionSpace,
                                        "DefaultAbsolutePantTiltPositionSpace", sb);
            ok = ok && currentOk;

            //DefaultAbsoluteZoomPositionSpace
            currentOk = StringsAreEqual(configuration1.DefaultAbsoluteZoomPositionSpace,
                                        configuration2.DefaultAbsoluteZoomPositionSpace,
                                        "DefaultAbsoluteZoomPositionSpace", sb);
            ok = ok && currentOk;

            //DefaultContinuousPanTiltVelocitySpace
            currentOk = StringsAreEqual(configuration1.DefaultContinuousPanTiltVelocitySpace,
                                        configuration2.DefaultContinuousPanTiltVelocitySpace,
                                        "DefaultContinuousPanTiltVelocitySpace", sb);
            ok = ok && currentOk;


            //DefaultContinuousZoomVelocitySpace
            currentOk = StringsAreEqual(configuration1.DefaultContinuousZoomVelocitySpace,
                                        configuration2.DefaultContinuousZoomVelocitySpace,
                                        "DefaultContinuousZoomVelocitySpace", sb);
            ok = ok && currentOk;


            //DefaultPTZSpeed
            if (configuration1.DefaultPTZSpeed != null && configuration2.DefaultPTZSpeed != null)
            {
                PTZSpeed speed1 = configuration1.DefaultPTZSpeed;
                PTZSpeed speed2 = configuration2.DefaultPTZSpeed;

                if (speed1.PanTilt != null && speed2.PanTilt != null)
                {
                    if (!(speed1.PanTilt.space == speed2.PanTilt.space && speed1.PanTilt.x == speed2.PanTilt.x && speed1.PanTilt.y == speed2.PanTilt.y))
                    {
                        ok = false;
                        sb.AppendLine("PanTilt settings in DefaultPTZSpeed are different");
                    }
                }
                else if (!(speed1.PanTilt == null && speed2.PanTilt == null))
                {
                    ok = false;
                    sb.AppendLine("PanTilt settings in DefaultPTZSpeed are defined for only one configuration");
                }

                if (speed1.Zoom != null && speed2.Zoom != null)
                {
                    if (!(speed1.Zoom.space == speed2.Zoom.space && speed1.Zoom.x == speed2.Zoom.x))
                    {
                        ok = false;
                        sb.AppendLine("Zoom settings in DefaultPTZSpeed are different");
                    }
                }
                else if (!(speed1.Zoom == null && speed2.Zoom == null))
                {
                    ok = false;
                    sb.AppendLine("Zoom settings in DefaultPTZSpeed are defined for only one configuration");
                }
            }
            else
            {
                if (!(configuration1.DefaultPTZSpeed == null && configuration2.DefaultPTZSpeed == null))
                {
                    ok = false;
                    sb.AppendLine("DefaultPTZSpeed are defined for only one configuration");
                }
            }


            //DefaultPTZTimeout
            //currentOk = StringsAreEqual(configuration1.DefaultPTZTimeout,
            //     configuration2.DefaultPTZTimeout,
            //     "DefaultPTZTimeout", sb);
            //ok = ok && currentOk;

            //DefaultRelativePanTiltTranslationSpace
            currentOk = StringsAreEqual(configuration1.DefaultRelativePanTiltTranslationSpace,
                                        configuration2.DefaultRelativePanTiltTranslationSpace,
                                        "DefaultRelativePanTiltTranslationSpace", sb);
            ok = ok && currentOk;

            //DefaultRelativeZoomTranslationSpace
            currentOk = StringsAreEqual(configuration1.DefaultRelativeZoomTranslationSpace,
                                        configuration2.DefaultRelativeZoomTranslationSpace,
                                        "DefaultRelativeZoomTranslationSpace", sb);
            ok = ok && currentOk;

            //NodeToken
            if (configuration1.NodeToken != configuration2.NodeToken)
            {
                ok = false;
                sb.AppendLine("'NodeToken' properties are different");
            }

            //PanTiltLimits
            if (configuration1.PanTiltLimits != null && configuration2.PanTiltLimits != null)
            {
                Space2DDescription range1 = configuration1.PanTiltLimits.Range;
                Space2DDescription range2 = configuration2.PanTiltLimits.Range;

                if (range1 != null && range2 != null)
                {
                    if (range1.URI != range2.URI)
                    {
                        ok = false;
                        sb.AppendLine("URI in 'PanTiltLimits' ranges are different");
                    }

                    FloatRange r1 = range1.XRange;
                    FloatRange r2 = range2.XRange;

                    if (r1 != null && r2 != null)
                    {
                        if (r1.Max != r2.Max || r1.Min != r2.Min)
                        {
                            ok = false;
                            sb.AppendLine("XRange in PanTiltLimits range are different");
                        }
                    }
                    else
                    {
                        if (!(r1 == null && r2 == null))
                        {
                            ok = false;
                            sb.AppendLine("XRange in PanTiltLimits range is defined for only one configuration");
                        }
                    }

                    r1 = range1.YRange;
                    r2 = range2.YRange;

                    if (r1 != null && r2 != null)
                    {
                        if (r1.Max != r2.Max || r1.Min != r2.Min)
                        {
                            ok = false;
                            sb.AppendLine("YRange in PanTiltLimits range are different");
                        }
                    }
                    else
                    {
                        if (!(r1 == null && r2 == null))
                        {
                            ok = false;
                            sb.AppendLine("YRange in PanTiltLimits range is defined for only one configuration");
                        }
                    }
                }
                else
                {
                    ok = false;
                    sb.AppendLine("'PanTiltLimits' range is defined for only one configuration");
                }
            }
            else
            {
                if (!(configuration1.PanTiltLimits == null && configuration2.PanTiltLimits == null))
                {
                    ok = false;
                    sb.AppendLine("PanTiltLimits are defined for only one configuration");
                }
            }


            //ZoomLimits
            if (configuration1.ZoomLimits != null && configuration2.ZoomLimits != null)
            {
                Space1DDescription range1 = configuration1.ZoomLimits.Range;
                Space1DDescription range2 = configuration2.ZoomLimits.Range;

                if (range1 != null && range2 != null)
                {
                    if (range1.URI != range2.URI)
                    {
                        ok = false;
                        sb.AppendLine("URI in ZoomLimits ranges are different");
                    }

                    FloatRange r1 = range1.XRange;
                    FloatRange r2 = range2.XRange;

                    if (r1 != null && r2 != null)
                    {
                        if (r1.Max != r2.Max || r1.Min != r2.Min)
                        {
                            ok = false;
                            sb.AppendLine("XRange in ZoomLimits range are different");
                        }
                    }
                    else
                    {
                        if (!(r1 == null && r2 == null))
                        {
                            ok = false;
                            sb.AppendLine("XRange in ZoomLimits range is defined for only one configuration");
                        }
                    }
                }
                else
                {
                    ok = false;
                    sb.AppendLine("'ZoomLimits' range is defined for only one configuration");
                }
            }
            else
            {
                if (!(configuration1.ZoomLimits == null && configuration2.ZoomLimits == null))
                {
                    ok = false;
                    sb.AppendLine("ZoomLimits are defined for only one configuration");
                }
            }

            Assert(ok, sb.ToStringTrimNewLine(), "Check that configurations are the same");
        }
예제 #56
0
 public static float Lerp(float val_t, FloatRange t, FloatRange r)
 {
     return(r.min + (r.max - r.min) * (val_t - t.min) / (t.max - t.min));
 }
        public static void FloatRange( Rect canvas, int id, ref FloatRange range, FloatRange sliderRange, ToStringStyle valueStyle = ToStringStyle.FloatTwo, string labelKey = null )
        {
            // margin
            canvas.xMin += 8f;
            canvas.xMax -= 8f;

            // label
            Color mainColor = GUI.color;
            GUI.color = new Color( 0.4f, 0.4f, 0.4f );
            string text = range.min.ToStringByStyle( valueStyle ) + " - " + range.max.ToStringByStyle( valueStyle );
            if( labelKey != null )
            {
                text = labelKey.Translate( text );
            }
            Text.Font = GameFont.Tiny;
            Rect labelRect = new Rect(canvas.x, canvas.y, canvas.width, 19f);
            Text.Anchor = TextAnchor.UpperCenter;
            Widgets.Label( labelRect, text );
            Text.Anchor = TextAnchor.UpperLeft;

            // background line
            Rect sliderRect = new Rect(canvas.x, labelRect.yMax, canvas.width, 2f);
            GUI.DrawTexture( sliderRect, BaseContent.WhiteTex );
            GUI.color = mainColor;

            // slider handle positions
            float pxPerUnit = sliderRect.width / sliderRange.Span;
            float minHandlePos = sliderRect.xMin + ( range.min - sliderRange.min ) * pxPerUnit;
            float maxHandlePos = sliderRect.xMin + ( range.max - sliderRange.min ) * pxPerUnit;
            
            // draw handles 
            Rect minHandleRect = new Rect(minHandlePos - 16f, sliderRect.center.y - 8f, 16f, 16f);
            GUI.DrawTexture( minHandleRect, FloatRangeSliderTex );
            Rect maxHandleRect = new Rect(maxHandlePos + 16f, sliderRect.center.y - 8f, -16f, 16f);
            GUI.DrawTexture( maxHandleRect, FloatRangeSliderTex );

            // interactions
            Rect interactionRect = canvas;
            interactionRect.xMin -= 8f;
            interactionRect.xMax += 8f;
            bool dragging = false;
            if( Mouse.IsOver( interactionRect ) || draggingId == id )
            {
                if( Event.current.type == EventType.MouseDown && Event.current.button == 0 )
                {
                    draggingId = id;
                    float x = Event.current.mousePosition.x;
                    if( x < minHandleRect.xMax )
                    {
                        draggingHandle = Handle.Min;
                    }
                    else if( x > maxHandleRect.xMin )
                    {
                        draggingHandle = Handle.Max;
                    }
                    else
                    {
                        float distToMin = Mathf.Abs(x - minHandleRect.xMax);
                        float distToMax = Mathf.Abs(x - (maxHandleRect.x - 16f));
                        draggingHandle = distToMin >= distToMax ? Handle.Max : Handle.Min;
                    }
                    dragging = true;
                    Event.current.Use();
                }
                if( dragging || ( draggingHandle != Handle.None && Event.current.type == EventType.MouseDrag ) )
                {
                    // NOTE: this deviates from vanilla, vanilla seemed to assume that max == span?
                    float curPosValue = (Event.current.mousePosition.x - canvas.x) / canvas.width * sliderRange.Span + sliderRange.min;
                    curPosValue = Mathf.Clamp( curPosValue, sliderRange.min, sliderRange.max );
                    if( draggingHandle == Handle.Min )
                    {
                        range.min = curPosValue;
                        if( range.max < range.min )
                        {
                            range.max = range.min;
                        }
                    }
                    else if( draggingHandle == Handle.Max )
                    {
                        range.max = curPosValue;
                        if( range.min > range.max )
                        {
                            range.min = range.max;
                        }
                    }
                    Event.current.Use();
                }
            }
            if( draggingHandle != Handle.None && Event.current.type == EventType.MouseUp )
            {
                draggingId = 0;
                draggingHandle = Handle.None;
                Event.current.Use();
            }
        }