Inheritance: MonoBehaviour
	public void CreateLinearBeat(float[] magnitudes) {
		Vector2 direction = new Vector2(0f, 0f);
		direction = GetDirection(magnitudes);
		bool reverseX = false;
		bool reverseXLeft = false;
		bool reverseXRight = false;
		
		bool reverseY = false;
		if(xAngle < xLimits.x ) {
			directions[0].x = 1f;
			reverseX = true;
			reverseXLeft = true;
		} else if(xAngle > xLimits.y) {
			directions[0].x = -1;
			reverseX = true;
			reverseXRight = true;
		}
		if(currentBeatPosition.y + direction.y < centerY - rangeY || currentBeatPosition.y + direction.y > centerY + rangeY) {
			direction.y *= -1f;
			reverseY = true;
		}
		
		if(reverseY) {
			ReverseDirections(reverseX, reverseY);
		}
		Vector3 lastBeatPosition = currentBeatPosition;
		Vector2 newBeats = GetXandZPositionFromAngleAndRadius(xAngle, radius);
		currentBeatPosition = new Vector3(transform.position.x + newBeats.x, currentBeatPosition.y + direction.y, transform.position.z + newBeats.y );
		int strongestMag = GetStrongestMagnitudeIndex(magnitudes);
		GameObject theBeat = (GameObject)Instantiate(linearBeats[strongestMag], currentBeatPosition, Quaternion.identity);
		latestFirework = theBeat.GetComponentInChildren<Firework>();
		
		Vector3 adjustedLastBeatPosition = lastBeatPosition;
		if(reverseXLeft) {
			adjustedLastBeatPosition = new Vector3(-1000f, currentBeatPosition.y, 0f);
		} else if(reverseXRight) {
			adjustedLastBeatPosition = new Vector3(1000f, currentBeatPosition.y, 0f);
		}
		latestFirework.SetInfo(adjustedLastBeatPosition, magnitudes[9], magnitudes[strongestMag], triggeredBeats);
		TweenToPosition[] particleScripts = theBeat.GetComponentsInChildren<TweenToPosition>();
		
		float timeModifier = 1f;
		if(magnitudes[8] < Global.audioClip.frequency * 2) {
			timeModifier = .75f + (float)magnitudes[8] / (float)Global.audioClip.frequency / 8f;
		}
		
		for(int i = 0; i < particleScripts.Length; i++) {
			StartCoroutine(particleScripts[i].StartIt(timeModifier));
		}
		
		if (triggeredBeats > 0) {
			//GameObject g = (GameObject)Instantiate(lineTracker, transform.position, Quaternion.identity);
			//LineTracker lt = g.GetComponent<LineTracker>();
			//StartCoroutine(lt.Instantiate(lastBeatPosition, currentBeatPosition, 1.2f));
		}
		triggeredBeats ++;
		lastBeatPosition = currentBeatPosition;
		StartCoroutine(TriggerRealtime());
		//StartCoroutine(TriggerCrosshair(true));
	}
Ejemplo n.º 2
0
        public static FireworkExplosion CreateFireworkExplosion(Firework epicenter)
        {
            Dictionary <FireworkType, int> sparks = Substitute.For <Dictionary <FireworkType, int> >();
            FireworkExplosion explosion           = Substitute.For <FireworkExplosion>(epicenter, 1, Amplitude, sparks);

            return(explosion);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Return a firework to recommend to this customer.
        /// </summary>
        /// <returns>a firework to recommend to this customer</returns>
        public Firework GetRecommended()
        {
            // if we're promoting a particular firework, return it
            try
            {
                String        s            = FileFinder.GetFileName("config", "strategy.xml");
                StreamReader  r            = new StreamReader(s);
                XmlSerializer xs           = new XmlSerializer(typeof(String));
                String        promotedName = (String)xs.Deserialize(r);
                r.Close();

                Firework f = Firework.Lookup(promotedName);
                if (f != null)
                {
                    return(f);
                }
            }
            catch {}

            // if registered, compare to other customers
            if (IsRegistered())
            {
                return((Firework)Rel8.Advise(this));
            }
            // check spending over the last year
            if (SpendingSince(DateTime.Now.AddYears(-1)) > 1000)
            {
                return((Firework)LikeMyStuff.Suggest(this));
            }
            // oh well!
            return(Firework.GetRandom());
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets <see cref="Firework"/> with maximum quality.
        /// </summary>
        /// <param name="currentMaximum">Current maximum quality <see cref="Firework"/>.</param>
        /// <param name="candidate">The <see cref="Firework"/> to be compared with
        /// <paramref name="currentMaximum"/>.</param>
        /// <returns>The <see cref="Firework"/> with maximum quality.</returns>
        protected virtual Firework GetGreaterQualityFirework(Firework currentMaximum, Firework candidate)
        {
            Debug.Assert(currentMaximum != null, "Current maximum is null");
            Debug.Assert(candidate != null, "Candidate for maximum is null");

            return(candidate.Quality.IsGreater(currentMaximum.Quality) ? candidate : currentMaximum);
        }
Ejemplo n.º 5
0
        public override void Draw(SpriteBatch sb, Projectile p, Firework f)
        {
            trail.Insert(0, new Vector2(pos.X, pos.Y));
            for (int i = 0; i < Math.Min(trail.Count, 10); i++)
            {
                Vector2 v     = trail[i];
                float   alpha = (10 - i) / 10f;
                sb.Draw(ptFuzzy, v - Main.screenPosition, GetRectFuzzy(), new Color(color.R, color.G, color.B, (byte)(color.A * alpha * .5f)), 0f, GetCenterFuzzy(), GetScaleFuzzy(36f), SpriteEffects.None, 0f);
                sb.Draw(ptFuzzy, v - Main.screenPosition, GetRectFuzzy(), new Color(color.R, color.G, color.B, (byte)(color.A * alpha)), 0f, GetCenterFuzzy(), GetScaleFuzzy(12f), SpriteEffects.None, 0f);
            }
            if (trail.Count > 10)
            {
                trail.RemoveAt(10);
            }
            Lighting.addLight((int)Math.Round(pos.X / 16f), (int)Math.Round(pos.Y / 16f), color.R / 255f * (color.A / 255f), color.G / 255f * (color.A / 255f), color.B / 255f * (color.A / 255f));

            pos   += vel;
            vel.Y += .075f;

            if (timeLeft > 0)
            {
                timeLeft--;
            }
            else
            {
                color.A = (byte)Math.Max(color.A - 10, 0);
                if (color.A == 0)
                {
                    dead = true;
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets <see cref="Firework"/> with minimum quality.
        /// </summary>
        /// <param name="currentMinimum">Current minimum quality <see cref="Firework"/>.</param>
        /// <param name="candidate">The <see cref="Firework"/> to be compared with
        /// <paramref name="currentMinimum"/>.</param>
        /// <returns>The <see cref="Firework"/> with minimum quality.</returns>
        protected virtual Firework GetLessQualityFirework(Firework currentMinimum, Firework candidate)
        {
            Debug.Assert(currentMinimum != null, "Current minimum is null");
            Debug.Assert(candidate != null, "Candidate for minimum is null");

            return(candidate.Quality.IsLess(currentMinimum.Quality) ? candidate : currentMinimum);
        }
Ejemplo n.º 7
0
    private void Update()
    {
        if (_canCreateFirework)
        {
            _timeToCreateFirework -= Time.deltaTime;
            if (_timeToCreateFirework <= 0)
            {
                _timeToCreateFirework += Interval;

                FireworkType type           = (FireworkType)Utility.RandomEnum <FireworkType>();
                Vector2      position       = Utility.RandomVector2(FireworkMinPosition, FireworkMaxPosition);
                float        scale          = Random.Range(FireworkMinScale, FireworkMaxScale);
                GameObject   fireworkObject = Utils.Spawn(FireworkPrefab, FireworkParent);
                Firework     firework       = fireworkObject.GetComponent <Firework>();
                firework.Init(type, position, new Vector3(scale, scale, scale));
                if (IsShowing)
                {
                    firework.Show();
                }
                else
                {
                    firework.Hide();
                }
                _fireworkList.Add(firework);
            }
        }
    }
        /// <summary>
        /// Creates the typed spark.
        /// </summary>
        /// <param name="explosion">The explosion that gives birth to the spark.</param>
        /// <returns>The new typed spark.</returns>
        protected override Firework CreateSparkTyped(FireworkExplosion explosion)
        {
            Debug.Assert(explosion != null, "Explosion is null");
            Debug.Assert(explosion.ParentFirework != null, "Explosion parent firework is null");
            Debug.Assert(explosion.ParentFirework.Coordinates != null, "Explosion parent firework coordinate collection is null");
            Debug.Assert(this.distribution != null, "Distribution is null");
            Debug.Assert(this.dimensions != null, "Dimension collection is null");
            Debug.Assert(this.randomizer != null, "Randomizer is null");

            Firework spark = new Firework(this.GeneratedSparkType, explosion.StepNumber, explosion.ParentFirework.Coordinates);

            Debug.Assert(spark.Coordinates != null, "Spark coordinate collection is null");

            double offsetDisplacement = this.distribution.Sample(); // Coefficient of Gaussian explosion

            foreach (Dimension dimension in this.dimensions)
            {
                Debug.Assert(dimension != null, "Dimension is null");
                Debug.Assert(dimension.VariationRange != null, "Dimension variation range is null");
                Debug.Assert(!dimension.VariationRange.Length.IsEqual(0.0), "Dimension variation range length is 0");

                if (this.randomizer.NextBoolean()) // Coin flip
                {
                    spark.Coordinates[dimension] *= offsetDisplacement;
                    if (!dimension.IsValueInRange(spark.Coordinates[dimension]))
                    {
                        spark.Coordinates[dimension] = dimension.VariationRange.Minimum + Math.Abs(spark.Coordinates[dimension]) % dimension.VariationRange.Length;
                    }
                }
            }

            return(spark);
        }
Ejemplo n.º 9
0
        private void _btnSelect_Click(object sender, RoutedEventArgs e)
        {
            List <Firework> fireworkList = new List <Firework>();

            foreach (var firework in _dvFireworks.SelectedItems)
            {
                fireworkList.Add((Firework)firework);
            }

            if (fireworkList.Count == 0)
            {
                DialogBoxHelper.ShowWarningMessage("Veuillez sélectionner au moins un feu d'artifice");
                return;
            }

            foreach (Firework fr in fireworkList)
            {
                Firework alreadyThere = _line.Fireworks.FirstOrDefault(f => f.Reference == fr.Reference);

                if (alreadyThere != null)
                {
                    DialogBoxHelper.ShowWarningMessage(string.Format("Le feu d'artifice avec la référence {0} est déjà associé à cette ligne", alreadyThere.Reference));
                    return;
                }
            }

            foreach (Firework fr in fireworkList)
            {
                Firework fireworkClone = fr.GetClone();
                _fireworkManager.AddFireworkToLine(fireworkClone, _line);
            }

            this.Close();
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Zwraca fajerwerk polecany klientowi.
        /// </summary>
        /// <returns>fajerwerk polecany klientowi</returns>
        public Firework GetRecommended()
        {
            // jeœli promowany jest konkretny fajerwerk, nale¿y do zwróciæ
            try
            {
                String        s            = FileFinder.GetFileName("config", "strategy.xml");
                StreamReader  r            = new StreamReader(s);
                XmlSerializer xs           = new XmlSerializer(typeof(String));
                String        promotedName = (String)xs.Deserialize(r);
                r.Close();

                Firework f = Firework.Lookup(promotedName);
                if (f != null)
                {
                    return(f);
                }
            }
            catch {}

            // jeœli klient jest zarejestrowany, trzeba go porównaæ z innymi
            if (IsRegistered())
            {
                return((Firework)Rel8.Advise(this));
            }
            // sprawdzenie wydatków z ubieg³ego roku
            if (SpendingSince(DateTime.Now.AddYears(-1)) > 1000)
            {
                return((Firework)LikeMyStuff.Suggest(this));
            }
            // trudno - bêdzie losowy
            return(Firework.GetRandom());
        }
Ejemplo n.º 11
0
        private void Tile_Click(object sender, RoutedEventArgs e)
        {
            if (Window == null)
            {
                Window     = new CommandsGeneratorTemplate(this);
                Window.win = (Application.Current.MainWindow as IMainWindowCommands).AddWindow(Icon, Window, "命令生成器", this);
                Window.win.WindowClosed += Win_WindowClosed;
            }
            object content = null;
            string title   = (sender as Tile).Title;

            switch (title)
            {
            case "基础命令": content = new BasicCommands(Window); break;

            case "服务器命令": content = new ServerCommands(Window); break;

            case "实体命令": content = new EntityCommands(Window); break;

            case "玩家命令": content = new PlayerCommands(Window); break;

            case "Json书": content = new Book(Window); break;

            case "告示牌": content = new Sign(Window); break;

            case "消息文本": content = new Tellraw(Window); break;

            case "显示标题": content = new Title(Window); break;

            case "记分板目标": content = new ScoreboardObjective(Window); break;

            case "记分板玩家": content = new ScoreboardPlayers(Window); break;

            case "记分板队伍": content = new ScoreboardTeam(Window); break;

            case "物品NBT": content = new ItemNBT(Window); break;

            case "实体NBT": content = new EntityNBT(Window); break;

            case "物品与生成": content = new GetElement(); break;

            case "检测与执行": content = new ExecuteAndDetect(); break;

            case "方块NBT/放置填充方块": content = new SetBlocks(Window); break;

            case "村民交易": content = new VillagerTrade(Window); break;

            case "刷怪笼": content = new MobSpawner(Window); break;

            case "烟花": content = new Firework(Window); break;

            case "旗帜/盾牌": content = new Banners(Window); break;

            case "药水/药水箭": content = new Potion(Window); break;

            case "盔甲架": content = new ArmorStand(Window); break;
            }
            Window.AddPage(title, content);
        }
        /// <summary>
        /// Compares two <see cref="Firework"/>s and determines if it is necessary to replace the worst one
        /// with the elite one according to the elite strategy.
        /// </summary>
        /// <param name="worst">The worst firework on current step.</param>
        /// <param name="elite">The elite firework on current step calculated by
        /// elite strategy</param>
        /// <returns><c>true</c> if necessary replace <paramref name="worst"/> with
        /// <paramref name="elite"/>.</returns>
        public bool ShouldReplaceWorstWithElite(Firework worst, Firework elite)
        {
            Debug.Assert(worst != null, "Worst firework is null");
            Debug.Assert(elite != null, "Elite firework is null");
            Debug.Assert(this.ProblemToSolve != null, "Problem to solve is null");

            return(this.ProblemToSolve.Target == ProblemTarget.Minimum ? worst.Quality.IsGreater(elite.Quality) : worst.Quality.IsLess(elite.Quality));
        }
Ejemplo n.º 13
0
        public void LoadFirework(Firework firework)
        {
            var gameSession = World.StorageManager.GetGameSession(Player.Id);

            if (!LoadedObjects.ContainsKey(firework.Id))
            {
                LoadedObjects.TryAdd(firework.Id, firework);
            }
            Packet.Builder.MineCreateCommand(gameSession, firework.Hash, firework.FireworkType, firework.Position, false);
        }
Ejemplo n.º 14
0
 // Token: 0x06000274 RID: 628 RVA: 0x00013708 File Offset: 0x00011908
 public void paint(mGraphics g)
 {
     for (int i = 0; i < this.fw.size(); i++)
     {
         Firework firework = (Firework)this.fw.elementAt(i);
         if (firework.y < -200)
         {
             this.fw.removeElementAt(i);
         }
         firework.paint(g);
     }
 }
Ejemplo n.º 15
0
        private void FireworkTimeline_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                Firework f = (Firework)e.AddedItems[0];
                //DialogBoxHelper.ShowInformationMessage("Ligne sélectionnée : ");

                _viewModel.LaunchFailedLine(f.AssignedLine.Number);

                _fireworkTimeline.SelectedItem = null;
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Calculates the quality for the given <paramref name="firework"/>.
        /// </summary>
        /// <param name="firework">The firework to calculate quality for.</param>
        /// <remarks>It is expected that <paramref name="firework"/> hasn't got its quality calculated before.</remarks>
        public virtual void CalculateQuality(Firework firework)
        {
            if (firework == null)
            {
                throw new ArgumentNullException(nameof(firework));
            }

            Debug.Assert(this.ProblemToSolve != null, "Problem to solve is null");
            Debug.Assert(double.IsNaN(firework.Quality), "Excessive quality calculation"); // If quality is not NaN, it most likely has been already calculated

            firework.Quality = this.ProblemToSolve.CalculateQuality(firework.Coordinates);
        }
Ejemplo n.º 17
0
 // look for a promoted firework
 private PromotionAdvisor()
 {
     try
     {
         String        s    = FileFinder.GetFileName("config", "strategy.xml");
         StreamReader  r    = new StreamReader(s);
         XmlSerializer xs   = new XmlSerializer(typeof(String));
         String        name = (String)xs.Deserialize(r);
         r.Close();
         _promoted = Firework.Lookup(name);
     }
     catch {}
 }
Ejemplo n.º 18
0
        public void FirewordExplosion_NullAs1stParam_ExceptionThrown()
        {
            Firework parent     = null;
            int      stepNumber = 1;
            double   amplidute  = 1.0;
            Dictionary <FireworkType, int> sparkCounts = new Dictionary <FireworkType, int>();
            string expectedParamName = "parentFirework";

            ArgumentNullException actualException = Assert.Throws <ArgumentNullException>(() => new FireworkExplosion(parent, stepNumber, amplidute, sparkCounts));

            Assert.NotNull(actualException);
            Assert.Equal(expectedParamName, actualException.ParamName);
        }
Ejemplo n.º 19
0
        public void FirewordExplosion_InfinityAs3tdParam_ExceptionThrown()
        {
            Firework parent     = new Firework(FireworkType.Initial, 1);
            int      stepNumber = 1;
            double   amplidute  = double.PositiveInfinity;
            Dictionary <FireworkType, int> sparkCounts = new Dictionary <FireworkType, int>();
            string expectedParamName = "amplitude";

            ArgumentOutOfRangeException actualException = Assert.Throws <ArgumentOutOfRangeException>(() => new FireworkExplosion(parent, stepNumber, amplidute, sparkCounts));

            Assert.NotNull(actualException);
            Assert.Equal(expectedParamName, actualException.ParamName);
        }
Ejemplo n.º 20
0
        public void TryAddFireworksReference(Firework firework)
        {
            Firework f = (from fw in _fireworks
                          where fw.Reference == firework.Reference
                          select fw).FirstOrDefault();

            if (f == null)
            {
                Firework newFirework = firework.GetClone();
                _fireworks.Add(newFirework);
                SaveFireworks();
            }
        }
Ejemplo n.º 21
0
        public void Load()
        {
            //TODO : Handle exeption  if conf. file does not exists
            //TODO : Handle exeption  if fireworks file does not exists

            //Load config file
            XDocument confFile = XDocument.Load(GetConfigFileName());

            //Load default receptors definition
            List <XElement> receptors = (from r in confFile.Descendants("Receptor")
                                         select r).ToList();

            _receptors.Clear();
            foreach (XElement r in receptors)
            {
                Receptor recep = new Receptor(r.Attribute("name").Value, r.Attribute("address").Value.ToString(), Convert.ToInt32(r.Attribute("nbOfChannels").Value.ToString()));
                _receptors.Add(recep);
            }

            //Excel
            XElement excelFile = confFile.Descendants("ExcelFile").First();

            _excelFireworkName = excelFile.Element("FireworkName").Value.ToString();
            _excelFirstRowData = Convert.ToInt32(excelFile.Element("FireworkDataRow").Value.ToString());
            _excelSheetNumber  = Convert.ToInt32(excelFile.Element("FireworkSheetNumber").Value.ToString());

            //Transceiver
            XElement transceiver = confFile.Descendants("Transceiver").First();

            //_ackTimeOut= Convert.ToInt32(transceiver.Element("AckTimeOut").Value.ToString());
            _totalTimeOut        = Convert.ToInt32(transceiver.Element("TotalTimeout").Value.ToString());
            _retryFrameEmission  = Convert.ToInt32(transceiver.Element("RetryFrameEmission").Value.ToString());
            _transceiverAddress  = transceiver.Element("Address").Value.ToString();
            _transceiverBaudrate = Convert.ToInt32(transceiver.Element("Baudrate").Value.ToString());
            //_tranceiverRetryPing = Convert.ToInt32(transceiver.Element("RetryPingTransceiver").Value.ToString());

            //*** Fireworks
            XDocument fireworksFile = XDocument.Load(GetFireworksFileName());

            List <XElement> fireworks = (from r in fireworksFile.Descendants("Firework")
                                         select r).ToList();

            _fireworks.Clear();
            foreach (XElement fw in fireworks)
            {
                TimeSpan duration = TimeSpan.Parse(fw.Attribute("duration").Value.ToString());
                Firework f        = new Firework(fw.Attribute("reference").Value.ToString(), fw.Attribute("designation").Value.ToString(), duration);

                _fireworks.Add(f);
            }
        }
Ejemplo n.º 22
0
    // Update is called once per frame
    void Update()
    {
        m_fireworkTimer += Time.deltaTime;
        if (m_fireworkTimer >= m_timePerFirework)
        {
            m_fireworkTimer -= m_timePerFirework;
            Firework firework = Instantiate(m_firework, transform);

            firework.m_timeToExplode = Random.value + .5f;
            Destroy(firework.gameObject, firework.m_timeToExplode + 2.0f);

            firework.GetComponent <Rigidbody>().AddForce(Random.onUnitSphere * 300, ForceMode.Force);
        }
    }
Ejemplo n.º 23
0
        /// <summary>
        /// Defines the exact (not rounded) count of the explosion sparks.
        /// </summary>
        /// <param name="focus">The explosion focus.</param>
        /// <param name="currentFireworks">The collection of fireworks that exist at the moment of explosion.</param>
        /// <param name="currentFireworkQualities">The current firework qualities.</param>
        /// <returns>The exact (not rounded) number of explosion sparks created by that explosion.</returns>
        private double CountExplosionSparksExact(Firework focus, IEnumerable <Firework> currentFireworks, IEnumerable <double> currentFireworkQualities)
        {
            Debug.Assert(focus != null, "Focus is null");
            Debug.Assert(currentFireworks != null, "Current fireworks is null");
            Debug.Assert(currentFireworkQualities != null, "Current firework qualities is null");
            Debug.Assert(this.settings != null, "Settings is null");

            double worstFireworkQuality = this.extremumFireworkSelector.SelectWorst(currentFireworks).Quality;

            Debug.Assert(!double.IsNaN(worstFireworkQuality), "Worst firework quality is NaN");
            Debug.Assert(!double.IsInfinity(worstFireworkQuality), "Worst firework quality is Infinity");

            return(this.settings.ExplosionSparksNumberModifier * (worstFireworkQuality - focus.Quality + double.Epsilon) / (currentFireworkQualities.Sum(fq => worstFireworkQuality - fq) + double.Epsilon));
        }
        public NearBestSelectorTests()
        {
            this.samplingNumber     = SelectorTestsHelper.SamplingNumber;
            this.countFireworks     = SelectorTestsHelper.CountFireworks;
            this.getBest            = SelectorTestsHelper.GetBest;
            this.bestFirework       = SelectorTestsHelper.FirstBestFirework;
            this.allFireworks       = new List <Firework>(SelectorTestsHelper.Fireworks);
            this.distanceCalculator = Substitute.For <IDistance>();
            for (int i = 1; i < 10; i++)
            {
                this.distanceCalculator.Calculate(this.bestFirework, this.allFireworks[i]).Returns(i);
            }

            this.nearBestSelector = new NearBestFireworkSelector(this.distanceCalculator, this.getBest, this.samplingNumber);
        }
Ejemplo n.º 25
0
    public void CreateFirework(Firework prefab, Vector3 position)
    {
        var firework = Instantiate(prefab, position, Quaternion.identity) as Firework;

        firework.t.SetParent(ui.game.stuffFront, true);
        firework.name = "Firework " + ++LAST_ID;

        firework.t.localScale = halfScale;
        firework.t.DOScale(Vector3.one, 0.5f).SetEase(Ease.OutBack);

        if (firework is FireworkRocket)
        {
            (firework as FireworkRocket).RotateToCenter(position);
        }
    }
Ejemplo n.º 26
0
        /// <summary>
        /// Calculates the explosion amplitude.
        /// </summary>
        /// <param name="focus">The explosion focus.</param>
        /// <param name="currentFireworks">The collection of fireworks that exist at the moment of explosion.</param>
        /// <param name="currentFireworkQualities">The current firework qualities.</param>
        /// <returns>The explosion amplitude.</returns>
        protected virtual double CalculateAmplitude(Firework focus, IEnumerable <Firework> currentFireworks, IEnumerable <double> currentFireworkQualities)
        {
            Debug.Assert(focus != null, "Focus is null");
            Debug.Assert(currentFireworks != null, "Current fireworks is null");
            Debug.Assert(currentFireworkQualities != null, "Current firework qualities is null");
            Debug.Assert(this.extremumFireworkSelector != null, "Extremum firework selector is null");
            Debug.Assert(this.settings != null, "Settings is null");

            double bestFireworkQuality = this.extremumFireworkSelector.SelectBest(currentFireworks).Quality;

            Debug.Assert(!double.IsNaN(bestFireworkQuality), "Best firework quality is NaN");
            Debug.Assert(!double.IsInfinity(bestFireworkQuality), "Best firework quality is Infinity");

            return(this.settings.ExplosionSparksMaximumAmplitude * (focus.Quality - bestFireworkQuality + double.Epsilon) / (currentFireworkQualities.Sum(fq => fq - bestFireworkQuality) + double.Epsilon));
        }
        /// <summary>
        /// Selects <paramref name="numberToSelect"/> the best <see cref="Firework"/>s from
        /// the <paramref name="from"/> collection. Selected <see cref="Firework"/>s
        /// are stored in the new collection, <paramref name="from"/> is not modified.
        /// </summary>
        /// <param name="from">A collection to select <see cref="Firework"/>s
        /// from.</param>
        /// <param name="numberToSelect">The number of <see cref="Firework"/>s
        /// to select.</param>
        /// <returns>
        /// A subset of the best <see cref="Firework"/>s.
        /// </returns>
        /// <exception cref="System.ArgumentNullException"> if <paramref name="from"/>
        /// is <c>null</c>.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException"> if <paramref name="numberToSelect"/>
        /// is less than zero or greater than the number of elements in <paramref name="from"/>.
        /// </exception>
        public override IEnumerable <Firework> SelectFireworks(IEnumerable <Firework> from, int numberToSelect)
        {
            if (from == null)
            {
                throw new ArgumentNullException(nameof(from));
            }

            if (numberToSelect < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(numberToSelect));
            }

            if (numberToSelect > from.Count())
            {
                throw new ArgumentOutOfRangeException(nameof(numberToSelect));
            }

            if (numberToSelect == from.Count())
            {
                return(new List <Firework>(from));
            }

            Debug.Assert(this.bestFireworkSelector != null, "Best firework selector is null");

            List <Firework> bestFireworks = new List <Firework>(numberToSelect);

            if (numberToSelect == 1)
            {
                // Handle "give me one best firework" case separately
                // for performance
                bestFireworks.Add(this.bestFireworkSelector(from));
            }
            else if (numberToSelect > 1)
            {
                // Find fireworks with the best quality based on a sampling number
                List <Firework> currentFireworks = new List <Firework>(from);
                for (int i = 0; i < numberToSelect; i++)
                {
                    // TODO: It makes sense to sort the collection first, and then take
                    // the first ones.
                    Firework bestFirework = this.bestFireworkSelector(currentFireworks);
                    bestFireworks.Add(bestFirework);
                    currentFireworks.Remove(bestFirework);
                }
            }

            return(bestFireworks);
        }
        /// <summary>
        /// Selects <paramref name="numberToSelect"/> <see cref="Firework"/>s from
        /// the <paramref name="from"/> collection. Selected <see cref="Firework"/>s
        /// are stored in the new collection, <paramref name="from"/> is not modified.
        /// </summary>
        /// <param name="from">A collection to select <see cref="Firework"/>s
        /// from.</param>
        /// <param name="numberToSelect">The number of <see cref="Firework"/>s
        /// to select.</param>
        /// <returns>
        /// A subset of <see cref="Firework"/>s.
        /// </returns>
        /// <exception cref="System.ArgumentNullException"> if <paramref name="from"/>
        /// is <c>null</c>.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException"> if <paramref name="numberToSelect"/>
        /// is less than zero or greater than the number of elements in <paramref name="from"/>.
        /// </exception>
        public override IEnumerable <Firework> SelectFireworks(IEnumerable <Firework> from, int numberToSelect)
        {
            if (from == null)
            {
                throw new ArgumentNullException(nameof(from));
            }

            if (numberToSelect < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(numberToSelect));
            }

            if (numberToSelect > from.Count())
            {
                throw new ArgumentOutOfRangeException(nameof(numberToSelect));
            }

            if (numberToSelect == from.Count())
            {
                return(new List <Firework>(from));
            }

            List <Firework> selectedLocations = new List <Firework>(numberToSelect);

            if (numberToSelect > 0)
            {
                Debug.Assert(this.bestFireworkSelector != null, "Best firework selector is null");

                // 1. Find a firework with best quality
                Firework bestFirework = this.bestFireworkSelector(from);

                // 2. Calculate distances near best firework
                IDictionary <Firework, double> distances = this.CalculateDistances(from, bestFirework);
                Debug.Assert(distances != null, "Distance collection is null");

                // 3. Select nearest individuals
                IOrderedEnumerable <KeyValuePair <Firework, double> > sortedDistances = distances.OrderBy(p => p.Value, new DoubleExtensionComparer());
                Debug.Assert(sortedDistances != null, "Sorted distances collection is null");

                IEnumerable <Firework> nearestLocations = sortedDistances.Take(numberToSelect).Select(sp => sp.Key);
                Debug.Assert(nearestLocations != null, "Nearest locations collection is null");

                selectedLocations.AddRange(nearestLocations);
            }

            return(selectedLocations);
        }
Ejemplo n.º 29
0
    public void CreateFireworkAndMove(Firework prefab, Vector3 from, Vector3 to)
    {
        var firework = Instantiate(prefab, from, Quaternion.identity) as Firework;

        firework.t.SetParent(ui.game.stuffFrontFront, true);
        firework.name = "Firework " + ++LAST_ID;

        firework.t.localScale = Vector3.zero;
        firework.t.DOScale(Vector3.one, 1.5f).SetEase(Ease.OutBack);

        if (firework is FireworkRocket)
        {
            (firework as FireworkRocket).RotateToCenter(to);
        }

        firework.Spread(to);
    }
Ejemplo n.º 30
0
        //TODO: lazy initialization collection of fireworks
        private static void FormFireworks()
        {
            Range           range     = new Range(intervalLowerLimit, intervalUpperLimit);
            List <Firework> fireworks = new List <Firework>();
            IDictionary <Dimension, double> coordinates;

            for (int i = 1; i < CountFireworks + 1; i++)
            {
                coordinates = new Dictionary <Dimension, double>();
                coordinates.Add(new Dimension(range), i);
                coordinates.Add(new Dimension(range), i);
                Firework firework = new Firework(FireworkType.Initial, 0, coordinates);
                firework.Quality = i;
                fireworks.Add(firework);
            }

            Fireworks = fireworks;
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Changes the <paramref name="firework"/>.
        /// </summary>
        /// <param name="firework">The <see cref="MutableFirework"/> to be changed.</param>
        /// <param name="explosion">The <see cref="FireworkExplosion"/> that
        /// contains explosion characteristics.</param>
        /// <exception cref="System.ArgumentNullException"> if <paramref name="firework"/>
        /// or <paramref name="explosion"/> is <c>null</c>.</exception>
        public void MutateFirework(ref MutableFirework firework, FireworkExplosion explosion)
        {
            if (firework == null)
            {
                throw new ArgumentNullException(nameof(firework));
            }

            if (explosion == null)
            {
                throw new ArgumentNullException(nameof(explosion));
            }

            Debug.Assert(this.generator != null, "Generator is null");

            Firework newState = this.generator.CreateSpark(explosion);

            Debug.Assert(newState != null, "New state is null");

            firework.Update(newState);
        }
		public override void Draw(SpriteBatch sb, Projectile p, Firework f) {
			trail.Insert(0,new Vector2(pos.X,pos.Y));
			for (int i = 0; i < Math.Min(trail.Count,10); i++) {
				Vector2 v = trail[i];
				float alpha = (10-i)/10f;
				sb.Draw(ptFuzzy,v-Main.screenPosition,GetRectFuzzy(),new Color(color.R,color.G,color.B,(byte)(color.A*alpha*.5f)),0f,GetCenterFuzzy(),GetScaleFuzzy(36f),SpriteEffects.None,0f);
				sb.Draw(ptFuzzy,v-Main.screenPosition,GetRectFuzzy(),new Color(color.R,color.G,color.B,(byte)(color.A*alpha)),0f,GetCenterFuzzy(),GetScaleFuzzy(12f),SpriteEffects.None,0f);
			}
			if (trail.Count > 10) trail.RemoveAt(10);
			Lighting.addLight((int)Math.Round(pos.X/16f),(int)Math.Round(pos.Y/16f),color.R/255f*(color.A/255f),color.G/255f*(color.A/255f),color.B/255f*(color.A/255f));
			
			pos += vel;
			vel.Y += .075f;
			
			if (timeLeft > 0) {
				timeLeft--;
			} else {
				color.A = (byte)Math.Max(color.A-10,0);
				if (color.A == 0) dead = true;
			}
		}
Ejemplo n.º 33
0
	public virtual void Draw(SpriteBatch sb, Projectile p, Firework f) {}