public ColorPickerLogic(Widget widget, HSLColor initialColor, Action<HSLColor> onChange, WorldRenderer worldRenderer) { var hueSlider = widget.Get<SliderWidget>("HUE"); var mixer = widget.Get<ColorMixerWidget>("MIXER"); var randomButton = widget.GetOrNull<ButtonWidget>("RANDOM_BUTTON"); hueSlider.OnChange += _ => mixer.Set(hueSlider.Value); mixer.OnChange += () => onChange(mixer.Color); if (randomButton != null) randomButton.OnClick = () => { // Avoid colors with low sat or lum var hue = (byte)Game.CosmeticRandom.Next(255); var sat = (byte)Game.CosmeticRandom.Next(70, 255); var lum = (byte)Game.CosmeticRandom.Next(70, 255); mixer.Set(new HSLColor(hue, sat, lum)); hueSlider.Value = hue / 255f; }; // Set the initial state mixer.Set(initialColor); hueSlider.Value = initialColor.H / 255f; onChange(mixer.Color); }
public ColorPickerLogic(Widget widget, HSLColor initialColor, Action<HSLColor> onChange, WorldRenderer worldRenderer) { var ticker = widget.GetOrNull<LogicTickerWidget>("ANIMATE_PREVIEW"); if (ticker != null) { var preview = widget.Get<SpriteSequenceWidget>("PREVIEW"); var anim = preview.GetAnimation(); anim.PlayRepeating(anim.CurrentSequence.Name); ticker.OnTick = () => anim.Tick(); } var hueSlider = widget.Get<SliderWidget>("HUE"); var mixer = widget.Get<ColorMixerWidget>("MIXER"); var randomButton = widget.GetOrNull<ButtonWidget>("RANDOM_BUTTON"); hueSlider.OnChange += _ => mixer.Set(hueSlider.Value); mixer.OnChange += () => onChange(mixer.Color); if (randomButton != null) randomButton.OnClick = () => { // Avoid colors with low sat or lum var hue = (byte)Game.CosmeticRandom.Next(255); var sat = (byte)Game.CosmeticRandom.Next(70, 255); var lum = (byte)Game.CosmeticRandom.Next(70, 255); mixer.Set(new HSLColor(hue, sat, lum)); hueSlider.Value = hue / 255f; }; // Set the initial state mixer.Set(initialColor); hueSlider.Value = initialColor.H / 255f; onChange(mixer.Color); }
// Update is called once per frame void Update() { if (HSLToRGB) { hsl = new HSLColor(h, s, l); rgbCol = (Color) hsl; renderer.material.color = rgbCol; r = rgbCol.r; g = rgbCol.g; b = rgbCol.b; } else { hsl = rgbCol; Color temp = hsl; renderer.material.color = temp; h = hsl.h; s = hsl.s; l = hsl.l; r = temp.r; g = temp.g; b = temp.b; } }
public void DisplayMessage(string text, string prefix = "Mission", HSLColor? color = null) { if (string.IsNullOrEmpty(text)) return; Color c = color.HasValue ? HSLColor.RGBFromHSL(color.Value.H / 255f, color.Value.S / 255f, color.Value.L / 255f) : Color.White; Game.AddChatLine(c, prefix, text); }
public void FloatingText(string text, WPos position, int duration = 30, HSLColor? color = null) { if (string.IsNullOrEmpty(text) || !world.Map.Contains(world.Map.CellContaining(position))) return; Color c = color.HasValue ? HSLColor.RGBFromHSL(color.Value.H / 255f, color.Value.S / 255f, color.Value.L / 255f) : Color.White; world.AddFrameEndTask(w => w.Add(new FloatingText(position, c, text, duration))); }
public override void Tick() { if (cachedColor == Color) return; preview.ApplyRemap(new PlayerColorRemap(RemapIndices, Color, Ramp)); cachedColor = Color; }
public static List<Color> GetAnalogousColorsForColor(HSLColor originalColor) { var analogousColors = new List<Color> { GetColorShiftedByAngle(originalColor, -30.0f), GetColorShiftedByAngle(originalColor, 30.0f) }; return analogousColors; }
public static List<Color> GetTriadicColorsForColor(HSLColor originalColor) { var triadicColors = new List<Color> { GetColorShiftedByAngle(originalColor, -120.0f), GetColorShiftedByAngle(originalColor, 120.0f) }; return triadicColors; }
public static List<Color> GetSplitComplementaryColorsForColor(HSLColor originalColor) { var splitComplementaryColors = new List<Color> { GetColorShiftedByAngle(originalColor, 150.0f), GetColorShiftedByAngle(originalColor, 210.0f) }; return splitComplementaryColors; }
public static List<Color> GetTetradicColorsForColor(HSLColor originalColor) { var tetradicColors = new List<Color> { GetColorShiftedByAngle(originalColor, -90.0f), GetColorShiftedByAngle(originalColor, 90.0f), GetComplementaryColor(originalColor) }; return tetradicColors; }
public SimpleAgent() { created_Agents++; alive_Agents++; ID(created_Agents); // Age by 1 every cycle mb.Add(new AgingBehavior(this, 1)); // Get hungrier by 0.75 every cycle mb.Add(new HungerBehavior(this, 0.75f)); // Define how we behave while well fed (>90) mb.Add(new WellFedMovementBehavior(this)); int lim = 1; // Define how we behave while wed less-than-well (<=90) mb.Add(new UnderfedMovementBehavior(this, lim)); // Define how we eat mb.Add(new FeedBehavior(this)); // Define how we multiply mb.Add(new MultiplicationBehavior(this, 110)); // Sometimes we die. mb.Add(new DeathBehavior(this)); // Golden ratio conjugate for uniform distribution of random colors double golden_ratio_conjugate = 0.618033988749895; // Constant saturation and luminosity double sat = 0.5f; double lum = 0.6f; // Random hue double h = rnd.NextDouble(); h += golden_ratio_conjugate; h %= 1; // Generate color HSLColor c = new HSLColor(h * 240, sat * 240, lum * 240); Col(c); }
public Player(World world, Session.Client client, Session.Slot slot, PlayerReference pr) { World = world; InternalName = pr.Name; PlayerReference = pr; string botType = null; // Real player or host-created bot if (client != null) { ClientIndex = client.Index; Color = client.Color; PlayerName = client.Name; botType = client.Bot; Country = ChooseCountry(world, client.Country); } else { // Map player ClientIndex = 0; // Owned by the host (TODO: fix this) Color = pr.Color; PlayerName = pr.Name; NonCombatant = pr.NonCombatant; Playable = pr.Playable; Spectating = pr.Spectating; botType = pr.Bot; Country = ChooseCountry(world, pr.Race); } PlayerActor = world.CreateActor("Player", new TypeDictionary { new OwnerInit(this) }); Shroud = PlayerActor.Trait<Shroud>(); // Enable the bot logic on the host IsBot = botType != null; if (IsBot && Game.IsHost) { var logic = PlayerActor.TraitsImplementing<IBot>() .FirstOrDefault(b => b.Info.Name == botType); if (logic == null) Log.Write("debug", "Invalid bot type: {0}", botType); else logic.Activate(this); } }
public FoodTickerAgent() { mb.Add(new FoodTickerBehavior(this, 100)); // Golden ratio conjugate for uniform distribution of random colors double golden_ratio_conjugate = 0.618033988749895; // Constant saturation and luminosity double sat = 0.5f; double lum = 0.6f; // Random hue double h = rnd.NextDouble(); h += golden_ratio_conjugate; h %= 1; // Generate color HSLColor c = new HSLColor(h * 240, sat * 240, lum * 240); Col(c); }
public static Color GetColorShiftedByAngle(HSLColor originalColor, float angle) { if (angle < 0) { while (angle < 0) { angle += 360.0f; } } var baseAngle = (float) originalColor.Hue / 240.0f * 360.0f; var finalAngle = baseAngle + angle; if (finalAngle > 360.0f) { finalAngle -= 360.0f; } Color finalColor = new HSLColor(finalAngle / 360.0f * 240.0f, originalColor.Saturation, originalColor.Luminosity); return Color.FromArgb(255, finalColor.R, finalColor.G, finalColor.B); }
public SpawnOccupant(GameInformation.Player player) { Color = player.Color; ClientIndex = player.ClientIndex; PlayerName = player.Name; Team = player.Team; Country = player.FactionId; SpawnPoint = player.SpawnPoint; }
private void SetColorsHSL(int index, float h, float s, float l) { colors[0][index] = new HSLColor(h, 1f, 0.5f).ToColor(255); colors[1][index] = new Color(l, l, l, 1f - s); colors[2][index] = new Color(l, l, l, Mathf.Abs(l - 0.5f) * 2); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { HSLColor selectedColor = (HSLColor)value; return(ColorHelper.GetColorShiftedByAngle(selectedColor, 150.0f)); }
private void BobberThread() { int EffectLengthi = 5000; if (BobberThreadEffectFinish == null) { BobberThreadEffectFinish = DateTime.Now; } const int numeffects = 6; while (true) { lock (ImageBackBufferCanvas) { Thread.Sleep(50); Thread.SpinWait(15); while (Form.ActiveForm == null) { Thread.Sleep(0); } if (!this.Visible) { Thread.Sleep(0); //nothing to do, allow other threads to run. } else { DrawFrame(); } if (performingEffect) { bool doflip = false; TimeSpan EffectLength = DateTime.Now - BobberThreadEffectStart; //currently the only supported "effect" ,draws a bunch of particles across the screen halfway. (Y). imagesdraw.Clear(); if (EffectLength.TotalMilliseconds > EffectLengthi) { performingEffect = false; prevparticlepos = new PointF(0, 0); BobberThreadEffectFinish = DateTime.Now; } else { double currpercent = (double)EffectLength.TotalMilliseconds / (double)EffectLengthi; int Xpos = (int) (((float)(ImageBackBufferbitmap.Width * 1.5) * currpercent) - ((float)(ImageBackBufferbitmap.Width * 0.2f))); Debug.Print("Effect currpercent=" + currpercent); // PointF addparticlepos = new PointF(Xpos, ImageBackBufferbitmap.Height / 2); int effectnumber = EffectCount % numeffects; if (effectnumber % 2 == 0) { Xpos = ImageBackBufferbitmap.Width - Xpos; doflip = true; } PointF addparticlepos = new PointF(Xpos, 163); if (prevparticlepos.X == 0 && prevparticlepos.Y == 0) { prevparticlepos = addparticlepos; } float usehue = (((float)currpercent * 3) % 1) * 240; Color particlecolor = new HSLColor(usehue, 240, 120); const float maxoutspeed = 1f; const int numparticles = 25; Image usepic = null; System.Drawing.Size?usesize; switch (effectnumber) { case 0: case 2: usepic = rdash.BackgroundImage; if (effectnumber == 2) { addparticlepos = new PointF(addparticlepos.X, ((float)Math.Sin(addparticlepos.X / 16) * 8) + addparticlepos.Y); } /*for (int addp = 0; addp < numparticles*2; addp++) * { * Particle addparticle = new DustParticle(addparticlepos, (float) (rg.NextDouble()*4), * 7500, particlecolor); * * * lock (DrawParticles) * { * DrawParticles.Add(addparticle); * } * }*/ //create a spectrum... const float numlines = 25; const int totalsize = 100; for (int i = 0; i < numlines; i++) { float useYoffset = (totalsize / 2) + (((float)i / numlines) * totalsize); float pct = ((float)i / numlines); float percenthue = (pct * 240); PointF offsetamount = new PointF(addparticlepos.X - prevparticlepos.X, addparticlepos.Y - prevparticlepos.Y); //PointF firstpoint = new PointF(addparticlepos.X, useYoffset); //PointF secondpoint = new PointF(firstpoint.X+offsetamount.X,firstpoint.Y+offsetamount.Y); PointF firstpoint = addparticlepos; PointF secondpoint = prevparticlepos; if (firstpoint.X > secondpoint.X) { firstpoint = new PointF(firstpoint.X + 2, firstpoint.Y); secondpoint = new PointF(secondpoint.X - 2, secondpoint.Y); } else { firstpoint = new PointF(firstpoint.X - 2, firstpoint.Y); secondpoint = new PointF(secondpoint.X + 2, secondpoint.Y); } //float phue = (percenthue + (Xpos/2)%240 )%240; float phue = percenthue % 240; Color linecoloruse = new HSLColor(phue, 240, 120); float usevel = (pct - 0.5f) * 5; DustParticle dust1 = new DustParticle(firstpoint, new PointF(0, usevel)); DustParticle dust2 = new DustParticle(secondpoint, new PointF(0, usevel)); LineParticle lp = new LineParticle(dust1, dust2, linecoloruse); lock (DrawParticles) { DrawParticles.Add(lp); if (Math.Truncate((double)Xpos) % 15 == 0) { //add a 5-pointed star... //StarParticle staradd = new StarParticle(addparticlepos, BCBlockGameState.GetRandomVelocity(0,3), 5, 3, 6, Color.Yellow, Color.Black, (float)(rg.NextDouble() * 2)); CharacterDebris staradd = new CharacterDebris(addparticlepos, BCBlockGameState. GetRandomVelocity(0, 3), Color.Yellow, 8, 18); DrawParticles.Add(staradd); } } } /* * Particle addParticleA = new DustParticle(addparticlepos, new PointF(0, -2)); * Particle addParticleB = new DustParticle(addparticlepos, new PointF(0, 2)); * LineParticle lp = new LineParticle(addParticleA, addParticleB, particlecolor); * * lock (DrawParticles) * { * DrawParticles.Add(lp); * } * * */ break; case 1: case 3: usepic = rdash.BackgroundImage; if (effectnumber == 3) { addparticlepos = new PointF(addparticlepos.X, ((float)Math.Sin(addparticlepos.X / 32) * 16) + addparticlepos.Y); } for (int addp = 0; addp < numparticles; addp++) { float ppercent = (float)addp / (float)numparticles; float usespeed = (float)(((maxoutspeed * 2) * ppercent) - maxoutspeed); PointF speeduse = new PointF((float)(rg.NextDouble() - 0.5d), usespeed); particlecolor = new HSLColor(ppercent * 240, 240, 120); //Particle addparticle = new PolyDebris(addparticlepos, rg.NextDouble() * 2, particlecolor, 3, 4, 3, 8); Particle addparticle = new PolyDebris(addparticlepos, speeduse, particlecolor, 3, 4, 3, 8); lock (DrawParticles) { DrawParticles.Add(addparticle); } } break; case 4: usepic = ttoaster.BackgroundImage; for (int addp = 0; addp < numparticles * 2; addp++) { particlecolor = Color.FromArgb(rg.Next(255), rg.Next(255), 0); Particle addparticle = new DustParticle(addparticlepos, (float)(rg.NextDouble() * 4), 7500, particlecolor); lock (DrawParticles) { DrawParticles.Add(addparticle); } } break; case 5: /* * */ //megaman sprites... //since these are loaded if (!mmimagesloaded) { mmimagesloaded = true; try { mmimages = BCBlockGameState.Imageman.getImageFrames("megaman"); } catch { mmimagesloaded = false; } } if (mmimagesloaded) { if ((DateTime.Now - lastmmFrameChange) > mmFrameDelayTime) { //advance the frame. mmimageframe++; } mmimageframe = mmimageframe % mmimages.Length; //they are... or should be, loaded now. usepic = mmimages[mmimageframe]; usesize = new Size(usepic.Size.Width * 3, usepic.Size.Height * 3); } break; /* * case 3: * * addparticlepos = new PointF(addparticlepos.X, ((float)Math.Sin(addparticlepos.X / 16) * 8) + addparticlepos.Y); * for (int addp = 0; addp < numparticles; addp++) * { * Particle addparticle = new PolyDebris(addparticlepos, rg.NextDouble()*2, particlecolor, 3, 4, 3, 8); * * * lock (DrawParticles) * { * DrawParticles.Add(addparticle); * } * } * break; */ } drawimagedata dd = new drawimagedata(); dd.DrawImage = (Image)usepic.Clone(); if (doflip) { dd.DrawImage.RotateFlip(RotateFlipType.RotateNoneFlipX); } dd.Location = addparticlepos; //imagesdraw.Add(new drawimagedata(BCBlockGameState.Imageman.GetLoadedImage("rdash") double ang = BCBlockGameState.GetAngle(prevparticlepos, addparticlepos); Debug.Print("chosen angle=" + ang); dd.Angle = ang; if (doflip) { dd.Angle += (float)Math.PI; } imagesdraw.Add(dd); prevparticlepos = addparticlepos; } } else if ((DateTime.Now - BobberThreadEffectFinish.Value).TotalSeconds >= 60) { EffectCount++; EffectCount = EffectCount % numeffects; switch (EffectCount) { case 0: case 1: case 2: case 3: EffectLengthi = 5000; if (BCBlockGameState.Soundman != null) //can be null, if you press shift during startup and take a while on the screen presented... { if (BCBlockGameState.Soundman.HasSound("asboom")) { BCBlockGameState.Soundman.PlaySound("asboom", 3.0f); } } break; case 4: iSoundSourceObject grabsound; if (BCBlockGameState.Soundman != null) { if (((grabsound = BCBlockGameState.Soundman.GetSoundRnd("TTOASTER")) != null)) { grabsound.Play(false, 3.0f); } } break; case 5: if (BCBlockGameState.Soundman != null) { BCBlockGameState.Soundman.PlaySound("ray"); } break; } Debug.Print("invoking effect #" + EffectCount); performingEffect = true; BobberThreadEffectStart = DateTime.Now; } } } }
public void TestWhiteCanBeRepresentedAsAnHSLColor() { var black = new HSLColor(0, 0, 1); new[] { black.H, black.S, black.L }.Should().BeEquivalentTo(new byte[] { 0, 0, 1 }); }
private void BobberThread() { int EffectLengthi = 5000; if (BobberThreadEffectFinish == null) { BobberThreadEffectFinish = DateTime.Now; } const int numeffects = 6; while (true) { lock (ImageBackBufferCanvas) { Thread.Sleep(40); Thread.SpinWait(15); while (Form.ActiveForm == null) Thread.Sleep(50); if (!this.Visible) { Thread.Sleep(50); //nothing to do, allow other threads to run. } else { DrawFrame(); } if (performingEffect) { bool doflip = false; TimeSpan EffectLength = DateTime.Now - BobberThreadEffectStart; //currently the only supported "effect" ,draws a bunch of particles across the screen halfway. (Y). imagesdraw.Clear(); if (EffectLength.TotalMilliseconds > EffectLengthi) { performingEffect = false; prevparticlepos = new PointF(0, 0); BobberThreadEffectFinish = DateTime.Now; } else { double currpercent = (double) EffectLength.TotalMilliseconds/(double) EffectLengthi; int Xpos = (int) (((float) (ImageBackBufferbitmap.Width*1.5)*currpercent) - ((float) (ImageBackBufferbitmap.Width*0.2f))); Debug.Print("Effect currpercent=" + currpercent); // PointF addparticlepos = new PointF(Xpos, ImageBackBufferbitmap.Height / 2); int effectnumber = EffectCount%numeffects; if (effectnumber%2 == 0) { Xpos = ImageBackBufferbitmap.Width - Xpos; doflip = true; } PointF addparticlepos = new PointF(Xpos, 163); if (prevparticlepos.X == 0 && prevparticlepos.Y == 0) prevparticlepos = addparticlepos; float usehue = (((float) currpercent*3)%1)*240; Color particlecolor = new HSLColor(usehue, 240, 120); const float maxoutspeed = 1f; const int numparticles = 25; Image[] usepics = null; System.Drawing.Size? usesize; switch (effectnumber) { case 0: case 2: usepics = new Image[] { rdash.BackgroundImage }; if (effectnumber == 2) addparticlepos = new PointF(addparticlepos.X, ((float) Math.Sin(addparticlepos.X/16)*8) + addparticlepos.Y); /*for (int addp = 0; addp < numparticles*2; addp++) { Particle addparticle = new DustParticle(addparticlepos, (float) (rg.NextDouble()*4), 7500, particlecolor); lock (DrawParticles) { DrawParticles.Add(addparticle); } }*/ //create a spectrum... const float numlines = 25; const int totalsize = 100; for (int i = 0; i < numlines; i++) { float useYoffset = (totalsize/2) + (((float) i/numlines)*totalsize); float pct = ((float) i/numlines); float percenthue = (pct*240); PointF offsetamount = new PointF(addparticlepos.X - prevparticlepos.X, addparticlepos.Y - prevparticlepos.Y); //PointF firstpoint = new PointF(addparticlepos.X, useYoffset); //PointF secondpoint = new PointF(firstpoint.X+offsetamount.X,firstpoint.Y+offsetamount.Y); PointF firstpoint = addparticlepos; PointF secondpoint = prevparticlepos; if (firstpoint.X > secondpoint.X) { firstpoint = new PointF(firstpoint.X + 2, firstpoint.Y); secondpoint = new PointF(secondpoint.X - 2, secondpoint.Y); } else { firstpoint = new PointF(firstpoint.X - 2, firstpoint.Y); secondpoint = new PointF(secondpoint.X + 2, secondpoint.Y); } //float phue = (percenthue + (Xpos/2)%240 )%240; float phue = percenthue%240; Color linecoloruse = new HSLColor(phue, 240, 120); float usevel = (pct - 0.5f)*5; DustParticle dust1 = new DustParticle(firstpoint, new PointF(0, usevel)); DustParticle dust2 = new DustParticle(secondpoint, new PointF(0, usevel)); LineParticle lp = new LineParticle(dust1, dust2, linecoloruse); lock (DrawParticles) { DrawParticles.Add(lp); if (Math.Truncate((double) Xpos)%15 == 0) { //add a 5-pointed star... //StarParticle staradd = new StarParticle(addparticlepos, BCBlockGameState.GetRandomVelocity(0,3), 5, 3, 6, Color.Yellow, Color.Black, (float)(rg.NextDouble() * 2)); CharacterDebris staradd = new CharacterDebris(addparticlepos, BCBlockGameState. GetRandomVelocity(0, 3), Color.Yellow, 8, 18); DrawParticles.Add(staradd); } } } /* Particle addParticleA = new DustParticle(addparticlepos, new PointF(0, -2)); Particle addParticleB = new DustParticle(addparticlepos, new PointF(0, 2)); LineParticle lp = new LineParticle(addParticleA, addParticleB, particlecolor); lock (DrawParticles) { DrawParticles.Add(lp); } */ break; case 1: case 3: usepics = new Image[] {rdash.BackgroundImage}; if (effectnumber == 3) addparticlepos = new PointF(addparticlepos.X, ((float) Math.Sin(addparticlepos.X/32)*16) + addparticlepos.Y); for (int addp = 0; addp < numparticles; addp++) { float ppercent = (float) addp/(float) numparticles; float usespeed = (float) (((maxoutspeed*2)*ppercent) - maxoutspeed); PointF speeduse = new PointF((float) (rg.NextDouble() - 0.5d), usespeed); particlecolor = new HSLColor(ppercent*240, 240, 120); //Particle addparticle = new PolyDebris(addparticlepos, rg.NextDouble() * 2, particlecolor, 3, 4, 3, 8); Particle addparticle = new PolyDebris(addparticlepos, speeduse, particlecolor, 3, 4, 3, 8); lock (DrawParticles) { DrawParticles.Add(addparticle); } } break; case 4: usepics = new Image[] { ttoaster.BackgroundImage }; for (int addp = 0; addp < numparticles*2; addp++) { particlecolor = Color.FromArgb(rg.Next(255), rg.Next(255), 0); Particle addparticle = new DustParticle(addparticlepos, (float) (rg.NextDouble()*4), 7500, particlecolor); lock (DrawParticles) { DrawParticles.Add(addparticle); } } break; case 5: /* */ //megaman sprites... //since these are loaded if (!mmimagesloaded) { mmimagesloaded = true; try { mmimages = BCBlockGameState.Imageman.getImageFrames("megaman"); } catch { mmimagesloaded = false; } } if (mmimagesloaded) { if ((DateTime.Now - lastmmFrameChange) > mmFrameDelayTime) { //advance the frame. mmimageframe++; } mmimageframe = mmimageframe%mmimages.Length; //they are... or should be, loaded now. usepics = new Image[] {mmimages[mmimageframe]}; usesize = new Size(usepics[0].Size.Width*3, usepics[0].Size.Height*3); } break; /* case 3: addparticlepos = new PointF(addparticlepos.X, ((float)Math.Sin(addparticlepos.X / 16) * 8) + addparticlepos.Y); for (int addp = 0; addp < numparticles; addp++) { Particle addparticle = new PolyDebris(addparticlepos, rg.NextDouble()*2, particlecolor, 3, 4, 3, 8); lock (DrawParticles) { DrawParticles.Add(addparticle); } } break; */ } drawimagedata dd = new drawimagedata(); //dd.DrawImage = (Image) usepic.Clone(); dd.ImageFrames = usepics; if (doflip) dd.DrawImage.RotateFlip(RotateFlipType.RotateNoneFlipX); dd.Location = addparticlepos; //imagesdraw.Add(new drawimagedata(BCBlockGameState.Imageman.GetLoadedImage("rdash") double ang = BCBlockGameState.GetAngle(prevparticlepos, addparticlepos); Debug.Print("chosen angle=" + ang); dd.Angle = ang; //if (doflip) dd.Angle += (float) Math.PI; imagesdraw.Add(dd); prevparticlepos = addparticlepos; } } else if ((DateTime.Now - BobberThreadEffectFinish.Value).TotalSeconds >= 60) { EffectCount++; EffectCount = EffectCount%numeffects; switch (EffectCount) { case 0: case 1: case 2: case 3: EffectLengthi = 5000; if (BCBlockGameState.Soundman != null) //can be null, if you press shift during startup and take a while on the screen presented... { if (BCBlockGameState.Soundman.HasSound("asboom")) { BCBlockGameState.Soundman.PlaySound("asboom", 3.0f); } } break; case 4: iSoundSourceObject grabsound; if (BCBlockGameState.Soundman != null) { if (((grabsound = BCBlockGameState.Soundman.GetSoundRnd("TTOASTER")) != null)) { grabsound.Play(false, 3.0f); } } break; case 5: if(BCBlockGameState.Soundman!=null) BCBlockGameState.Soundman.PlaySound("ray"); break; } Debug.Print("invoking effect #" + EffectCount); performingEffect = true; BobberThreadEffectStart = DateTime.Now; } } } }
public static ColorScheme FromHue(float hue, float multiplier) { Func <HSLColor, float, HSLColor> getColor = (hsl, luminosity) => hsl.WithLuminosity(((luminosity - 0.5f) * multiplier) + 0.5f); var scheme = new ColorScheme(); HSLColor gray; if (multiplier > 0.9f || multiplier < -0.9f) { gray = HSLColor.FromRGB(0.5f, 0.5f, 0.5f); } else { gray = HSLColor.FromRGB(0.5f, 0.5f, 0.515f); } var highlight = new HSLColor(hue, 1f, 0.5f); // Light scheme scheme.IsLightTheme = multiplier > 0; //if (scheme.IsLightTheme) //{ // scheme.TabPanelBG = Color.White; //} //else //{ // scheme.TabPanelBG = Color.Gray; //} // Text scheme.TextCaret = new SolidBrush(scheme.Text = (multiplier > 0 ? HSLColor.FromRGB(0, 0, 0) : HSLColor.FromRGB(1, 1, 1)).ToColor()); scheme.ChatBorderFocused = scheme.ChatBorder = getColor(gray, 1f).ToPen(); scheme.ChatMessageSeperatorBorder = getColor(gray, 0.99f).ToPen(); scheme.ChatMessageSeperatorBorderInner = getColor(gray, 0.8f).ToPen(); scheme.ChatSeperator = getColor(gray, 0.75f).ToColor(); // Backgrounds scheme.ChatBackground = getColor(gray, 0.95f).ToBrush(); if (scheme.IsLightTheme) { scheme.ChatBackgroundHighlighted = getColor(HSLColor.FromRGB(1f, 0.5f, 0.5f), 0.9f).ToBrush(); scheme.ChatBackgroundUsernameHighlighted = new SolidBrush(rgb(0xead09f)); scheme.ChatBackgroundResub = getColor(HSLColor.FromRGB(0.5f, 0.5f, 1f), 0.9f).ToBrush(); scheme.ChatBackgroundWhisper = getColor(HSLColor.FromRGB(0.5f, 1f, 0.5f), 0.9f).ToBrush(); scheme.ChatBackgroundSearchResult = new SolidBrush(rgb(0xaaf9a4)); scheme.ChatBackgroundHighlightedMessage = new SolidBrush(rgb(0xc3e0df)); } else { //scheme.ChatBackgroundHighlighted = getColor(HSLColor.FromRGB(0.6f, 0.5f, 0.52f), 0.9f).ToBrush(); //scheme.ChatBackgroundHighlighted = new SolidBrush(Color.FromArgb(52, 0, 16)); var l = multiplier == -1 ? 0 : 20; scheme.ChatBackgroundHighlighted = new SolidBrush(Color.FromArgb(55 + l, 20 + l, 24 + l)); scheme.ChatBackgroundUsernameHighlighted = new SolidBrush(Color.FromArgb(61 + l, 49 + l, 28 + l)); scheme.ChatBackgroundResub = new SolidBrush(Color.FromArgb(47 + l, 20 + l, 70 + l)); scheme.ChatBackgroundWhisper = new SolidBrush(Color.FromArgb(20 + l, 40 + l, 70 + l)); scheme.ChatBackgroundSearchResult = new SolidBrush(rgb(0x043000)); scheme.ChatBackgroundHighlightedMessage = new SolidBrush(rgb(0x002e2b)); //scheme.ChatBackgroundResub = getColor(HSLColor.FromRGB(0.52f, 0.5f, 0.6f), 0.8f).ToBrush(); //scheme.ChatBackgroundWhisper = getColor(HSLColor.FromRGB(0.5f, 0.55f, 0.5f), 0.8f).ToBrush(); } scheme.Menu = getColor(gray, 0.90f).ToBrush(); scheme.MenuBorder = getColor(gray, 0.86f).ToPen(); scheme.ChatInputOuter = getColor(gray, 0.90f).ToBrush(); scheme.ChatInputBorder = getColor(gray, 0.86f).ToPen(); // Scroll scheme.ScrollbarThumb = getColor(gray, 0.8f).ToBrush(); // Highlights scheme.TabSelectedBG = highlight.WithLuminosity(0.5f).WithSaturation(0.5f).ToBrush(); scheme.TabHighlightedBG = highlight.WithLuminosity(0.8f).WithSaturation(0.5f).ToBrush(); scheme.TabNewMessageBG = highlight.WithLuminosity(0.9f).WithSaturation(0.5f).ToBrush(); scheme.TabNewMessageBG = new HatchBrush(HatchStyle.LightUpwardDiagonal, highlight.WithLuminosity(0.85f).WithSaturation(0.5f).ToColor(), highlight.WithLuminosity(0.95f).WithSaturation(0.5f).ToColor()); scheme.TextFocused = getColor(highlight, 0.25f).ToColor(); return(scheme); }
void ValidateClient(Connection newConn, string data) { try { if (State == ServerState.GameStarted) { SendOrderTo(newConn, "ServerError", "The game has already started"); DropClient(newConn); return; } var handshake = HandshakeResponse.Deserialize(data); if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password) { var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password"; SendOrderTo(newConn, "AuthenticationError", message); DropClient(newConn); return; } var client = new Session.Client { Name = EW.Settings.SanitizedPlayerName(handshake.Client.Name), IpAddress = ((IPEndPoint)newConn.Socket.RemoteEndPoint).Address.ToString(), Index = newConn.PlayerIndex, Slot = LobbyInfo.FirstEmptySlot(), PreferredColor = handshake.Client.PreferredColor, Color = handshake.Client.Color, Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.Invalid, IsAdmin = !LobbyInfo.Clients.Any(cl => cl.IsAdmin) }; if (client.IsObserver && !LobbyInfo.GlobalSettings.AllowSpectators) { SendOrderTo(newConn, "ServerError", "The game is full"); DropClient(newConn); return; } if (client.Slot != null) { SyncClientToPlayerReference(client, Map.Players.Players[client.Slot]); } else { client.Color = HSLColor.FromRGB(255, 255, 255); } if (ModData.Manifest.Id != handshake.Mod) { SendOrderTo(newConn, "ServerError", "Server is running an incompatible mod"); DropClient(newConn); return; } if (ModData.Manifest.Metadata.Version != handshake.Version && !LobbyInfo.GlobalSettings.AllowVersionMismatch) { SendOrderTo(newConn, "ServerError", "Server is running an incompatible version"); DropClient(newConn); return; } //Check if IP is banned var bans = Settings.Ban.Union(TempBans); if (bans.Contains(client.IpAddress)) { SendOrderTo(newConn, "ServerError", "You have been {0} from the server".F(Settings.Ban.Contains(client.IpAddress) ? "banned" : "temporarily banned")); DropClient(newConn); return; } //Promote connection to a valid client PreConns.Remove(newConn); Conns.Add(newConn); LobbyInfo.Clients.Add(client); newConn.Validated = true; var clientPing = new Session.ClientPing { Index = client.Index }; LobbyInfo.ClientPings.Add(clientPing); foreach (var t in serverTraits.WithInterface <IClientJoined>()) { t.ClientJoined(this, newConn); } SyncLobbyInfo(); if (LobbyInfo.NonBotClients.Count() > 1) { SendMessage("{0} has joined the game".F(client.Name)); } SendOrderTo(newConn, "Ping", WarGame.RunTime.ToString(CultureInfo.InvariantCulture)); if (Dedicated) { } if (Map.DefinesUnsafeCustomRules) { SendOrderTo(newConn, "Message", "This map contains custom rules.Game experience may change."); } if (!LobbyInfo.GlobalSettings.EnableSinglePlayer) { SendOrderTo(newConn, "Message", TwoHumansRequiredText); } else if (Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) { SendOrderTo(newConn, "Message", "Bots have been disabled on this map"); } } catch (Exception ex) { DropClient(newConn); } }
public Player(World world, Session.Client client, PlayerReference pr) { World = world; InternalName = pr.Name; PlayerReference = pr; // Real player or host-created bot if (client != null) { ClientIndex = client.Index; Color = client.Color; if (client.Bot != null) { var botInfo = world.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().First(b => b.Type == client.Bot); var botsOfSameType = world.LobbyInfo.Clients.Where(c => c.Bot == client.Bot).ToArray(); PlayerName = botsOfSameType.Length == 1 ? botInfo.Name : "{0} {1}".F(botInfo.Name, botsOfSameType.IndexOf(client) + 1); } else { PlayerName = client.Name; } BotType = client.Bot; Faction = ChooseFaction(world, client.Faction, !pr.LockFaction); DisplayFaction = ChooseDisplayFaction(world, client.Faction); } else { // Map player ClientIndex = 0; // Owned by the host (TODO: fix this) Color = pr.Color; PlayerName = pr.Name; NonCombatant = pr.NonCombatant; Playable = pr.Playable; Spectating = pr.Spectating; BotType = pr.Bot; Faction = ChooseFaction(world, pr.Faction, false); DisplayFaction = ChooseDisplayFaction(world, pr.Faction); } PlayerActor = world.CreateActor("Player", new TypeDictionary { new OwnerInit(this) }); Shroud = PlayerActor.Trait <Shroud>(); // Enable the bot logic on the host IsBot = BotType != null; if (IsBot && Game.IsHost) { var logic = PlayerActor.TraitsImplementing <IBot>().FirstOrDefault(b => b.Info.Type == BotType); if (logic == null) { Log.Write("debug", "Invalid bot type: {0}", BotType); } else { logic.Activate(this); } } stanceColors.Self = ChromeMetrics.Get <Color>("PlayerStanceColorSelf"); stanceColors.Allies = ChromeMetrics.Get <Color>("PlayerStanceColorAllies"); stanceColors.Enemies = ChromeMetrics.Get <Color>("PlayerStanceColorEnemies"); stanceColors.Neutrals = ChromeMetrics.Get <Color>("PlayerStanceColorNeutrals"); }
private void lbl_HSL_MouseDoubleClick(object sender, MouseEventArgs e) { Copy(HSLColor.FromColor(ldcPlate.SelectedColor)); }
// 임시 핫키 세팅과 연동 필요함 private void InitHotKey() { Keys[] semi_hkKeys = new Keys[] { Keys.Left, Keys.Right, Keys.Up, Keys.Down }; Point[] semi_hkDeltas = new Point[] { new Point(-1, 0), new Point(1, 0), new Point(0, -1), new Point(0, 1) }; for (int i = 0; i < semi_hkDeltas.Length; i++) { int idx = i; HotkeyManager.Register($"SEMI_{semi_hkKeys[idx].ToString()}", new HotKey() { Keys = new Keys[] { semi_hkKeys[idx] }, Action = () => { if (setting.SemiControl) { Point acPt = Point.Empty; if (HotkeyManager.IsShift()) { acPt = new Point(semi_hkDeltas[idx].X * 3, semi_hkDeltas[idx].Y * 3); } SetCursorPosDelta(semi_hkDeltas[idx] + (Size)acPt); } } }); } HotkeyManager.Register("Pause", new HotKey() { Keys = new Keys[] { Keys.None, Keys.F1 }, Action = () => { mPause = !mPause; } }); HotkeyManager.Register("ZoomIn", new HotKey() { Keys = new Keys[] { Keys.None, Keys.Add }, Action = () => { zoomSlider.Value += 1; } }); HotkeyManager.Register("ZoomOut", new HotKey() { Keys = new Keys[] { Keys.None, Keys.Subtract }, Action = () => { zoomSlider.Value -= 1; } }); HotkeyManager.Register("RGB", new HotKey() { Keys = new Keys[] { Keys.None, Keys.F2 }, Action = () => { AddColor(RGBColor.FromColor(ldcPlate.SelectedColor)); } }); HotkeyManager.Register("HEX", new HotKey() { Keys = new Keys[] { Keys.None, Keys.F3 }, Action = () => { AddColor(HEXColor.FromColor(ldcPlate.SelectedColor)); } }); HotkeyManager.Register("HSL", new HotKey() { Keys = new Keys[] { Keys.None, Keys.F4 }, Action = () => { AddColor(HSLColor.FromColor(ldcPlate.SelectedColor)); } }); HotkeyManager.Register("HSB", new HotKey() { Keys = new Keys[] { Keys.None, Keys.F5 }, Action = () => { AddColor(HSVColor.FromColor(ldcPlate.SelectedColor)); } }); }
public void TestHSLColorCanProduceAProperStringRepresentation() { var hslColor = new HSLColor(348, 0.91, 0.5); hslColor.ToString().Should().BeEquivalentTo("hsl(348°, 91%, 50%)"); }
public void TestHueIsDiscardedWhenLuminanceIs0Percent() { var black = new HSLColor(359, 0, 0); new[] { black.H, black.S, black.L }.Should().BeEquivalentTo(new byte[] { 0, 0, 0 }); }
void OnGUI() { GUILayout.BeginArea(new Rect(0, 0, this.position.width - 8, this.position.height)); GUILayout.Space(4); GUILayout.Label("CARTOON FX Easy Editor", EditorStyles.boldLabel); GUILayout.Label("Easily change properties of any Particle System!", EditorStyles.miniLabel); //---------------------------------------------------------------- EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); IncludeChildren = GUILayout.Toggle(IncludeChildren, new GUIContent("Include Children", "If checked, changes will affect every Particle Systems from each child of the selected GameObject(s)")); GUILayout.Space(90f); if (GUILayout.Button("Test Effect")) { foreach (GameObject go in Selection.gameObjects) { ParticleSystem[] systems = go.GetComponents <ParticleSystem>(); if (systems.Length == 0) { continue; } foreach (ParticleSystem system in systems) { system.Play(IncludeChildren); } } } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); //---------------------------------------------------------------- //Separator GUILayout.Box("", GUILayout.Width(this.position.width - 12), GUILayout.Height(3)); EditorGUI.BeginChangeCheck(); basicFoldout = EditorGUILayout.Foldout(basicFoldout, "BASIC PROPERTIES"); if (EditorGUI.EndChangeCheck()) { foldoutChanged = true; } if (basicFoldout) { //---------------------------------------------------------------- GUILayout.BeginHorizontal(); if (GUILayout.Button(new GUIContent("Scale Size", "Changes the size of the Particle System(s) and other values accordingly (speed, gravity, etc.)"), GUILayout.Width(120))) { applyScale(); } GUILayout.Label("Multiplier:", GUILayout.Width(110)); ScalingValue = EditorGUILayout.FloatField(ScalingValue); if (ScalingValue <= 0) { ScalingValue = 0.1f; } GUILayout.EndHorizontal(); //---------------------------------------------------------------- GUILayout.BeginHorizontal(); if (GUILayout.Button(new GUIContent("Set Duration", "Changes the duration of the Particle System(s) (if you want quicker or longer effects, 100% = default duration)"), GUILayout.Width(120))) { applyScaleLifetime(); } GUILayout.Label("Duration (%):", GUILayout.Width(110)); LTScalingValue = EditorGUILayout.FloatField(LTScalingValue); if (LTScalingValue < 0.1f) { LTScalingValue = 0.1f; } else if (LTScalingValue > 9999) { LTScalingValue = 9999; } GUILayout.EndHorizontal(); //---------------------------------------------------------------- GUILayout.Space(2); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(new GUIContent("Loop Effect", "Loop the effect (might not work properly on some effects such as explosions)"), EditorStyles.miniButtonLeft, GUILayout.Width(120))) { loopEffect(true); } if (GUILayout.Button(new GUIContent("Unloop Effect", "Remove looping from the effect"), EditorStyles.miniButtonRight, GUILayout.Width(120))) { loopEffect(false); } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(2); //---------------------------------------------------------------- } //Separator GUILayout.Box("", GUILayout.Width(this.position.width - 12), GUILayout.Height(3)); // GUILayout.Space(4); EditorGUI.BeginChangeCheck(); colorFoldout = EditorGUILayout.Foldout(colorFoldout, "COLOR MANIPULATIONS"); if (EditorGUI.EndChangeCheck()) { foldoutChanged = true; } if (colorFoldout) { //---------------------------------------------------------------- GUILayout.BeginHorizontal(); if (GUILayout.Button(new GUIContent("Set Start Color(s)", "Changes the color(s) of the Particle System(s)\nSecond Color is used when Start Color is 'Random Between Two Colors'."), GUILayout.Width(120))) { applyColor(); } ColorValue = EditorGUILayout.ColorField(ColorValue); ColorValue2 = EditorGUILayout.ColorField(ColorValue2); AffectAlpha = GUILayout.Toggle(AffectAlpha, new GUIContent("Alpha", "If checked, the alpha value will also be changed")); GUILayout.EndHorizontal(); //---------------------------------------------------------------- GUILayout.BeginHorizontal(); if (GUILayout.Button(new GUIContent("Tint Colors", "Tints the colors of the Particle System(s), including gradients!\n(preserving their saturation and lightness)"), GUILayout.Width(120))) { tintColor(); } TintColorValue = EditorGUILayout.ColorField(TintColorValue); TintColorValue = HSLColor.FromRGBA(TintColorValue).VividColor(); GUILayout.EndHorizontal(); //---------------------------------------------------------------- /* * GUILayout.BeginHorizontal(); * GUILayout.Label("Add/Substract Lightness:"); * * LightnessStep = EditorGUILayout.IntField(LightnessStep, GUILayout.Width(30)); * if(LightnessStep > 99) LightnessStep = 99; * else if(LightnessStep < 1) LightnessStep = 1; * GUILayout.Label("%"); * * if(GUILayout.Button("-", EditorStyles.miniButtonLeft, GUILayout.Width(22))) * { * addLightness(true); * } * if(GUILayout.Button("+", EditorStyles.miniButtonRight, GUILayout.Width(22))) * { * addLightness(false); * } * GUILayout.FlexibleSpace(); * GUILayout.EndHorizontal(); */ //---------------------------------------------------------------- GUILayout.Label("Color Modules to affect:"); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUI.color = TintStartColor ? ColorSelected : Color.white; if (GUILayout.Button(new GUIContent("Start Color", "If checked, the \"Start Color\" value(s) will be affected."), EditorStyles.toolbarButton, GUILayout.Width(70))) { TintStartColor = !TintStartColor; } GUI.color = TintColorModule ? ColorSelected : Color.white; if (GUILayout.Button(new GUIContent("Color over Lifetime", "If checked, the \"Color over Lifetime\" value(s) will be affected."), EditorStyles.toolbarButton, GUILayout.Width(110))) { TintColorModule = !TintColorModule; } GUI.color = TintColorSpeedModule ? ColorSelected : Color.white; if (GUILayout.Button(new GUIContent("Color by Speed", "If checked, the \"Color by Speed\" value(s) will be affected."), EditorStyles.toolbarButton, GUILayout.Width(100))) { TintColorSpeedModule = !TintColorSpeedModule; } GUI.color = Color.white; GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(4); //---------------------------------------------------------------- } //Separator GUILayout.Box("", GUILayout.Width(this.position.width - 12), GUILayout.Height(3)); // GUILayout.Space(6); //---------------------------------------------------------------- EditorGUI.BeginChangeCheck(); copyFoldout = EditorGUILayout.Foldout(copyFoldout, "COPY MODULES"); if (EditorGUI.EndChangeCheck()) { foldoutChanged = true; } if (copyFoldout) { GUILayout.Label("Copy properties from a Particle System to others!", EditorStyles.miniLabel); GUILayout.BeginHorizontal(); GUILayout.Label("Source Object:", GUILayout.Width(110)); sourceObject = (ParticleSystem)EditorGUILayout.ObjectField(sourceObject, typeof(ParticleSystem), true); GUILayout.EndHorizontal(); EditorGUILayout.LabelField("Modules to Copy:"); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("ALL", EditorStyles.miniButtonLeft, GUILayout.Width(120))) { for (int i = 0; i < b_modules.Length; i++) { b_modules[i] = true; } } if (GUILayout.Button("NONE", EditorStyles.miniButtonRight, GUILayout.Width(120))) { for (int i = 0; i < b_modules.Length; i++) { b_modules[i] = false; } } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(4); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUI.color = b_modules[0] ? ColorSelected : Color.white; if (GUILayout.Button("Initial", EditorStyles.toolbarButton, GUILayout.Width(70))) { b_modules[0] = !b_modules[0]; } GUI.color = b_modules[1] ? ColorSelected : Color.white; if (GUILayout.Button("Emission", EditorStyles.toolbarButton, GUILayout.Width(70))) { b_modules[1] = !b_modules[1]; } GUI.color = b_modules[2] ? ColorSelected : Color.white; if (GUILayout.Button("Shape", EditorStyles.toolbarButton, GUILayout.Width(70))) { b_modules[2] = !b_modules[2]; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUI.color = b_modules[3] ? ColorSelected : Color.white; if (GUILayout.Button("Velocity", EditorStyles.toolbarButton, GUILayout.Width(70))) { b_modules[3] = !b_modules[3]; } GUI.color = b_modules[4] ? ColorSelected : Color.white; if (GUILayout.Button("Limit Velocity", EditorStyles.toolbarButton, GUILayout.Width(100))) { b_modules[4] = !b_modules[4]; } GUI.color = b_modules[5] ? ColorSelected : Color.white; if (GUILayout.Button("Force", EditorStyles.toolbarButton, GUILayout.Width(70))) { b_modules[5] = !b_modules[5]; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUI.color = b_modules[6] ? ColorSelected : Color.white; if (GUILayout.Button("Color over Lifetime", EditorStyles.toolbarButton, GUILayout.Width(120))) { b_modules[6] = !b_modules[6]; } GUI.color = b_modules[7] ? ColorSelected : Color.white; if (GUILayout.Button("Color by Speed", EditorStyles.toolbarButton, GUILayout.Width(120))) { b_modules[7] = !b_modules[7]; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUI.color = b_modules[8] ? ColorSelected : Color.white; if (GUILayout.Button("Size over Lifetime", EditorStyles.toolbarButton, GUILayout.Width(120))) { b_modules[8] = !b_modules[8]; } GUI.color = b_modules[9] ? ColorSelected : Color.white; if (GUILayout.Button("Size by Speed", EditorStyles.toolbarButton, GUILayout.Width(120))) { b_modules[9] = !b_modules[9]; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUI.color = b_modules[10] ? ColorSelected : Color.white; if (GUILayout.Button("Rotation over Lifetime", EditorStyles.toolbarButton, GUILayout.Width(120))) { b_modules[10] = !b_modules[10]; } GUI.color = b_modules[11] ? ColorSelected : Color.white; if (GUILayout.Button("Rotation by Speed", EditorStyles.toolbarButton, GUILayout.Width(120))) { b_modules[11] = !b_modules[11]; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUI.color = b_modules[12] ? ColorSelected : Color.white; if (GUILayout.Button("Collision", EditorStyles.toolbarButton, GUILayout.Width(100))) { b_modules[12] = !b_modules[12]; } GUI.color = b_modules[13] ? ColorSelected : Color.white; if (GUILayout.Button("Sub Emitters", EditorStyles.toolbarButton, GUILayout.Width(100))) { b_modules[13] = !b_modules[13]; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUI.color = b_modules[14] ? ColorSelected : Color.white; if (GUILayout.Button("Texture Animation", EditorStyles.toolbarButton, GUILayout.Width(110))) { b_modules[14] = !b_modules[14]; } GUI.color = b_modules[15] ? ColorSelected : Color.white; if (GUILayout.Button("Renderer", EditorStyles.toolbarButton, GUILayout.Width(90))) { b_modules[15] = !b_modules[15]; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUI.color = Color.white; GUILayout.Space(4); if (GUILayout.Button("Copy properties to selected Object(s)")) { bool foundPs = false; foreach (GameObject go in Selection.gameObjects) { ParticleSystem[] systems; if (IncludeChildren) { systems = go.GetComponentsInChildren <ParticleSystem>(true); } else { systems = go.GetComponents <ParticleSystem>(); } if (systems.Length == 0) { continue; } foundPs = true; foreach (ParticleSystem system in systems) { CopyModules(sourceObject, system); } } if (!foundPs) { Debug.LogWarning("CartoonFX Easy Editor: No Particle System found in the selected GameObject(s)!"); } } } //---------------------------------------------------------------- GUILayout.Space(8); //Resize window if (foldoutChanged && Event.current.type == EventType.repaint) { foldoutChanged = false; Rect r = GUILayoutUtility.GetLastRect(); this.minSize = new Vector2(300, r.y + 8); this.maxSize = new Vector2(300, r.y + 8); this.position = new Rect(this.position.x, this.position.y, 300, r.y + 8); } GUILayout.EndArea(); }
public override bool Powerup_PerformFrame(BCBlockGameState gamestate) { Random rg = BCBlockGameState.rgen; Color usecolor = new HSLColor(BCBlockGameState.rgen.NextDouble() * 240, 240, 120); //select a random position. RectangleF baserect = GetRectangleF(); PointF randompos = new PointF(baserect.Left + (float)(baserect.Width * rg.NextDouble()), baserect.Top + (float)(baserect.Height * rg.NextDouble())); PointF RandomVelocity = new PointF((float)rg.NextDouble() * 0.5f - 0.25f, (float)rg.NextDouble() * 0.5f - 0.25f); Sparkle sp = new Sparkle(randompos, RandomVelocity, usecolor); sp.MaxRadius = (float)(1 + rg.NextDouble() * 4); gamestate.Particles.Add(sp); return false; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { HSLColor selectedColor = (HSLColor)value; return((int)(selectedColor.Luminosity)); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var selectedColor = (HSLColor)value; Color convertedColor = new HSLColor(selectedColor.Hue, selectedColor.Saturation, 0.20f * 240); return Color.FromArgb(255, convertedColor.R, convertedColor.G, convertedColor.B); }
void ValidateClient(Connection newConn, string data) { try { if (State == ServerState.GameStarted) { Log.Write("server", "Rejected connection from {0}; game is already started.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "The game has already started"); DropClient(newConn); return; } var handshake = HandshakeResponse.Deserialize(data); if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password) { var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password"; SendOrderTo(newConn, "AuthenticationError", message); DropClient(newConn); return; } var client = new Session.Client { Name = OpenRA.Settings.SanitizedPlayerName(handshake.Client.Name), IpAddress = ((IPEndPoint)newConn.Socket.RemoteEndPoint).Address.ToString(), Index = newConn.PlayerIndex, Slot = LobbyInfo.FirstEmptySlot(), PreferredColor = handshake.Client.PreferredColor, Color = handshake.Client.Color, Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.Invalid, IsAdmin = !LobbyInfo.Clients.Any(c1 => c1.IsAdmin) }; if (client.IsObserver && !LobbyInfo.GlobalSettings.AllowSpectators) { SendOrderTo(newConn, "ServerError", "The game is full"); DropClient(newConn); return; } if (client.Slot != null) { SyncClientToPlayerReference(client, Map.Players.Players[client.Slot]); } else { client.Color = HSLColor.FromRGB(255, 255, 255); } if (ModData.Manifest.Id != handshake.Mod) { Log.Write("server", "Rejected connection from {0}; mods do not match.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible mod"); DropClient(newConn); return; } if (ModData.Manifest.Metadata.Version != handshake.Version && !LobbyInfo.GlobalSettings.AllowVersionMismatch) { Log.Write("server", "Rejected connection from {0}; Not running the same version.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible version"); DropClient(newConn); return; } // Check if IP is banned var bans = Settings.Ban.Union(TempBans); if (bans.Contains(client.IpAddress)) { Log.Write("server", "Rejected connection from {0}; Banned.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "You have been {0} from the server".F(Settings.Ban.Contains(client.IpAddress) ? "banned" : "temporarily banned")); DropClient(newConn); return; } Action completeConnection = () => { // Promote connection to a valid client PreConns.Remove(newConn); Conns.Add(newConn); LobbyInfo.Clients.Add(client); newConn.Validated = true; var clientPing = new Session.ClientPing { Index = client.Index }; LobbyInfo.ClientPings.Add(clientPing); Log.Write("server", "Client {0}: Accepted connection from {1}.", newConn.PlayerIndex, newConn.Socket.RemoteEndPoint); if (client.Fingerprint != null) { Log.Write("server", "Client {0}: Player fingerprint is {1}.", newConn.PlayerIndex, client.Fingerprint); } foreach (var t in serverTraits.WithInterface <IClientJoined>()) { t.ClientJoined(this, newConn); } SyncLobbyInfo(); Log.Write("server", "{0} ({1}) has joined the game.", client.Name, newConn.Socket.RemoteEndPoint); // Report to all other players SendMessage("{0} has joined the game.".F(client.Name), newConn); // Send initial ping SendOrderTo(newConn, "Ping", Game.RunTime.ToString(CultureInfo.InvariantCulture)); if (Dedicated) { var motdFile = Platform.ResolvePath(Platform.SupportDirPrefix, "motd.txt"); if (!File.Exists(motdFile)) { File.WriteAllText(motdFile, "Welcome, have fun and good luck!"); } var motd = File.ReadAllText(motdFile); if (!string.IsNullOrEmpty(motd)) { SendOrderTo(newConn, "Message", motd); } } if (Map.DefinesUnsafeCustomRules) { SendOrderTo(newConn, "Message", "This map contains custom rules. Game experience may change."); } if (!LobbyInfo.GlobalSettings.EnableSingleplayer) { SendOrderTo(newConn, "Message", TwoHumansRequiredText); } else if (Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) { SendOrderTo(newConn, "Message", "Bots have been disabled on this map."); } }; if (!string.IsNullOrEmpty(handshake.Fingerprint) && !string.IsNullOrEmpty(handshake.AuthSignature)) { waitingForAuthenticationCallback++; Action <DownloadDataCompletedEventArgs> onQueryComplete = i => { PlayerProfile profile = null; if (i.Error == null) { try { var yaml = MiniYaml.FromString(Encoding.UTF8.GetString(i.Result)).First(); if (yaml.Key == "Player") { profile = FieldLoader.Load <PlayerProfile>(yaml.Value); var publicKey = Encoding.ASCII.GetString(Convert.FromBase64String(profile.PublicKey)); var parameters = CryptoUtil.DecodePEMPublicKey(publicKey); if (!profile.KeyRevoked && CryptoUtil.VerifySignature(parameters, newConn.AuthToken, handshake.AuthSignature)) { client.Fingerprint = handshake.Fingerprint; Log.Write("server", "{0} authenticated as {1} (UID {2})", newConn.Socket.RemoteEndPoint, profile.ProfileName, profile.ProfileID); } else if (profile.KeyRevoked) { Log.Write("server", "{0} failed to authenticate as {1} (key revoked)", newConn.Socket.RemoteEndPoint, handshake.Fingerprint); } else { Log.Write("server", "{0} failed to authenticate as {1} (signature verification failed)", newConn.Socket.RemoteEndPoint, handshake.Fingerprint); } } else { Log.Write("server", "{0} failed to authenticate as {1} (invalid server response: `{2}` is not `Player`)", newConn.Socket.RemoteEndPoint, handshake.Fingerprint, yaml.Key); } } catch (Exception ex) { Log.Write("server", "{0} failed to authenticate as {1} (exception occurred)", newConn.Socket.RemoteEndPoint, handshake.Fingerprint); Log.Write("server", ex.ToString()); } } else { Log.Write("server", "{0} failed to authenticate as {1} (server error: `{2}`)", newConn.Socket.RemoteEndPoint, handshake.Fingerprint, i.Error); } delayedActions.Add(() => { if (Dedicated && Settings.RequireAuthIDs.Any() && (profile == null || !Settings.RequireAuthIDs.Contains(profile.ProfileID))) { Log.Write("server", "Rejected connection from {0}; Not in server whitelist.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "You are not authenticated for this server"); DropClient(newConn); } else { completeConnection(); } waitingForAuthenticationCallback--; }, 0); }; new Download(playerDatabase.Profile + handshake.Fingerprint, _ => { }, onQueryComplete); } else { if (Dedicated && Settings.RequireAuthIDs.Any()) { Log.Write("server", "Rejected connection from {0}; Not authenticated and whitelist is set.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "You are not authenticated for this server"); DropClient(newConn); } else { completeConnection(); } } } catch (Exception ex) { Log.Write("server", "Dropping connection {0} because an error occurred:", newConn.Socket.RemoteEndPoint); Log.Write("server", ex.ToString()); DropClient(newConn); } }
private void chooseimage() { //April 6th, birthday of windows 3.1 if (DateTime.Now.Month == 4 && DateTime.Now.Day == 6) { useBackground = panWin31.BackgroundImage; } else { //select a random start image from the available start images. GetSplashImages(); Image[] selectfrom = SplashImages; Image useimage = selectfrom[rgen.Next(selectfrom.Length)]; useBackground = useimage; } //new as of July 14th 2011: colourize to a random hue 50% of the time. if (rgen.NextDouble() > 0.5d) { //choose a random colour... Color colourizeto = new HSLColor(rgen.NextDouble() * 240, 240, 120); ImageAttributes attribcolourize = new ImageAttributes(); QColorMatrix qc = new QColorMatrix(); qc.RotateHue((float)(rgen.NextDouble()*255)); attribcolourize.SetColorMatrix(qc.ToColorMatrix()); // ColorMatrices.AddColourizer(attribcolourize, colourizeto); useBackground = BCBlockGameState.AppyImageAttributes(useBackground, attribcolourize); } Graphics drawtoit = Graphics.FromImage(useBackground); drawtoit.DrawImageUnscaled(RegUnregImage, 2, 2); drawtoit.Dispose(); }
void ValidateClient(Connection newConn, string data) { try { if (State == ServerState.GameStarted) { Log.Write("server", "Rejected connection from {0}; game is already started.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "The game has already started"); DropClient(newConn); return; } var handshake = HandshakeResponse.Deserialize(data); if (!string.IsNullOrEmpty(Settings.Password) && handshake.Password != Settings.Password) { var message = string.IsNullOrEmpty(handshake.Password) ? "Server requires a password" : "Incorrect password"; SendOrderTo(newConn, "AuthenticationError", message); DropClient(newConn); return; } var client = new Session.Client { Name = OpenRA.Settings.SanitizedPlayerName(handshake.Client.Name), IpAddress = ((IPEndPoint)newConn.Socket.RemoteEndPoint).Address.ToString(), Index = newConn.PlayerIndex, Slot = LobbyInfo.FirstEmptySlot(), PreferredColor = handshake.Client.PreferredColor, Color = handshake.Client.Color, Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.Invalid, IsAdmin = !LobbyInfo.Clients.Any(c1 => c1.IsAdmin) }; if (client.IsObserver && !LobbyInfo.GlobalSettings.AllowSpectators) { SendOrderTo(newConn, "ServerError", "The game is full"); DropClient(newConn); return; } if (client.Slot != null) { SyncClientToPlayerReference(client, Map.Players.Players[client.Slot]); } else { client.Color = HSLColor.FromRGB(255, 255, 255); } if (ModData.Manifest.Id != handshake.Mod) { Log.Write("server", "Rejected connection from {0}; mods do not match.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible mod"); DropClient(newConn); return; } if (ModData.Manifest.Metadata.Version != handshake.Version && !LobbyInfo.GlobalSettings.AllowVersionMismatch) { Log.Write("server", "Rejected connection from {0}; Not running the same version.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "Server is running an incompatible version"); DropClient(newConn); return; } // Check if IP is banned var bans = Settings.Ban.Union(TempBans); if (bans.Contains(client.IpAddress)) { Log.Write("server", "Rejected connection from {0}; Banned.", newConn.Socket.RemoteEndPoint); SendOrderTo(newConn, "ServerError", "You have been {0} from the server".F(Settings.Ban.Contains(client.IpAddress) ? "banned" : "temporarily banned")); DropClient(newConn); return; } // Promote connection to a valid client PreConns.Remove(newConn); Conns.Add(newConn); LobbyInfo.Clients.Add(client); var clientPing = new Session.ClientPing { Index = client.Index }; LobbyInfo.ClientPings.Add(clientPing); Log.Write("server", "Client {0}: Accepted connection from {1}.", newConn.PlayerIndex, newConn.Socket.RemoteEndPoint); foreach (var t in serverTraits.WithInterface <IClientJoined>()) { t.ClientJoined(this, newConn); } SyncLobbyInfo(); Log.Write("server", "{0} ({1}) has joined the game.", client.Name, newConn.Socket.RemoteEndPoint); if (Dedicated || !LobbyInfo.IsSinglePlayer) { SendMessage("{0} has joined the game.".F(client.Name)); } // Send initial ping SendOrderTo(newConn, "Ping", Game.RunTime.ToString(CultureInfo.InvariantCulture)); if (Dedicated) { var motdFile = Platform.ResolvePath("^", "motd.txt"); if (!File.Exists(motdFile)) { File.WriteAllText(motdFile, "Welcome, have fun and good luck!"); } var motd = File.ReadAllText(motdFile); if (!string.IsNullOrEmpty(motd)) { SendOrderTo(newConn, "Message", motd); } } if (!LobbyInfo.IsSinglePlayer && Map.DefinesUnsafeCustomRules) { SendOrderTo(newConn, "Message", "This map contains custom rules. Game experience may change."); } if (!LobbyInfo.GlobalSettings.EnableSingleplayer) { SendOrderTo(newConn, "Message", TwoHumansRequiredText); } else if (Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) { SendOrderTo(newConn, "Message", "Bots have been disabled on this map."); } if (handshake.Mod == "{DEV_VERSION}") { SendMessage("{0} is running an unversioned development build, ".F(client.Name) + "and may desynchronize the game state if they have incompatible rules."); } } catch (Exception ex) { Log.Write("server", "Dropping connection {0} because an error occurred:", newConn.Socket.RemoteEndPoint); Log.Write("server", ex.ToString()); DropClient(newConn); } }
private Color getrndcolor() { var hscolor = new HSLColor(rgen.NextDouble() * 240, 240, 120); return(hscolor); }
public bool Equals(HSLColor hsl) { return((this.H == hsl.H) && (this.S == hsl.S) && (this.L == hsl.L)); }
public static Color GetContrastColor(Color fgColor, Color bgDark, Color bgLight) { var fg = new HSLColor(fgColor); return(fg.RGB == Color.White || fg.L > 80 ? bgDark : bgLight); }
public bool InterpretCommand(S server, Connection conn, Session.Client client, string cmd) { if (!ValidateCommand(server, conn, client, cmd)) { return(false); } var dict = new Dictionary <string, Func <string, bool> > { { "state", s => { var state = Session.ClientState.Invalid; if (!Enum <Session.ClientState> .TryParse(s, false, out state)) { server.SendOrderTo(conn, "Message", "Malformed state command"); return(true); } client.State = state; Log.Write("server", "Player @{0} is {1}", conn.socket.RemoteEndPoint, client.State); server.SyncLobbyClients(); CheckAutoStart(server); return(true); } }, { "startgame", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can start the game"); return(true); } if (server.LobbyInfo.Slots.Any(sl => sl.Value.Required && server.LobbyInfo.ClientInSlot(sl.Key) == null)) { server.SendOrderTo(conn, "Message", "Unable to start the game until required slots are full."); return(true); } server.StartGame(); return(true); } }, { "slot", s => { if (!server.LobbyInfo.Slots.ContainsKey(s)) { Log.Write("server", "Invalid slot: {0}", s); return(false); } var slot = server.LobbyInfo.Slots[s]; if (slot.Closed || server.LobbyInfo.ClientInSlot(s) != null) { return(false); } client.Slot = s; S.SyncClientToPlayerReference(client, server.Map.Players[s]); server.SyncLobbyClients(); CheckAutoStart(server); return(true); } }, { "allow_spectators", s => { if (bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllowSpectators)) { server.SyncLobbyGlobalSettings(); return(true); } else { server.SendOrderTo(conn, "Message", "Malformed allow_spectate command"); return(true); } } }, { "spectate", s => { if (server.LobbyInfo.GlobalSettings.AllowSpectators || client.IsAdmin) { client.Slot = null; client.SpawnPoint = 0; client.Color = HSLColor.FromRGB(255, 255, 255); server.SyncLobbyClients(); return(true); } else { return(false); } } }, { "slot_close", s => { if (!ValidateSlotCommand(server, conn, client, s, true)) { return(false); } // kick any player that's in the slot var occupant = server.LobbyInfo.ClientInSlot(s); if (occupant != null) { if (occupant.Bot != null) { server.LobbyInfo.Clients.Remove(occupant); server.SyncLobbyClients(); var ping = server.LobbyInfo.PingFromClient(occupant); server.LobbyInfo.ClientPings.Remove(ping); server.SyncClientPing(); } else { var occupantConn = server.Conns.FirstOrDefault(c => c.PlayerIndex == occupant.Index); if (occupantConn != null) { server.SendOrderTo(occupantConn, "ServerError", "Your slot was closed by the host"); server.DropClient(occupantConn); } } } server.LobbyInfo.Slots[s].Closed = true; server.SyncLobbySlots(); return(true); } }, { "slot_open", s => { if (!ValidateSlotCommand(server, conn, client, s, true)) { return(false); } var slot = server.LobbyInfo.Slots[s]; slot.Closed = false; server.SyncLobbySlots(); // Slot may have a bot in it var occupant = server.LobbyInfo.ClientInSlot(s); if (occupant != null && occupant.Bot != null) { server.LobbyInfo.Clients.Remove(occupant); var ping = server.LobbyInfo.PingFromClient(occupant); server.LobbyInfo.ClientPings.Remove(ping); } server.SyncLobbyClients(); return(true); } }, { "slot_bot", s => { var parts = s.Split(' '); if (parts.Length < 3) { server.SendOrderTo(conn, "Message", "Malformed slot_bot command"); return(true); } if (!ValidateSlotCommand(server, conn, client, parts[0], true)) { return(false); } var slot = server.LobbyInfo.Slots[parts[0]]; var bot = server.LobbyInfo.ClientInSlot(parts[0]); int controllerClientIndex; if (!Exts.TryParseIntegerInvariant(parts[1], out controllerClientIndex)) { Log.Write("server", "Invalid bot controller client index: {0}", parts[1]); return(false); } var botType = parts.Skip(2).JoinWith(" "); // Invalid slot if (bot != null && bot.Bot == null) { server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client"); return(true); } slot.Closed = false; if (bot == null) { // Create a new bot bot = new Session.Client() { Index = server.ChooseFreePlayerIndex(), Name = botType, Bot = botType, Slot = parts[0], Country = "random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady, BotControllerClientIndex = controllerClientIndex }; // pick a random color for the bot var hue = (byte)server.Random.Next(255); var sat = (byte)server.Random.Next(255); var lum = (byte)server.Random.Next(51, 255); bot.Color = bot.PreferredColor = new HSLColor(hue, sat, lum); server.LobbyInfo.Clients.Add(bot); } else { // Change the type of the existing bot bot.Name = botType; bot.Bot = botType; } S.SyncClientToPlayerReference(bot, server.Map.Players[parts[0]]); server.SyncLobbyClients(); server.SyncLobbySlots(); return(true); } }, { "map", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can change the map"); return(true); } if (server.ModData.MapCache[s].Status != MapStatus.Available) { server.SendOrderTo(conn, "Message", "Map was not found on server"); return(true); } server.LobbyInfo.GlobalSettings.Map = s; var oldSlots = server.LobbyInfo.Slots.Keys.ToArray(); LoadMap(server); SetDefaultDifficulty(server); // Reset client states foreach (var c in server.LobbyInfo.Clients) { c.State = Session.ClientState.Invalid; } // Reassign players into new slots based on their old slots: // - Observers remain as observers // - Players who now lack a slot are made observers // - Bots who now lack a slot are dropped var slots = server.LobbyInfo.Slots.Keys.ToArray(); int i = 0; foreach (var os in oldSlots) { var c = server.LobbyInfo.ClientInSlot(os); if (c == null) { continue; } c.SpawnPoint = 0; c.Slot = i < slots.Length ? slots[i++] : null; if (c.Slot != null) { // Remove Bot from slot if slot forbids bots if (c.Bot != null && !server.Map.Players[c.Slot].AllowBots) { server.LobbyInfo.Clients.Remove(c); } S.SyncClientToPlayerReference(c, server.Map.Players[c.Slot]); } else if (c.Bot != null) { server.LobbyInfo.Clients.Remove(c); } } server.SyncLobbyInfo(); return(true); } }, { "fragilealliance", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if (server.Map.Options.FragileAlliances.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled alliance configuration"); return(true); } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.FragileAlliances); server.SyncLobbyGlobalSettings(); return(true); } }, { "allowcheats", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if (server.Map.Options.Cheats.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled cheat configuration"); return(true); } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllowCheats); server.SyncLobbyGlobalSettings(); return(true); } }, { "shroud", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if (server.Map.Options.Shroud.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled shroud configuration"); return(true); } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Shroud); server.SyncLobbyGlobalSettings(); return(true); } }, { "fog", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if (server.Map.Options.Fog.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled fog configuration"); return(true); } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Fog); server.SyncLobbyGlobalSettings(); return(true); } }, { "assignteams", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } int teamCount; if (!Exts.TryParseIntegerInvariant(s, out teamCount)) { server.SendOrderTo(conn, "Message", "Number of teams could not be parsed: {0}".F(s)); return(true); } var maxTeams = (server.LobbyInfo.Clients.Count(c => c.Slot != null) + 1) / 2; teamCount = teamCount.Clamp(0, maxTeams); var players = server.LobbyInfo.Slots .Select(slot => server.LobbyInfo.ClientInSlot(slot.Key)) .Where(c => c != null && !server.LobbyInfo.Slots[c.Slot].LockTeam); var assigned = 0; var playerCount = players.Count(); foreach (var player in players) { // Free for all if (teamCount == 0) { player.Team = 0; } // Humans vs Bots else if (teamCount == 1) { player.Team = player.Bot == null ? 1 : 2; } else { player.Team = assigned++ *teamCount / playerCount + 1; } } server.SyncLobbyClients(); return(true); } }, { "crates", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if (server.Map.Options.Crates.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled crate configuration"); return(true); } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.Crates); server.SyncLobbyGlobalSettings(); return(true); } }, { "allybuildradius", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if (server.Map.Options.AllyBuildRadius.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled ally build radius configuration"); return(true); } bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllyBuildRadius); server.SyncLobbyGlobalSettings(); return(true); } }, { "difficulty", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if (s != null && !server.Map.Options.Difficulties.Contains(s)) { server.SendOrderTo(conn, "Message", "Unsupported difficulty selected: {0}".F(s)); server.SendOrderTo(conn, "Message", "Supported difficulties: {0}".F(server.Map.Options.Difficulties.JoinWith(","))); return(true); } server.LobbyInfo.GlobalSettings.Difficulty = s; server.SyncLobbyGlobalSettings(); return(true); } }, { "startingunits", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if (!server.Map.Options.ConfigurableStartingUnits) { server.SendOrderTo(conn, "Message", "Map has disabled start unit configuration"); return(true); } server.LobbyInfo.GlobalSettings.StartingUnitsClass = s; server.SyncLobbyGlobalSettings(); return(true); } }, { "startingcash", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if (server.Map.Options.StartingCash.HasValue) { server.SendOrderTo(conn, "Message", "Map has disabled cash configuration"); return(true); } server.LobbyInfo.GlobalSettings.StartingCash = Exts.ParseIntegerInvariant(s); server.SyncLobbyGlobalSettings(); return(true); } }, { "techlevel", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option"); return(true); } if (server.Map.Options.TechLevel != null) { server.SendOrderTo(conn, "Message", "Map has disabled Tech configuration"); return(true); } server.LobbyInfo.GlobalSettings.TechLevel = s; server.SyncLobbyInfo(); return(true); } }, { "kick", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can kick players"); return(true); } var split = s.Split(' '); if (split.Length < 2) { server.SendOrderTo(conn, "Message", "Malformed kick command"); return(true); } int kickClientID; Exts.TryParseIntegerInvariant(split[0], out kickClientID); var kickConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == kickClientID); if (kickConn == null) { server.SendOrderTo(conn, "Message", "Noone in that slot."); return(true); } var kickConnIP = server.GetClient(kickConn).IpAddress; Log.Write("server", "Kicking client {0} as requested", kickClientID); server.SendOrderTo(kickConn, "ServerError", "You have been kicked from the server"); server.DropClient(kickConn); bool tempBan; bool.TryParse(split[1], out tempBan); if (tempBan) { Log.Write("server", "Temporarily banning client {0} ({1}) as requested", kickClientID, kickConnIP); server.TempBans.Add(kickConnIP); } server.SyncLobbyClients(); server.SyncLobbySlots(); return(true); } }, { "name", s => { Log.Write("server", "Player@{0} is now known as {1}", conn.socket.RemoteEndPoint, s); client.Name = s; server.SyncLobbyClients(); return(true); } }, { "race", s => { var parts = s.Split(' '); var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) { return(true); } // Map has disabled race changes if (server.LobbyInfo.Slots[targetClient.Slot].LockRace) { return(true); } targetClient.Country = parts[1]; server.SyncLobbyClients(); return(true); } }, { "team", s => { var parts = s.Split(' '); var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) { return(true); } // Map has disabled team changes if (server.LobbyInfo.Slots[targetClient.Slot].LockTeam) { return(true); } int team; if (!Exts.TryParseIntegerInvariant(parts[1], out team)) { Log.Write("server", "Invalid team: {0}", s); return(false); } targetClient.Team = team; server.SyncLobbyClients(); return(true); } }, { "spawn", s => { var parts = s.Split(' '); var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) { return(true); } // Spectators don't need a spawnpoint if (targetClient.Slot == null) { return(true); } // Map has disabled spawn changes if (server.LobbyInfo.Slots[targetClient.Slot].LockSpawn) { return(true); } int spawnPoint; if (!Exts.TryParseIntegerInvariant(parts[1], out spawnPoint) || spawnPoint <0 || spawnPoint> server.Map.GetSpawnPoints().Length) { Log.Write("server", "Invalid spawn point: {0}", parts[1]); return(true); } if (server.LobbyInfo.Clients.Where(cc => cc != client).Any(cc => (cc.SpawnPoint == spawnPoint) && (cc.SpawnPoint != 0))) { server.SendOrderTo(conn, "Message", "You can't be at the same spawn point as another player"); return(true); } targetClient.SpawnPoint = spawnPoint; server.SyncLobbyClients(); return(true); } }, { "color", s => { var parts = s.Split(' '); var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) { return(true); } // Spectator or map has disabled color changes if (targetClient.Slot == null || server.LobbyInfo.Slots[targetClient.Slot].LockColor) { return(true); } var ci = parts[1].Split(',').Select(cc => Exts.ParseIntegerInvariant(cc)).ToArray(); targetClient.Color = targetClient.PreferredColor = new HSLColor((byte)ci[0], (byte)ci[1], (byte)ci[2]); server.SyncLobbyClients(); return(true); } } }; var cmdName = cmd.Split(' ').First(); var cmdValue = cmd.Split(' ').Skip(1).JoinWith(" "); Func <string, bool> a; if (!dict.TryGetValue(cmdName, out a)) { return(false); } return(a(cmdValue)); }
private void chooseimage() { //April 6th, birthday of windows 3.1 if (DateTime.Now.Month == 4 && DateTime.Now.Day == 6) { useBackground = panWin31.BackgroundImage; } else { //select a random start image from the available start images. Image[] selectfrom = new Image[] { panStandard.BackgroundImage, panStandard2.BackgroundImage,panStandard3.BackgroundImage }; Image useimage = selectfrom[rgen.Next(selectfrom.Length)]; useBackground = useimage; } //new as of July 14th 2011: colourize to a random hue 50% of the time. if (rgen.NextDouble() > 0.5d) { //choose a random colour... Color colourizeto = new HSLColor(rgen.NextDouble() * 240, 240, 120); ImageAttributes attribcolourize = new ImageAttributes(); attribcolourize.SetColorMatrix(ColorMatrices.GetColourizer((float)(colourizeto.R)/255, (float)(colourizeto.G)/255, (float)(colourizeto.B)/255)); useBackground = BCBlockGameState.AppyImageAttributes(useBackground, attribcolourize); } }
public static object GetValue(string fieldName, Type fieldType, MiniYaml yaml, MemberInfo field) { var value = yaml.Value; if (value != null) { value = value.Trim(); } if (fieldType == typeof(int)) { int res; if (Exts.TryParseIntegerInvariant(value, out res)) { return(res); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(ushort)) { ushort res; if (ushort.TryParse(value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out res)) { return(res); } return(InvalidValueAction(value, fieldType, fieldName)); } if (fieldType == typeof(long)) { long res; if (long.TryParse(value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out res)) { return(res); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(float)) { float res; if (value != null && float.TryParse(value.Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res)) { return(res * (value.Contains('%') ? 0.01f : 1f)); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(decimal)) { decimal res; if (value != null && decimal.TryParse(value.Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res)) { return(res * (value.Contains('%') ? 0.01m : 1m)); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(string)) { if (field != null && MemberHasTranslateAttribute[field] && value != null) { return(Regex.Replace(value, "@[^@]+@", m => Translate(m.Value.Substring(1, m.Value.Length - 2)), RegexOptions.Compiled)); } return(value); } else if (fieldType == typeof(Color)) { Color color; if (value != null && HSLColor.TryParseRGB(value, out color)) { return(color); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(Color[])) { if (value != null) { var parts = value.Split(','); var colors = new Color[parts.Length]; for (var i = 0; i < colors.Length; i++) { if (!HSLColor.TryParseRGB(parts[i], out colors[i])) { return(InvalidValueAction(value, fieldType, fieldName)); } } return(colors); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(HSLColor)) { if (value != null) { Color rgb; if (HSLColor.TryParseRGB(value, out rgb)) { return(new HSLColor(rgb)); } // Allow old HSLColor/ColorRamp formats to be parsed as HSLColor var parts = value.Split(','); if (parts.Length == 3 || parts.Length == 4) { return(new HSLColor( (byte)Exts.ParseIntegerInvariant(parts[0]).Clamp(0, 255), (byte)Exts.ParseIntegerInvariant(parts[1]).Clamp(0, 255), (byte)Exts.ParseIntegerInvariant(parts[2]).Clamp(0, 255))); } } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(Hotkey)) { Hotkey res; if (Hotkey.TryParse(value, out res)) { return(res); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(HotkeyReference)) { return(Game.ModData.Hotkeys[value]); } else if (fieldType == typeof(WDist)) { WDist res; if (WDist.TryParse(value, out res)) { return(res); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(WVec)) { if (value != null) { var parts = value.Split(','); if (parts.Length == 3) { WDist rx, ry, rz; if (WDist.TryParse(parts[0], out rx) && WDist.TryParse(parts[1], out ry) && WDist.TryParse(parts[2], out rz)) { return(new WVec(rx, ry, rz)); } } } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(WVec[])) { if (value != null) { var parts = value.Split(','); if (parts.Length % 3 != 0) { return(InvalidValueAction(value, fieldType, fieldName)); } var vecs = new WVec[parts.Length / 3]; for (var i = 0; i < vecs.Length; ++i) { WDist rx, ry, rz; if (WDist.TryParse(parts[3 * i], out rx) && WDist.TryParse(parts[3 * i + 1], out ry) && WDist.TryParse(parts[3 * i + 2], out rz)) { vecs[i] = new WVec(rx, ry, rz); } } return(vecs); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(WPos)) { if (value != null) { var parts = value.Split(','); if (parts.Length == 3) { WDist rx, ry, rz; if (WDist.TryParse(parts[0], out rx) && WDist.TryParse(parts[1], out ry) && WDist.TryParse(parts[2], out rz)) { return(new WPos(rx, ry, rz)); } } } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(WAngle)) { int res; if (Exts.TryParseIntegerInvariant(value, out res)) { return(new WAngle(res)); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(WRot)) { if (value != null) { var parts = value.Split(','); if (parts.Length == 3) { int rr, rp, ry; if (Exts.TryParseIntegerInvariant(parts[0], out rr) && Exts.TryParseIntegerInvariant(parts[1], out rp) && Exts.TryParseIntegerInvariant(parts[2], out ry)) { return(new WRot(new WAngle(rr), new WAngle(rp), new WAngle(ry))); } } } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(CPos)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return(new CPos(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]))); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(CVec)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return(new CVec(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]))); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(CVec[])) { if (value != null) { var parts = value.Split(','); if (parts.Length % 2 != 0) { return(InvalidValueAction(value, fieldType, fieldName)); } var vecs = new CVec[parts.Length / 2]; for (var i = 0; i < vecs.Length; i++) { int rx, ry; if (int.TryParse(parts[2 * i], out rx) && int.TryParse(parts[2 * i + 1], out ry)) { vecs[i] = new CVec(rx, ry); } } return(vecs); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(BooleanExpression)) { if (value != null) { try { return(BooleanExpressionCache[value]); } catch (InvalidDataException e) { throw new YamlException(e.Message); } } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(IntegerExpression)) { if (value != null) { try { return(IntegerExpressionCache[value]); } catch (InvalidDataException e) { throw new YamlException(e.Message); } } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType.IsEnum) { try { return(Enum.Parse(fieldType, value, true)); } catch (ArgumentException) { return(InvalidValueAction(value, fieldType, fieldName)); } } else if (fieldType == typeof(ImageFormat)) { if (value != null) { switch (value.ToLowerInvariant()) { case "bmp": return(ImageFormat.Bmp); case "gif": return(ImageFormat.Gif); case "jpg": case "jpeg": return(ImageFormat.Jpeg); case "tif": case "tiff": return(ImageFormat.Tiff); default: return(ImageFormat.Png); } } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(bool)) { return(ParseYesNo(value, fieldType, fieldName)); } else if (fieldType == typeof(int2[])) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length % 2 != 0) { return(InvalidValueAction(value, fieldType, fieldName)); } var ints = new int2[parts.Length / 2]; for (var i = 0; i < ints.Length; i++) { ints[i] = new int2(Exts.ParseIntegerInvariant(parts[2 * i]), Exts.ParseIntegerInvariant(parts[2 * i + 1])); } return(ints); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType.IsArray && fieldType.GetArrayRank() == 1) { if (value == null) { return(Array.CreateInstance(fieldType.GetElementType(), 0)); } var options = field != null && field.HasAttribute <AllowEmptyEntriesAttribute>() ? StringSplitOptions.None : StringSplitOptions.RemoveEmptyEntries; var parts = value.Split(new char[] { ',' }, options); var ret = Array.CreateInstance(fieldType.GetElementType(), parts.Length); for (var i = 0; i < parts.Length; i++) { ret.SetValue(GetValue(fieldName, fieldType.GetElementType(), parts[i].Trim(), field), i); } return(ret); } else if (fieldType.IsGenericType && (fieldType.GetGenericTypeDefinition() == typeof(HashSet <>) || fieldType.GetGenericTypeDefinition() == typeof(List <>))) { var set = Activator.CreateInstance(fieldType); if (value == null) { return(set); } var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var addMethod = fieldType.GetMethod("Add", fieldType.GetGenericArguments()); for (var i = 0; i < parts.Length; i++) { addMethod.Invoke(set, new[] { GetValue(fieldName, fieldType.GetGenericArguments()[0], parts[i].Trim(), field) }); } return(set); } else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Dictionary <,>)) { var dict = Activator.CreateInstance(fieldType); var arguments = fieldType.GetGenericArguments(); var addMethod = fieldType.GetMethod("Add", arguments); foreach (var node in yaml.Nodes) { var key = GetValue(fieldName, arguments[0], node.Key, field); var val = GetValue(fieldName, arguments[1], node.Value, field); addMethod.Invoke(dict, new[] { key, val }); } return(dict); } else if (fieldType == typeof(Size)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return(new Size(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]))); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(int2)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { return(InvalidValueAction(value, fieldType, fieldName)); } return(new int2(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]))); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(float2)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); float xx = 0; float yy = 0; float res; if (float.TryParse(parts[0].Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res)) { xx = res * (parts[0].Contains('%') ? 0.01f : 1f); } if (float.TryParse(parts[1].Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res)) { yy = res * (parts[1].Contains('%') ? 0.01f : 1f); } return(new float2(xx, yy)); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(float3)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); float x = 0; float y = 0; float z = 0; float.TryParse(parts[0], NumberStyles.Float, NumberFormatInfo.InvariantInfo, out x); float.TryParse(parts[1], NumberStyles.Float, NumberFormatInfo.InvariantInfo, out y); // z component is optional for compatibility with older float2 definitions if (parts.Length > 2) { float.TryParse(parts[2], NumberStyles.Float, NumberFormatInfo.InvariantInfo, out z); } return(new float3(x, y, z)); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(Rectangle)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return(new Rectangle( Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]), Exts.ParseIntegerInvariant(parts[2]), Exts.ParseIntegerInvariant(parts[3]))); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(BitSet <>)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var ctor = fieldType.GetConstructor(new[] { typeof(string[]) }); return(ctor.Invoke(new object[] { parts.Select(p => p.Trim()).ToArray() })); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Nullable <>)) { var innerType = fieldType.GetGenericArguments().First(); var innerValue = GetValue("Nullable<T>", innerType, value, field); return(fieldType.GetConstructor(new[] { innerType }).Invoke(new[] { innerValue })); } else if (fieldType == typeof(DateTime)) { DateTime dt; if (DateTime.TryParseExact(value, "yyyy-MM-dd HH-mm-ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out dt)) { return(dt); } return(InvalidValueAction(value, fieldType, fieldName)); } else { var conv = TypeDescriptor.GetConverter(fieldType); if (conv.CanConvertFrom(typeof(string))) { try { return(conv.ConvertFromInvariantString(value)); } catch { return(InvalidValueAction(value, fieldType, fieldName)); } } } UnknownFieldAction("[Type] {0}".F(value), fieldType); return(null); }
public SpawnOccupant(Session.Client client) { Color = client.Color; ClientIndex = client.Index; PlayerName = client.Name; Team = client.Team; Country = client.Country; SpawnPoint = client.SpawnPoint; }
public HSLColor MakeValid(Color askedColor, MersenneTwister random, IEnumerable <Color> terrainColors, IEnumerable <Color> playerColors, Action <string> onError) { Color forbiddenColor; if (IsValid(askedColor, out forbiddenColor, terrainColors, playerColors, onError)) { return(new HSLColor(askedColor)); } // Vector between the 2 colors var vector = new double[] { askedColor.R - forbiddenColor.R, askedColor.G - forbiddenColor.G, askedColor.B - forbiddenColor.B }; // Reduce vector by it's biggest value (more calculations, but more accuracy too) var vectorMax = vector.Max(vv => Math.Abs(vv)); if (vectorMax == 0) { vectorMax = 1; // Avoid division by 0 } vector[0] /= vectorMax; vector[1] /= vectorMax; vector[2] /= vectorMax; // Color weights var rmean = (double)(askedColor.R + forbiddenColor.R) / 2; var weightVector = new[] { 2.0 + rmean / 256, 4.0, 2.0 + (255 - rmean) / 256, }; var attempt = 1; var allForbidden = terrainColors.Concat(playerColors); HSLColor color; do { // If we reached the limit (The ii >= 255 prevents too much calculations) if (attempt >= 255) { color = RandomValidColor(random, terrainColors, playerColors); break; } // Apply vector to forbidden color var r = (forbiddenColor.R + (int)(vector[0] * weightVector[0] * attempt)).Clamp(0, 255); var g = (forbiddenColor.G + (int)(vector[1] * weightVector[1] * attempt)).Clamp(0, 255); var b = (forbiddenColor.B + (int)(vector[2] * weightVector[2] * attempt)).Clamp(0, 255); // Get the alternative color attempt color = new HSLColor(Color.FromArgb(r, g, b)); attempt++; } while (!IsValid(color.RGB, allForbidden, out forbiddenColor)); return(color); }
private static double GetTemp2(HSLColor hslColor) { double temp2; if (hslColor.luminosity < 0.5) //<=?? temp2 = hslColor.luminosity * (1.0 + hslColor.saturation); else temp2 = hslColor.luminosity + hslColor.saturation - (hslColor.luminosity * hslColor.saturation); return temp2; }
protected override void SetPercent(float percent) { base.SetPercent(percent); m_selectedColor.Lightness = percent / 100; SelectedHSLColor = m_selectedColor; }
public static string FormatValue(object v) { if (v == null) { return(""); } var t = v.GetType(); // Color.ToString() does the wrong thing; force it to format as rgb[a] hex if (t == typeof(Color)) { return(HSLColor.ToHexString((Color)v)); } // HSLColor.ToString() does the wrong thing; force it to format as rgb[a] hex if (t == typeof(HSLColor)) { return(((HSLColor)v).ToHexString()); } if (t == typeof(ImageFormat)) { return(((ImageFormat)v).ToString()); } if (t == typeof(Rectangle)) { var r = (Rectangle)v; return("{0},{1},{2},{3}".F(r.X, r.Y, r.Width, r.Height)); } if (t.IsArray && t.GetArrayRank() == 1) { return(((Array)v).Cast <object>().Select(FormatValue).JoinWith(", ")); } if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(HashSet <>)) { return(((System.Collections.IEnumerable)v).Cast <object>().Select(FormatValue).JoinWith(", ")); } // This is only for documentation generation if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary <,>)) { var result = ""; var dict = (System.Collections.IDictionary)v; foreach (var kvp in dict) { var key = ((System.Collections.DictionaryEntry)kvp).Key; var value = ((System.Collections.DictionaryEntry)kvp).Value; var formattedKey = FormatValue(key); var formattedValue = FormatValue(value); result += "{0}: {1}{2}".F(formattedKey, formattedValue, Environment.NewLine); } return(result); } if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(OpenRA.Primitives.Cache <,>)) { return(""); // TODO } if (t == typeof(DateTime)) { return(((DateTime)v).ToString("yyyy-MM-dd HH-mm-ss", CultureInfo.InvariantCulture)); } // Try the TypeConverter var conv = TypeDescriptor.GetConverter(t); if (conv.CanConvertTo(typeof(string))) { try { return(conv.ConvertToInvariantString(v)); } catch { } } return(v.ToString()); }
void OnWheelColorChanged(object sender, EventArgs e) { m_selectedColor.Hue = m_colorWheel.SelectedHSLColor.Hue; m_selectedColor.Saturation = m_colorWheel.SelectedHSLColor.Saturation; SelectedHSLColor = m_selectedColor; }
public override bool AbilityFrame(GameCharacter gamechar, BCBlockGameState gstatem) { delayvalue++; if (delayvalue == delayfactor) { usetheseattributes = BCBlockGameState.Choose(useDrawAttributes); delayvalue = 0; } //also spawn a sparkly. One sparkley per frame. //choose a random colour... Random rg = BCBlockGameState.rgen; Color usecolor = new HSLColor(BCBlockGameState.rgen.NextDouble()*240, 240, 120); //select a random position. RectangleF baserect = gamechar.GetRectangleF(); PointF randompos = new PointF(baserect.Left + (float)(baserect.Width * rg.NextDouble()), baserect.Top + (float)(baserect.Height * rg.NextDouble())); PointF RandomVelocity = new PointF((float)rg.NextDouble()*0.5f-0.25f,(float)rg.NextDouble()*0.5f-0.25f); Sparkle sp = new Sparkle(randompos, RandomVelocity, usecolor); sp.MaxRadius = 5; gstatem.Particles.Add(sp); return base.AbilityFrame(gamechar, gstatem); }
public MyColorHSL(Color rgbcolor) { this.rgbcolor = rgbcolor; this.hslcolor = HSLColor.FromRGB(rgbcolor); }
//TODO THIS FUNCTION public void UpdateFromColor(Color aColor) { //ColorImages ColorA = aColor; if (ColorAImage != null) { ColorAImage.color = aColor; } //Event OnColorChange.Invoke(); //HUE VARIABLES HSLColor newColor = aColor; HSLColor saturatedColorHSL = aColor; saturatedColorHSL.s = 1.0f; Color saturatedColorRGB = saturatedColorHSL; saturatedColorHSL = saturatedColorRGB; RectTransform rtColorWheel = ColorWheel.GetComponent <RectTransform> (); RectTransform rtColorTriangle = ColorTriangle.GetComponent <RectTransform> (); RectTransform rtColorHue = ColorHue.GetComponent <RectTransform> (); KUIColorTriangle KCT = ColorTriangle.gameObject.GetComponent <KUIColorTriangle> (); RectTransform rtColorWheelCursor = ColorWheel.imageCursor.GetComponent <RectTransform> (); RectTransform rtColorTriangleCursor = ColorTriangle.imageCursor.GetComponent <RectTransform> (); RectTransform rtColorHueCursor = ColorHue.imageCursor.GetComponent <RectTransform> (); //Hue Cursor float w = rtColorHue.rect.width; Vector3 p = rtColorHue.position; p.x = p.x - w * 0.5f + w * newColor.h / 360.0f; rtColorHueCursor.position = p; //Triangle Cursor w = rtColorTriangle.rect.width; float h = rtColorTriangle.rect.height; p = rtColorTriangle.position; p.x = p.x - w * 0.5f + w * newColor.s; p.y = p.y - h * 0.5f + h * newColor.l; rtColorTriangleCursor.position = p; //Triangle Point position and Color KCT.color3 = saturatedColorRGB; KCT.pointCenter = saturatedColorHSL.l; KCT.SetVerticesDirty(); //Wheel w = rtColorWheel.rect.width; h = rtColorWheel.rect.height; p = rtColorWheel.position; p.x = p.x + Mathf.Cos((newColor.h + 30.0f) * Mathf.Deg2Rad) * w * 0.5f * newColor.s; p.y = p.y + Mathf.Sin((newColor.h + 30.0f) * Mathf.Deg2Rad) * h * 0.5f * newColor.s; rtColorWheelCursor.position = p; //Text ColorText.text = newColor.ToString(); }
/// <summary> /// Converts HSL to RGB, with a specified output Alpha. /// Arguments are limited to the defined range: /// does not raise exceptions. /// </summary> /// <param name="h">Hue, must be in [0, 360].</param> /// <param name="s">Saturation, must be in [0, 1].</param> /// <param name="l">Luminance, must be in [0, 1].</param> /// <param name="a">Output Alpha, must be in [0, 255].</param> public static MudColor HsLtoRgb(HSLColor hsl, int a = 255) { var h = SystemMath.Max(0D, SystemMath.Min(360D, hsl.H)); var s = SystemMath.Max(0D, SystemMath.Min(1D, hsl.S)); var l = SystemMath.Max(0D, SystemMath.Min(1D, hsl.L)); a = SystemMath.Max(0, SystemMath.Min(255, a)); // achromatic argb (gray scale) if (SystemMath.Abs(s) < EPSILON) { return(MudColor.FromArgb( a, SystemMath.Max(0, SystemMath.Min(255, Convert.ToInt32(double.Parse($"{l * 255D:0.00}")))), SystemMath.Max(0, SystemMath.Min(255, Convert.ToInt32(double.Parse($"{l * 255D:0.00}")))), SystemMath.Max(0, SystemMath.Min(255, Convert.ToInt32(double.Parse($"{l * 255D:0.00}")))))); } double q = l < .5D ? l * (1D + s) : (l + s) - (l * s); double p = (2D * l) - q; double hk = h / 360D; double[] T = new double[3]; T[0] = hk + (1D / 3D); // Tr T[1] = hk; // Tb T[2] = hk - (1D / 3D); // Tg for (int i = 0; i < 3; i++) { if (T[i] < 0D) { T[i] += 1D; } if (T[i] > 1D) { T[i] -= 1D; } if ((T[i] * 6D) < 1D) { T[i] = p + ((q - p) * 6D * T[i]); } else if ((T[i] * 2D) < 1) { T[i] = q; } else if ((T[i] * 3D) < 2) { T[i] = p + ((q - p) * ((2D / 3D) - T[i]) * 6D); } else { T[i] = p; } } return(MudColor.FromArgb( a, SystemMath.Max(0, SystemMath.Min(255, (int)Math.Round(T[0] * 255D))), SystemMath.Max(0, SystemMath.Min(255, (int)Math.Round(T[1] * 255D))), SystemMath.Max(0, SystemMath.Min(255, (int)Math.Round(T[2] * 255D))))); }
public ColorInformationDialog(HSLColor selectedColor) { _selectedColor = selectedColor; InitializeComponent(); SetUpUI(); }
private Color getrndcolor() { var hscolor = new HSLColor(rgen.NextDouble()*240, 240, 120); return hscolor; }
public bool InterpretCommand(S server, Connection conn, Session.Client client, string cmd) { if (server == null || conn == null || client == null || !ValidateCommand(server, conn, client, cmd)) { return(false); } var dict = new Dictionary <string, Func <string, bool> > { { "state", s => { var state = Session.ClientState.Invalid; if (!Enum <Session.ClientState> .TryParse(s, false, out state)) { server.SendOrderTo(conn, "Message", "Malformed state command"); return(true); } client.State = state; Log.Write("server", "Player @{0} is {1}", conn.Socket.RemoteEndPoint, client.State); server.SyncLobbyClients(); CheckAutoStart(server); return(true); } }, { "startgame", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can start the game."); return(true); } if (server.LobbyInfo.Slots.Any(sl => sl.Value.Required && server.LobbyInfo.ClientInSlot(sl.Key) == null)) { server.SendOrderTo(conn, "Message", "Unable to start the game until required slots are full."); return(true); } if (!server.LobbyInfo.GlobalSettings.EnableSingleplayer && server.LobbyInfo.Clients.Where(c => c.Bot == null && c.Slot != null).Count() == 1) { server.SendOrderTo(conn, "Message", server.TwoHumansRequiredText); return(true); } server.StartGame(); return(true); } }, { "slot", s => { if (!server.LobbyInfo.Slots.ContainsKey(s)) { Log.Write("server", "Invalid slot: {0}", s); return(false); } var slot = server.LobbyInfo.Slots[s]; if (slot.Closed || server.LobbyInfo.ClientInSlot(s) != null) { return(false); } // If the previous slot had a locked spawn then we must not carry that to the new slot var oldSlot = client.Slot != null ? server.LobbyInfo.Slots[client.Slot] : null; if (oldSlot != null && oldSlot.LockSpawn) { client.SpawnPoint = 0; } client.Slot = s; S.SyncClientToPlayerReference(client, server.Map.Players.Players[s]); if (!slot.LockColor) { client.PreferredColor = client.Color = SanitizePlayerColor(server, client.Color, client.Index, conn); } server.SyncLobbyClients(); CheckAutoStart(server); return(true); } }, { "allow_spectators", s => { if (bool.TryParse(s, out server.LobbyInfo.GlobalSettings.AllowSpectators)) { server.SyncLobbyGlobalSettings(); return(true); } else { server.SendOrderTo(conn, "Message", "Malformed allow_spectate command"); return(true); } } }, { "spectate", s => { if (server.LobbyInfo.GlobalSettings.AllowSpectators || client.IsAdmin) { client.Slot = null; client.SpawnPoint = 0; client.Color = HSLColor.FromRGB(255, 255, 255); server.SyncLobbyClients(); CheckAutoStart(server); return(true); } else { return(false); } } }, { "slot_close", s => { if (!ValidateSlotCommand(server, conn, client, s, true)) { return(false); } // kick any player that's in the slot var occupant = server.LobbyInfo.ClientInSlot(s); if (occupant != null) { if (occupant.Bot != null) { server.LobbyInfo.Clients.Remove(occupant); server.SyncLobbyClients(); var ping = server.LobbyInfo.PingFromClient(occupant); if (ping != null) { server.LobbyInfo.ClientPings.Remove(ping); server.SyncClientPing(); } } else { var occupantConn = server.Conns.FirstOrDefault(c => c.PlayerIndex == occupant.Index); if (occupantConn != null) { server.SendOrderTo(occupantConn, "ServerError", "Your slot was closed by the host."); server.DropClient(occupantConn); } } } server.LobbyInfo.Slots[s].Closed = true; server.SyncLobbySlots(); return(true); } }, { "slot_open", s => { if (!ValidateSlotCommand(server, conn, client, s, true)) { return(false); } var slot = server.LobbyInfo.Slots[s]; slot.Closed = false; server.SyncLobbySlots(); // Slot may have a bot in it var occupant = server.LobbyInfo.ClientInSlot(s); if (occupant != null && occupant.Bot != null) { server.LobbyInfo.Clients.Remove(occupant); var ping = server.LobbyInfo.PingFromClient(occupant); if (ping != null) { server.LobbyInfo.ClientPings.Remove(ping); server.SyncClientPing(); } } server.SyncLobbyClients(); return(true); } }, { "slot_bot", s => { var parts = s.Split(' '); if (parts.Length < 3) { server.SendOrderTo(conn, "Message", "Malformed slot_bot command"); return(true); } if (!ValidateSlotCommand(server, conn, client, parts[0], true)) { return(false); } var slot = server.LobbyInfo.Slots[parts[0]]; var bot = server.LobbyInfo.ClientInSlot(parts[0]); int controllerClientIndex; if (!Exts.TryParseIntegerInvariant(parts[1], out controllerClientIndex)) { Log.Write("server", "Invalid bot controller client index: {0}", parts[1]); return(false); } var botType = parts.Skip(2).JoinWith(" "); // Invalid slot if (bot != null && bot.Bot == null) { server.SendOrderTo(conn, "Message", "Can't add bots to a slot with another client."); return(true); } slot.Closed = false; if (bot == null) { // Create a new bot bot = new Session.Client() { Index = server.ChooseFreePlayerIndex(), Name = botType, Bot = botType, Slot = parts[0], Faction = "Random", SpawnPoint = 0, Team = 0, State = Session.ClientState.NotReady, BotControllerClientIndex = controllerClientIndex }; // Pick a random color for the bot var validator = server.ModData.Manifest.Get <ColorValidator>(); var tileset = server.Map.Rules.TileSet; var terrainColors = tileset.TerrainInfo.Where(ti => ti.RestrictPlayerColor).Select(ti => ti.Color); var playerColors = server.LobbyInfo.Clients.Select(c => c.Color.RGB) .Concat(server.Map.Players.Players.Values.Select(p => p.Color.RGB)); bot.Color = bot.PreferredColor = validator.RandomValidColor(server.Random, terrainColors, playerColors); server.LobbyInfo.Clients.Add(bot); } else { // Change the type of the existing bot bot.Name = botType; bot.Bot = botType; } S.SyncClientToPlayerReference(bot, server.Map.Players.Players[parts[0]]); server.SyncLobbyClients(); server.SyncLobbySlots(); return(true); } }, { "map", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can change the map."); return(true); } var lastMap = server.LobbyInfo.GlobalSettings.Map; Action <MapPreview> selectMap = map => { // Make sure the map hasn't changed in the meantime if (server.LobbyInfo.GlobalSettings.Map != lastMap) { return; } server.LobbyInfo.GlobalSettings.Map = map.Uid; var oldSlots = server.LobbyInfo.Slots.Keys.ToArray(); server.Map = server.ModData.MapCache[server.LobbyInfo.GlobalSettings.Map]; server.LobbyInfo.Slots = server.Map.Players.Players .Select(p => MakeSlotFromPlayerReference(p.Value)) .Where(ss => ss != null) .ToDictionary(ss => ss.PlayerReference, ss => ss); LoadMapSettings(server, server.LobbyInfo.GlobalSettings, server.Map.Rules); // Reset client states foreach (var c in server.LobbyInfo.Clients) { c.State = Session.ClientState.Invalid; } // Reassign players into new slots based on their old slots: // - Observers remain as observers // - Players who now lack a slot are made observers // - Bots who now lack a slot are dropped // - Bots who are not defined in the map rules are dropped var botNames = server.Map.Rules.Actors["player"].TraitInfos <IBotInfo>().Select(t => t.Name); var slots = server.LobbyInfo.Slots.Keys.ToArray(); var i = 0; foreach (var os in oldSlots) { var c = server.LobbyInfo.ClientInSlot(os); if (c == null) { continue; } c.SpawnPoint = 0; c.Slot = i < slots.Length ? slots[i++] : null; if (c.Slot != null) { // Remove Bot from slot if slot forbids bots if (c.Bot != null && (!server.Map.Players.Players[c.Slot].AllowBots || !botNames.Contains(c.Bot))) { server.LobbyInfo.Clients.Remove(c); } S.SyncClientToPlayerReference(c, server.Map.Players.Players[c.Slot]); } else if (c.Bot != null) { server.LobbyInfo.Clients.Remove(c); } } // Validate if color is allowed and get an alternative if it isn't foreach (var c in server.LobbyInfo.Clients) { if (c.Slot == null || (c.Slot != null && !server.LobbyInfo.Slots[c.Slot].LockColor)) { c.Color = c.PreferredColor = SanitizePlayerColor(server, c.Color, c.Index, conn); } } server.SyncLobbyInfo(); server.SendMessage("{0} changed the map to {1}.".F(client.Name, server.Map.Title)); if (server.Map.DefinesUnsafeCustomRules) { server.SendMessage("This map contains custom rules. Game experience may change."); } if (!server.LobbyInfo.GlobalSettings.EnableSingleplayer) { server.SendMessage(server.TwoHumansRequiredText); } else if (server.Map.Players.Players.Where(p => p.Value.Playable).All(p => !p.Value.AllowBots)) { server.SendMessage("Bots have been disabled on this map."); } var briefing = MissionBriefingOrDefault(server); if (briefing != null) { server.SendMessage(briefing); } }; Action queryFailed = () => server.SendOrderTo(conn, "Message", "Map was not found on server."); var m = server.ModData.MapCache[s]; if (m.Status == MapStatus.Available || m.Status == MapStatus.DownloadAvailable) { selectMap(m); } else if (server.Settings.QueryMapRepository) { server.SendOrderTo(conn, "Message", "Searching for map on the Resource Center..."); server.ModData.MapCache.QueryRemoteMapDetails(new[] { s }, selectMap, queryFailed); } else { queryFailed(); } return(true); } }, { "option", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can change the configuration."); return(true); } var allOptions = server.Map.Rules.Actors["player"].TraitInfos <ILobbyOptions>() .Concat(server.Map.Rules.Actors["world"].TraitInfos <ILobbyOptions>()) .SelectMany(t => t.LobbyOptions(server.Map.Rules)); // Overwrite keys with duplicate ids var options = new Dictionary <string, LobbyOption>(); foreach (var o in allOptions) { options[o.Id] = o; } var split = s.Split(' '); LobbyOption option; if (split.Length < 2 || !options.TryGetValue(split[0], out option) || !option.Values.ContainsKey(split[1])) { server.SendOrderTo(conn, "Message", "Invalid configuration command."); return(true); } if (option.Locked) { server.SendOrderTo(conn, "Message", "{0} cannot be changed.".F(option.Name)); return(true); } var oo = server.LobbyInfo.GlobalSettings.LobbyOptions[option.Id]; if (oo.Value == split[1]) { return(true); } oo.Value = oo.PreferredValue = split[1]; if (option.Id == "gamespeed") { var speed = server.ModData.Manifest.Get <GameSpeeds>().Speeds[oo.Value]; server.LobbyInfo.GlobalSettings.Timestep = speed.Timestep; server.LobbyInfo.GlobalSettings.OrderLatency = speed.OrderLatency; } server.SyncLobbyGlobalSettings(); server.SendMessage(option.ValueChangedMessage(client.Name, split[1])); return(true); } }, { "assignteams", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set that option."); return(true); } int teamCount; if (!Exts.TryParseIntegerInvariant(s, out teamCount)) { server.SendOrderTo(conn, "Message", "Number of teams could not be parsed: {0}".F(s)); return(true); } var maxTeams = (server.LobbyInfo.Clients.Count(c => c.Slot != null) + 1) / 2; teamCount = teamCount.Clamp(0, maxTeams); var clients = server.LobbyInfo.Slots .Select(slot => server.LobbyInfo.ClientInSlot(slot.Key)) .Where(c => c != null && !server.LobbyInfo.Slots[c.Slot].LockTeam); var assigned = 0; var clientCount = clients.Count(); foreach (var player in clients) { // Free for all if (teamCount == 0) { player.Team = 0; } // Humans vs Bots else if (teamCount == 1) { player.Team = player.Bot == null ? 1 : 2; } else { player.Team = assigned++ *teamCount / clientCount + 1; } } server.SyncLobbyClients(); return(true); } }, { "kick", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can kick players."); return(true); } var split = s.Split(' '); if (split.Length < 2) { server.SendOrderTo(conn, "Message", "Malformed kick command"); return(true); } int kickClientID; Exts.TryParseIntegerInvariant(split[0], out kickClientID); var kickConn = server.Conns.SingleOrDefault(c => server.GetClient(c) != null && server.GetClient(c).Index == kickClientID); if (kickConn == null) { server.SendOrderTo(conn, "Message", "No-one in that slot."); return(true); } var kickClient = server.GetClient(kickConn); Log.Write("server", "Kicking client {0}.", kickClientID); server.SendMessage("{0} kicked {1} from the server.".F(client.Name, kickClient.Name)); server.SendOrderTo(kickConn, "ServerError", "You have been kicked from the server."); server.DropClient(kickConn); bool tempBan; bool.TryParse(split[1], out tempBan); if (tempBan) { Log.Write("server", "Temporarily banning client {0} ({1}).", kickClientID, kickClient.IpAddress); server.SendMessage("{0} temporarily banned {1} from the server.".F(client.Name, kickClient.Name)); server.TempBans.Add(kickClient.IpAddress); } server.SyncLobbyClients(); server.SyncLobbySlots(); return(true); } }, { "name", s => { var sanitizedName = Settings.SanitizedPlayerName(s); if (sanitizedName == client.Name) { return(true); } Log.Write("server", "Player@{0} is now known as {1}.", conn.Socket.RemoteEndPoint, sanitizedName); server.SendMessage("{0} is now known as {1}.".F(client.Name, sanitizedName)); client.Name = sanitizedName; server.SyncLobbyClients(); return(true); } }, { "faction", s => { var parts = s.Split(' '); var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) { return(true); } // Map has disabled faction changes if (server.LobbyInfo.Slots[targetClient.Slot].LockFaction) { return(true); } var factions = server.Map.Rules.Actors["world"].TraitInfos <FactionInfo>() .Where(f => f.Selectable).Select(f => f.InternalName); if (!factions.Contains(parts[1])) { server.SendOrderTo(conn, "Message", "Invalid faction selected: {0}".F(parts[1])); server.SendOrderTo(conn, "Message", "Supported values: {0}".F(factions.JoinWith(", "))); return(true); } targetClient.Faction = parts[1]; server.SyncLobbyClients(); return(true); } }, { "team", s => { var parts = s.Split(' '); var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) { return(true); } // Map has disabled team changes if (server.LobbyInfo.Slots[targetClient.Slot].LockTeam) { return(true); } int team; if (!Exts.TryParseIntegerInvariant(parts[1], out team)) { Log.Write("server", "Invalid team: {0}", s); return(false); } targetClient.Team = team; server.SyncLobbyClients(); return(true); } }, { "spawn", s => { var parts = s.Split(' '); var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) { return(true); } // Spectators don't need a spawnpoint if (targetClient.Slot == null) { return(true); } // Map has disabled spawn changes if (server.LobbyInfo.Slots[targetClient.Slot].LockSpawn) { return(true); } int spawnPoint; if (!Exts.TryParseIntegerInvariant(parts[1], out spawnPoint) || spawnPoint <0 || spawnPoint> server.Map.SpawnPoints.Length) { Log.Write("server", "Invalid spawn point: {0}", parts[1]); return(true); } if (server.LobbyInfo.Clients.Where(cc => cc != client).Any(cc => (cc.SpawnPoint == spawnPoint) && (cc.SpawnPoint != 0))) { server.SendOrderTo(conn, "Message", "You cannot occupy the same spawn point as another player."); return(true); } // Check if any other slot has locked the requested spawn if (spawnPoint > 0) { var spawnLockedByAnotherSlot = server.LobbyInfo.Slots.Where(ss => ss.Value.LockSpawn).Any(ss => { var pr = PlayerReferenceForSlot(server, ss.Value); return(pr != null && pr.Spawn == spawnPoint); }); if (spawnLockedByAnotherSlot) { server.SendOrderTo(conn, "Message", "The spawn point is locked to another player slot."); return(true); } } targetClient.SpawnPoint = spawnPoint; server.SyncLobbyClients(); return(true); } }, { "color", s => { var parts = s.Split(' '); var targetClient = server.LobbyInfo.ClientWithIndex(Exts.ParseIntegerInvariant(parts[0])); // Only the host can change other client's info if (targetClient.Index != client.Index && !client.IsAdmin) { return(true); } // Spectator or map has disabled color changes if (targetClient.Slot == null || server.LobbyInfo.Slots[targetClient.Slot].LockColor) { return(true); } // Validate if color is allowed and get an alternative it isn't var newColor = FieldLoader.GetValue <HSLColor>("(value)", parts[1]); targetClient.Color = SanitizePlayerColor(server, newColor, targetClient.Index, conn); // Only update player's preferred color if new color is valid if (newColor == targetClient.Color) { targetClient.PreferredColor = targetClient.Color; } server.SyncLobbyClients(); return(true); } }, { "sync_lobby", s => { if (!client.IsAdmin) { server.SendOrderTo(conn, "Message", "Only the host can set lobby info"); return(true); } var lobbyInfo = Session.Deserialize(s); if (lobbyInfo == null) { server.SendOrderTo(conn, "Message", "Invalid Lobby Info Sent"); return(true); } server.LobbyInfo = lobbyInfo; server.SyncLobbyInfo(); return(true); } } }; var cmdName = cmd.Split(' ').First(); var cmdValue = cmd.Split(' ').Skip(1).JoinWith(" "); Func <string, bool> a; if (!dict.TryGetValue(cmdName, out a)) { return(false); } return(a(cmdValue)); }
/// <summary> /// /// </summary> /// <param name="fieldName"></param> /// <param name="fieldType"></param> /// <param name="yaml"></param> /// <param name="field"></param> /// <returns></returns> public static object GetValue(string fieldName, Type fieldType, MiniYaml yaml, MemberInfo field) { var value = yaml.Value; if (value != null) { value = value.Trim(); } if (fieldType == typeof(int)) { int res; if (Exts.TryParseIntegerInvariant(value, out res)) { return(res); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(ushort)) { ushort res; if (ushort.TryParse(value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out res)) { return(res); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(long)) { long res; if (long.TryParse(value, NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out res)) { return(res); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(float)) { float res; if (value != null && float.TryParse(value.Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res)) { return(res * (value.Contains('%') ? 0.01f : 1f)); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(decimal)) { decimal res; if (value != null && decimal.TryParse(value.Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res)) { return(res * (value.Contains('%') ? 0.01m : 1m)); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(string)) { if (field != null && MemberHasTranslateAttribute[field] && value != null) { } return(value); } else if (fieldType == typeof(WRot)) { if (value != null) { var parts = value.Split(','); if (parts.Length == 3) { int rr, rp, ry; if (Exts.TryParseIntegerInvariant(parts[0], out rr) && Exts.TryParseIntegerInvariant(parts[1], out rp) && Exts.TryParseIntegerInvariant(parts[2], out ry)) { return(new WRot(new WAngle(rr), new WAngle(rp), new WAngle(ry))); } } } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(WAngle)) { int res; if (Exts.TryParseIntegerInvariant(value, out res)) { return(new WAngle(res)); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(WVec)) { if (value != null) { var parts = value.Split(','); if (parts.Length == 3) { WDist rx, ry, rz; if (WDist.TryParse(parts[0], out rx) && WDist.TryParse(parts[1], out ry) && WDist.TryParse(parts[2], out rz)) { return(new WVec(rx, ry, rz)); } } } } else if (fieldType == typeof(WVec[])) { if (value != null) { var parts = value.Split(','); if (parts.Length % 3 != 0) { return(InvalidValueAction(value, fieldType, fieldName)); } var vecs = new WVec[parts.Length / 3]; for (var i = 0; i < vecs.Length; i++) { WDist rx, ry, rz; if (WDist.TryParse(parts[3 * i], out rx) && WDist.TryParse(parts[3 * i + 1], out ry) && WDist.TryParse(parts[3 * i + 2], out rz)) { vecs[i] = new WVec(rx, ry, rz); } } return(vecs); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(WDist)) { WDist res; if (WDist.TryParse(value, out res)) { return(res); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(WPos)) { if (value != null) { var parts = value.Split(','); if (parts.Length == 3) { WDist rx, ry, rz; if (WDist.TryParse(parts[0], out rx) && WDist.TryParse(parts[1], out ry) && WDist.TryParse(parts[2], out rz)) { return(new WPos(rx, ry, rz)); } } } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(CPos)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return(new CPos(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]))); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(CVec)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return(new CVec(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]))); } } else if (fieldType == typeof(CVec[])) { if (value != null) { var parts = value.Split(','); if (parts.Length % 2 != 0) { return(InvalidValueAction(value, fieldType, fieldName)); } var vecs = new CVec[parts.Length / 2]; for (var i = 0; i < vecs.Length; i++) { int rx, ry; if (int.TryParse(parts[2 * i], out rx) && int.TryParse(parts[2 * i + 1], out ry)) { vecs[i] = new CVec(rx, ry); } } return(vecs); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(Int2)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return(new Int2(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]))); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType.IsEnum) { try { return(Enum.Parse(fieldType, value, true)); } catch (ArgumentException) { return(InvalidValueAction(value, fieldType, fieldName)); } } else if (fieldType == typeof(Size)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return(new Size(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]))); } } else if (fieldType.IsArray && fieldType.GetArrayRank() == 1) //获取Rank属性,例如,一维数组返回1,二维数组返回2 { if (value == null) { return(Array.CreateInstance(fieldType.GetElementType(), 0)); } var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var ret = Array.CreateInstance(fieldType.GetElementType(), parts.Length); for (var i = 0; i < parts.Length; i++) { ret.SetValue(GetValue(fieldName, fieldType.GetElementType(), parts[i].Trim(), field), i); } return(ret); } else if (fieldType == typeof(Rectangle)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return(new Rectangle( Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]), Exts.ParseIntegerInvariant(parts[2]), Exts.ParseIntegerInvariant(parts[3]))); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(EW.Framework.Point)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); return(new EW.Framework.Point(Exts.ParseIntegerInvariant(parts[0]), Exts.ParseIntegerInvariant(parts[1]))); } } else if (fieldType == typeof(bool)) { return(ParseYesNo(value, fieldType, fieldName)); } else if (fieldType == typeof(Vector2)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); float xx = 0; float yy = 0; float res; if (float.TryParse(parts[0].Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res)) { xx = res * (parts[0].Contains('%') ? 0.01f : 1f); } if (float.TryParse(parts[1].Replace("%", ""), NumberStyles.Float, NumberFormatInfo.InvariantInfo, out res)) { yy = res * (parts[1].Contains('%') ? 0.01f : 1f); } return(new Vector2(xx, yy)); } } else if (fieldType == typeof(Vector3)) { if (value != null) { var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); float x, y, z = 0; float.TryParse(parts[0], NumberStyles.Float, NumberFormatInfo.InvariantInfo, out x); float.TryParse(parts[1], NumberStyles.Float, NumberFormatInfo.InvariantInfo, out y); if (parts.Length > 2) { float.TryParse(parts[2], NumberStyles.Float, NumberFormatInfo.InvariantInfo, out z); } return(new Vector3(x, y, z)); } } else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(HashSet <>)) { var set = Activator.CreateInstance(fieldType); if (value == null) { return(set); } var parts = value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var addMethod = fieldType.GetMethod("Add", fieldType.GetGenericArguments()); for (var i = 0; i < parts.Length; i++) { addMethod.Invoke(set, new[] { GetValue(fieldName, fieldType.GetGenericArguments()[0], parts[i].Trim(), field) }); } return(set); } else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Dictionary <,>)) { var dict = Activator.CreateInstance(fieldType); var arguments = fieldType.GetGenericArguments(); var addMethod = fieldType.GetMethod("Add", arguments); foreach (var node in yaml.Nodes) { var key = GetValue(fieldName, arguments[0], node.Key, field); var val = GetValue(fieldName, arguments[1], node.Value, field); addMethod.Invoke(dict, new[] { key, val }); } return(dict); } else if (fieldType == typeof(System.Drawing.Color)) { System.Drawing.Color color; if (value != null && HSLColor.TryParseRGB(value, out color)) { return(color); } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(System.Drawing.Color[])) { if (value != null) { var parts = value.Split(','); var colors = new System.Drawing.Color[parts.Length]; for (var i = 0; i < parts.Length; i++) { if (!HSLColor.TryParseRGB(parts[i], out colors[i])) { return(InvalidValueAction(value, fieldType, fieldName)); } } return(colors); } } else if (fieldType == typeof(HSLColor)) { if (value != null) { System.Drawing.Color rgb; if (HSLColor.TryParseRGB(value, out rgb)) { return(new HSLColor(rgb)); } //Allowed old HSLColor / ColorRamp formats to be parsed as HSLColor var parts = value.Split(','); if (parts.Length == 3 || parts.Length == 4) { return(new HSLColor((byte)Exts.ParseIntegerInvariant(parts[0]).Clamp(0, 255), (byte)Exts.ParseIntegerInvariant(parts[1]).Clamp(0, 255), (byte)Exts.ParseIntegerInvariant(parts[2]).Clamp(0, 255))); } } return(InvalidValueAction(value, fieldType, fieldName)); } else if (fieldType == typeof(BooleanExpression)) { if (value != null) { try { return(new BooleanExpression(value)); } catch (InvalidDataException e) { throw new YamlException(e.Message); } } return(InvalidValueAction(value, fieldType, fieldName)); } else { var conv = TypeDescriptor.GetConverter(fieldType); if (conv.CanConvertFrom(typeof(string))) { try { return(conv.ConvertFromInvariantString(value)); } catch { return(InvalidValueAction(value, fieldType, fieldName)); } } } UnknownFieldAction("[Type]{0}".F(value), fieldType); return(null); }
public MyColorHSL(HSLColor hsbcolor) { this.hslcolor = hsbcolor; this.rgbcolor = hsbcolor.Color; }
void OnLightnessColorChanged(object sender, EventArgs e) { m_selectedColor.Lightness = m_colorBar.SelectedHSLColor.Lightness; SelectedHSLColor = m_selectedColor; }
public static Brush ToBrush(this HSLColor hsl) { return(new SolidBrush(ToColor(hsl))); }
public bool HueCycler(BasicFadingText obj) { obj.HueCycle=(obj.HueCycle+1)%240; Color usecolor = new HSLColor(obj.HueCycle, 240, 120); obj.TextBrush = new SolidBrush(usecolor); return true; }
public static Pen ToPen(this HSLColor hsl) { return(new Pen(ToColor(hsl))); }