public void flipRaining() { if(isRaining){ //Support.SoundSystem.Instance.Play("rain.wav"); var rainsprite = Support.TiledSpriteFromFile("/Application/assets/rain_Sheet.png", 9, 1); var raincountX = Camera.CalcBounds().Max.X/rainsprite.Quad.X.X; var raincountY = Camera.CalcBounds().Max.Y/rainsprite.Quad.Y.Y; var currentPos = new Vector2(0, 20); for(var i = 0; i < raincountY; i++){ for(int j = 0; j < raincountX; j++){ rainsprite = Support.TiledSpriteFromFile("/Application/assets/rain_Sheet.png", 9, 1); rainsprite.CenterSprite(); rainsprite.Position = currentPos; rainsprite.VertexZ = 1; this.AddChild(rainsprite,1); rain.Add(rainsprite); var RainAnimation = new Support.AnimationAction(rainsprite, 9, 1, 1.0f, looping: true); var Wait = new DelayTime((float)rng.NextDouble() * 2); var seq = new Sequence(); seq.Add(Wait); seq.Add(RainAnimation); rainsprite.RunAction(seq); currentPos += new Vector2(rainsprite.Quad.X.X, 0); } currentPos = new Vector2(0, currentPos.Y + rainsprite.Quad.Y.Y); } } else { for(int i = 0; i < rain.Count; i++){ GameScene.Instance.RemoveChild(rain[i], true); } rain.Clear(); } }
public void SequenceTestSerialize() { Sequence<int> before = new Sequence<int>(3); before.AddRange( new[] {1,2}); before.Add(3); before.Add(4); Assert.Equal(4, before[0]); Assert.Equal(3, before[1]); Assert.Equal(2, before[2]); Assert.Equal(3, before.Capacity); Assert.Equal(4, before.CountOfAllObservedItems); //JsonSerializerSettings serializerSettings = new JsonSerializerSettings(); //serializerSettings.Converters.Add(new SequenceConverter()); string serialized = JsonConvert.SerializeObject(before); Sequence<int> after = JsonConvert.DeserializeObject<Sequence<int>>(serialized); Assert.Equal(4, after[0]); Assert.Equal(3, after[1]); Assert.Equal(2,after[2]); Assert.Equal(3, after.Capacity); Assert.Equal(4, after.CountOfAllObservedItems); Assert.Equal(before, after); }
public Boolean checkCellWin(Cell c) { Sequence seq; if (c.type == goalMutation){ //Support.SoundSystem.Instance.Play("blip.wav"); goalSprite.Visible = false; var right = Support.TiledSpriteFromFile("/Application/assets/display_GOOD.png", 1, 1); GameScene.Instance.AddChild(right); right.CenterSprite(); right.Quad.S = right.TextureInfo.TextureSizef/2; right.Position = goalSprite.Position; right.VertexZ = 1; seq = new Sequence(); seq.Add(new DelayTime(2)); seq.Add(new CallFunc(() => { GameScene.Instance.RemoveChild(right, true); goalSprite.Visible = true;})); GameScene.Instance.RunAction(seq); return true; } //Support.SoundSystem.Instance.Play("blip.wav"); goalSprite.Visible = false; var wrong = Support.TiledSpriteFromFile("/Application/assets/display_BAD.png", 1, 1); wrong.CenterSprite(); wrong.Quad.S = wrong.TextureInfo.TextureSizef/2; wrong.Position = goalSprite.Position; wrong.VertexZ = 1; GameScene.Instance.AddChild(wrong); seq = new Sequence(); seq.Add(new DelayTime(2)); seq.Add(new CallFunc(() => { GameScene.Instance.RemoveChild(wrong, true); goalSprite.Visible = true;;})); GameScene.Instance.RunAction(seq); return false; }
// METHODS ----------------------------------------------------------------------------------------- public void OnMoveComplete() { Sequence sequence = new Sequence(); sequence.Add( new DelayTime( GameScene.Random.NextFloat() * 1.0f ) ); sequence.Add( new MoveTo( BASE + GameScene.Random.NextFloat() * RANGE, 1.0f + 1.0f * GameScene.Random.NextFloat() ) ); sequence.Add( new CallFunc( () => { OnMoveComplete(); } ) ); this.RunAction( sequence ); }
/// <summary> /// スプライトを見えなくし、一定時間後元に戻すエフェクト /// </summary> /// <param name='sprite'> /// Sprite. /// </param> public static void Disappear(SpriteUV sprite) { Global.characterActive = false; var seq = new Sequence(); seq.Add(new CallFunc(()=>Disappear1(sprite))); seq.Add(new CallFunc(()=>{sprite.Visible = false;})); seq.Add(new MoveBy(new Vector2(0,0),2)); seq.Add(new CallFunc(()=>Appear(sprite))); sprite.RunAction(seq); }
public override AbstractCrystallonEntity BeAddedToGroup(GroupCrystallonEntity pGroup) { pGroup.Attach( this ); if (pGroup is SelectionGroup) { getNode().StopActionByTag(20); Sequence sequence = new Sequence() { Tag = 20 }; sequence.Add( new DelayTime( 3.0f ) ); sequence.Add( new CallFunc( () => { playSound(); } ) ); getNode().RunAction(sequence); } return this; }
public void testClone() { var sequence = new Sequence(); sequence.Add("a", 10); sequence.Add("b", 20); var copy = sequence.Clone() as Sequence; Assert.NotNull(copy); Assert.True(sequence.Outcomes.SequenceEqual(copy.Outcomes)); Assert.True(sequence.Probabilities.SequenceEqual(copy.Probabilities)); Assert.True(sequence.CompareTo(copy) == 0); }
private Sequence<InstructionNode> Create(IEnumerator<XamlInstruction> stream) { var nodes = new Sequence<InstructionNode>(); while (IsLeading(stream.Current)) { var currentNode = new InstructionNode { Leading = stream.Current }; var continueWorking = true; while (stream.MoveNext() && continueWorking) { if (IsLeading(stream.Current)) { currentNode.Children = Create(stream); } var xamlNode = stream.Current; if (IsTrailing(xamlNode)) { continueWorking = false; currentNode.Trailing = stream.Current; } else { currentNode.Body.Add(stream.Current); } } nodes.Add(currentNode); } return nodes; }
public void testAddMethod() { var sequence = new Sequence(); sequence.Add("a", 10d); Assert.AreEqual("a", sequence.Outcomes[0]); Assert.AreEqual(10d, sequence.Probabilities[0]); }
public EnemySlime() { Sprite = Support.TiledSpriteFromFile("/Application/assets/slime_green_frames.png", 4, 4); IdleAnimation = new Support.AnimationAction(Sprite, 0, 8, 0.5f, looping: true); JumpInAnimation = new Support.AnimationAction(Sprite, 8, 12, 0.3f, looping: false); JumpMidAnimation = new Support.AnimationAction(Sprite, 12, 13, 1.0f, looping: false); JumpOutAnimation = new Support.AnimationAction(Sprite, 13, 16, 0.2f, looping: false); JumpAnimationSequence = new Sequence(); JumpAnimationSequence.Add(JumpInAnimation); JumpAnimationSequence.Add(new CallFunc(this.Jump)); JumpAnimationSequence.Add(JumpMidAnimation); JumpAnimationSequence.Add(new DelayTime() { Duration = 0.40f }); JumpAnimationSequence.Add(JumpOutAnimation); JumpAnimationSequence.Add(new DelayTime() { Duration = 0.05f }); JumpAnimationSequence.Add(IdleAnimation); this.AddChild(Sprite); Sprite.RunAction(IdleAnimation); // CollisionDatas.Add(new EntityCollider.CollisionEntry() { // type = EntityCollider.CollisionEntityType.Enemy, // owner = this, // collider = Sprite, // center = () => GetCollisionCenter(Sprite) + new Vector2(0.0f, -8.0f), // radius = () => 24.0f, // }); // // GroundFriction = new Vector2(0.85f); Health = 2.0f; MoveDelay = 3.0f; }
private static void TestGunshotTrack(Sequence sequence) { var track = new Track(); track.Insert(0, new ChannelMessage(ChannelCommand.ProgramChange, 1, 127)); track.Insert(0, new ChannelMessage(ChannelCommand.NoteOn, 1, 35, 127)); track.Insert(100, new ChannelMessage(ChannelCommand.NoteOff, 1, 35, 0)); track.Insert(101, new ChannelMessage(ChannelCommand.NoteOn, 1, 76, 127)); track.Insert(200, new ChannelMessage(ChannelCommand.NoteOff, 1, 76, 0)); sequence.Add(track); }
// protected Label inside; public ScorePopup(Node pParent, int pPoints) : base(pPoints.ToString(), map) { parent = pParent; if (pPoints < 10) { offset = DoubleDigitOffset; } else { offset = SingleDigitOffset; } // velocity = Vector2.Zero; Position = parent.LocalToWorld(parent.Position) + offset; // this.RegisterPalette(0); Color = Support.ExtractColor("333330"); Pivot = new Vector2(0.5f, 0.5f); // HeightScale = 1.0f; // inside = new Label() { // Text = pPoints.ToString(), // FontMap = map, // Pivot = Vector2.One/2.0f, //// Position = Vector2.One //// Scale = new Vector2(0.9f, 0.9f) // }; // inside.Color = LevelManager.Instance.BackgroundColor; // this.AddChild(inside); Sequence sequence = new Sequence(); sequence.Add( new DelayTime( 0.1f ) ); GameScene.Layers[2].AddChild(this); sequence.Add( new CallFunc( () => { Scheduler.Instance.ScheduleUpdateForTarget(this,0,false); } ) ); this.RunAction(sequence); #if DEBUG Console.WriteLine (GetType().ToString() + " created" ); #endif }
public ScorePanel( ICrystallonEntity pEntity, int pPoints ) { InitializeWidget(); ScoreLabel = new Sce.PlayStation.HighLevel.GameEngine2D.Label() { Text = pPoints.ToString() }; var font = new Font("Application/assets/fonts/Bariol_Regular.otf", 25, FontStyle.Regular); var map = new FontMap(font); ScoreLabel.FontMap = map; ScoreLabel.Position = new Vector2(-4.0f, 10.0f); ScoreLabel.Color = Colors.White; ScoreLabel.HeightScale = 1.0f; ScoreLabel.Pivot = new Vector2(0.5f, 0.5f); Sequence sequence = new Sequence(); sequence.Add( new DelayTime( 0.5f ) ); sequence.Add ( new CallFunc( () => { pEntity.getNode().Parent.AddChild(ScoreLabel); } ) ); // ScoreText.Font = FontManager.Instance.Get ("Bariol", 20, "Bold"); // ScoreText.Text = pPoints.ToString(); // ScoreText.Alpha = 0.0f; // _scoreTexture = new Texture2D((int)ScoreText.Width, (int)ScoreText.Height, false, PixelFormat.Rgba); // ScoreText.RenderToTexture(_scoreTexture); // _scoreTextureInfo = new TextureInfo(_scoreTexture); // _scoreSprite = new SpriteUV(_scoreTextureInfo); // _scoreSprite.Pivot = new Vector2(0.5f, 0.5f); // pEntity.getNode().AddChild(_scoreSprite); // _scoreSprite.Position = new Vector2(0.0f, 20.0f); // Vector2 v = ConvertScreenToLocal( pPosition ); // this.SetPosition( v.X - ScoreText.Width/2, Director.Instance.GL.Context.GetViewport().Height - (v.Y + 40) ); // Sequence sequence = new Sequence(); // sequence.Add( new DelayTime( 3.0f ) ); // sequence.Add ( new CallFunc( () => { // ScoreText.Visible = false; // this.Dispose(); // } ) ); Director.Instance.CurrentScene.RunAction(sequence); }
public static void Main(String[] args) { Sequence<int> sequence = new Sequence<int>(10); for(int i = 0; i < 10; i++) { sequence.Add(i); } ISelector selector = sequence.Selector(); while(!selector.End()) { Console.WriteLine(selector.Current()); selector.Next(); } }
// METHODS ---------------------------------------------- public void Flash() { Sequence sequence = new Sequence(); sequence.Add( new CallFunc( () => TintTo( QColor.palette[1], 0.08f, false) ) ); sequence.Add( new DelayTime(0.08f) ); sequence.Add( new CallFunc( () => TintTo( QColor.palette[2], 0.08f, false) ) ); sequence.Add( new DelayTime(0.08f) ); sequence.Add( new CallFunc( () => TintTo( QColor.palette[0], 0.08f, false) ) ); sequence.Add( new DelayTime(0.08f) ); this.getNode().RunAction( new RepeatForever() { InnerAction=sequence, Tag = 40 } ); }
public static void Save(List<List<Event>> allEvents, string path) { Sequence sequence = new Sequence(); Dictionary<int, Track> tracks = new Dictionary<int, Track>(); for (int trackIndex = 0; trackIndex < allEvents.Count; trackIndex++) { Track track = new Track(); sequence.Add(track); List<Event> trackEvents = allEvents[trackIndex]; foreach (var midiEvent in trackEvents.Select(trackEvent => new { Tick = trackEvent.Tick, MidiMessage = Convert(trackEvent, track) })) { track.Insert(midiEvent.Tick, midiEvent.MidiMessage); } } sequence.Save(path); }
private static void TestPianoTrack(Sequence sequence) { var track = new Track(); track.Insert(0, new ChannelMessage(ChannelCommand.ProgramChange, 0, 0)); track.Insert(0, new ChannelMessage(ChannelCommand.NoteOn, 0, 35, 127)); track.Insert(100, new ChannelMessage(ChannelCommand.NoteOff, 0, 35, 0)); track.Insert(101, new ChannelMessage(ChannelCommand.NoteOn, 0, 76, 127)); track.Insert(200, new ChannelMessage(ChannelCommand.NoteOff, 0, 76, 0)); for (int i = 0; i < 1000; i += 10) { track.Insert(i, new ChannelMessage(ChannelCommand.NoteOn, 0, 76, 127)); track.Insert(i + 9, new ChannelMessage(ChannelCommand.NoteOff, 0, 76)); } sequence.Add(track); }
public void testCompareTo() { var lowScore = new Sequence(); lowScore.Add("A", 1d); lowScore.Add("B", 2d); lowScore.Add("C", 3d); var highScore = new Sequence(); lowScore.Add("A", 7d); lowScore.Add("B", 8d); lowScore.Add("C", 9d); Assert.AreEqual(-1, lowScore.CompareTo(highScore)); Assert.AreEqual(1, highScore.CompareTo(lowScore)); Assert.AreEqual(0, highScore.CompareTo(highScore)); }
public void SlideIn(SlideDirection pDirection) { Position = Offset; if( SourceObject != null ) { Position += SourceObject.Position; } Vector2 Destination; switch(pDirection){ case(SlideDirection.LEFT): Destination = new Vector2(Position.X - Width, Position.Y); break; case(SlideDirection.RIGHT): Position += new Vector2(-Width, 0.0f); Destination = new Vector2(Position.X + Width, Position.Y); break; case(SlideDirection.UP): Position += new Vector2(0.0f, -Height); Destination = new Vector2(Position.X, Position.Y + Height); break; case(SlideDirection.DOWN): default: Destination = new Vector2(Position.X, Position.Y - Height); break; } Sequence baseSequence = new Sequence(); baseSequence.Add( new CallFunc( () => { Visible = true; EventHandler handler = OnSlideInStart; if ( handler != null ) { handler( this, null ); } } ) ); baseSequence.Add( new MoveTo( Destination, MoveDuration) ); baseSequence.Add( new CallFunc( () => { EventHandler handler = OnSlideInComplete; if ( handler != null ) { handler( this, null ); } } ) ); this.RunAction( baseSequence ); if (DismissDelay > 0.0f) { Sequence sequence = new Sequence(); sequence.Add( new DelayTime(DismissDelay) ); sequence.Add( new CallFunc( () => {AllowDismiss (); } ) ); this.RunAction(sequence); } if (Lifetime > 0.0f) { Sequence sequence = new Sequence(); sequence.Add( new DelayTime(1.0f + Lifetime) ); sequence.Add( new CallFunc( () => {SlideOut(); } ) ); this.RunAction(sequence); } }
public void ValidateStructureRulesRequirements(IEnumerable <IObjectOnServer> serverObjects, bool isADDS) { bool isAllowedParent = false; List <string> sampleClasses = new List <string>(); sampleClasses.Add("organization"); sampleClasses.Add("attributeSchema"); sampleClasses.Add("account"); sampleClasses.Add("classSchema"); foreach (IObjectOnServer serverObj in serverObjects) { if (sampleClasses.Contains(serverObj.Name)) { //Get possSuperior value Sequence <string> possSuperiors = new Sequence <string>(); if (serverObj.Properties.ContainsKey(StandardNames.possSuperiors.ToLower())) { foreach (string element in serverObj.Properties[StandardNames.possSuperiors.ToLower()]) { possSuperiors = possSuperiors.Add(element); } } if (serverObj.Properties.ContainsKey(StandardNames.systemPossSuperiors.ToLower())) { foreach (string element in serverObj.Properties[StandardNames.systemPossSuperiors.ToLower()]) { possSuperiors = possSuperiors.Add(element); } } //For each possSuperior. foreach (string possSuperior in possSuperiors) { isAllowedParent = false; //Get distinguishedName of this possSuperior from model to get this object from server. ModelObject possSuperiorObject; if (isADDS) { possSuperiorObject = dcModel.GetClass(possSuperior); } else { possSuperiorObject = adamModel.GetClass(possSuperior); } if (possSuperiorObject == null) { DataSchemaSite.Assume.IsNotNull( possSuperiorObject, "Class " + possSuperior + " is not existing in Model"); } string possSuperiorDN = (string)possSuperiorObject[StandardNames.distinguishedName].UnderlyingValues[0]; //Get this possSuperior from Server DirectoryEntry possSuperiorServerObject; if (isADDS) { if (!adAdapter.GetObjectByDN(possSuperiorDN, out possSuperiorServerObject)) { DataSchemaSite.Assume.IsTrue(false, possSuperiorDN + " Object is not found in server"); } } else { if (!adAdapter.GetLdsObjectByDN(possSuperiorDN, out possSuperiorServerObject)) { DataSchemaSite.Assume.IsTrue(false, possSuperiorDN + " Object is not found in server"); } } //Get possibleInfeiror value of possSuperiorClass. possSuperiorServerObject.RefreshCache(new string[] { "possibleinferiors" }); PropertyValueCollection possInferiorVal = possSuperiorServerObject. Properties[StandardNames.possibleInferiors.ToLower()]; //In all possSuperior object, this class name should exist in its possibleInferiors. foreach (string possInfe in possInferiorVal) { if (possInfe.Equals(serverObj.Name)) { isAllowedParent = true; break; } } if (!isAllowedParent) { break; } } if (!isAllowedParent) { break; } } } //MS-ADTS-Schema_R149. DataSchemaSite.CaptureRequirementIfIsTrue( isAllowedParent, 149, "The union of values in possSuperiors and systemPossSuperiors specifies the classes that " + "are allowed to be parents of an object instance of the class in question."); }
public void ShiftColors( int pShifts, float pShiftTime, float pRestTime=1.0f) { Director.Instance.CurrentScene.StopActionByTag(30); var cRot = new Sequence(); // cRot.Add( new CallFunc( () => { // rotatePalette(); // } )); cRot.Add( new CallFunc( () => { for (int i=0; i < registry.Length; i++) { var list = registry[i]; if ( list != null ) { foreach ( Node node in list ) { if ( node is SpriteBase) { (node as SpriteBase).ShiftSpriteColor(QColor.uiPalette[i], pShiftTime); } else { (node as Label).ShiftLabelColor(QColor.uiPalette[i], pShiftTime); } } } } } )); cRot.Add( new DelayTime(pShiftTime + pRestTime) ); if (pShifts > 1) { Director.Instance.CurrentScene.RunAction(new Repeat(cRot, pShifts) {Tag = 30}); } else if (pShifts == 1) { Director.Instance.CurrentScene.RunAction(cRot); } else { Director.Instance.CurrentScene.RunAction(new RepeatForever() {Tag = 30, InnerAction = cRot}); } }
void PlayMidiFromSelection() { try { if (EditorPro.Sequence == null) { return; } if (!CreateMidiPlaybackDeviceIfNull()) { return; } if (midiPlaybackSequencer == null) { midiPlaybackSequencer = new Sequencer(); } if (playbackSequencerAttached == false) { this.midiPlaybackSequencer.PlayingCompleted += new EventHandler(midiPlaybackSequencer_PlayingCompleted); this.midiPlaybackSequencer.ChannelMessagePlayed += new EventHandler <ChannelMessageEventArgs>(midiPlaybackSequencer_ChannelMessagePlayed); this.midiPlaybackSequencer.SysExMessagePlayed += new EventHandler <SysExMessageEventArgs>(midiPlaybackSequencer_SysExMessagePlayed); playbackSequencerAttached = true; } if (MidiPlaybackInProgress == true) { midiPlaybackSequencer.Stop(); MidiPlaybackInProgress = false; } if (midiPlaybackSequence != null) { midiPlaybackSequence.Dispose(); } midiPlaybackSequence = new Sequence(FileType.Pro, EditorPro.Sequence.Division); midiPlaybackSequence.Format = EditorPro.Sequence.Format; midiPlaybackSequencer.Sequence = midiPlaybackSequence; int pos = 0; if (SelectedChord != null) { pos = SelectedChord.DownTick - Utility.ScollToSelectionOffset; } var mainTrack = EditorPro.GuitarTrack.GetTrack(); if (mainTrack != null) { midiPlaybackSequence.AddTempo(EditorPro.GuitarTrack.GetTempoTrack().Clone()); Track t = new Track(FileType.Pro, mainTrack.Name); foreach (var gc in EditorPro.GuitarTrack.Messages.Chords.Where(x => x.IsPureArpeggioHelper == false).ToList()) { foreach (var cn in gc.Notes.Where(x => x.IsArpeggioNote == false && x.TickLength > 0 && x.Data2 >= 100).ToList()) { t.Insert(gc.DownTick - Utility.ScollToSelectionOffset, new ChannelMessage(ChannelCommand.NoteOn, cn.Data1, cn.Data2)); t.Insert(gc.UpTick - 1 - Utility.ScollToSelectionOffset, new ChannelMessage(ChannelCommand.NoteOff, cn.Data1, 0)); } } midiPlaybackSequence.Add(t); } if (SelectedSong != null) { if (SelectedSong.EnableSongMP3Playback && SelectedSong.SongMP3Location.FileExists()) { LoadSongMP3Playback(); } } midiPlaybackSequencer.Start(); MidiPlaybackPosition = pos; midiPlaybackSequencer.Position = pos; MidiPlaybackInProgress = true; timerMidiPlayback.Enabled = true; } catch { MidiPlaybackInProgress = false; timerMidiPlayback.Enabled = false; } }
public ChordBotV1(Sequence seq, int channel = 0, int instrument = (int)GeneralMidiInstrument.ChoirAahs, int minNote = 48, int maxNote = 72, int maxInterval = 7, int numVoices = 2, int minVol = 60, int maxVol = 90, int songLength = 25000, int subDiv = 100, int upDownChance = 50) { var trackLog = new TrackLog(_track); var note = _rnd.RandomInt(minNote, maxNote); var vol = _rnd.RandomInt(minVol, maxVol); trackLog.InsertChannelMessage(0, ChannelCommand.ProgramChange, channel, instrument); for (var i = 0; i <= songLength; i += subDiv) { for (var v = 0; v < numVoices; v++) { trackLog.InsertChannelMessage(i, ChannelCommand.NoteOn, channel, note, vol); trackLog.InsertChannelMessage(i + (subDiv - 1), ChannelCommand.NoteOff, channel, note); vol = _rnd.RandomMidiGeneral(); if (_rnd.Chance(upDownChance)) { note += _rnd.RandomInt(0, maxInterval); if (note > maxNote) { note = maxNote; } } else { note -= _rnd.RandomInt(0, maxInterval); if (note < minNote) { note = minNote; } } } } seq.Add(_track); }
protected override void CreateTrack(int track) { base.CreateTrack(track); tracks[track] = new Track(); Sequence.Add(tracks[track]); }
public void Calculate() { if (SpellPriority.Count == 0) { return; } Stats currentStats; Random rnd = new Random(DateTime.Now.Millisecond); int castCount = 0, critableCount = 0, ssCount = 0; float timer = 0.0f, drumsTimer = 0.0f, drumsUpTimer = 0.0f; while (timer < CalculationOptions.FightDuration) { timer += CalculationOptions.Lag / 1000.0f; timer += CalculationOptions.WaitTime / 1000.0f; if (CalculationOptions.DrumsCount > 0 && drumsTimer < timer) { drumsTimer = timer + 120.0f; drumsUpTimer = timer + CalculationOptions.DrumsCount * 30.0f; if (CalculationOptions.UseYourDrum) { timer += SpellPriority[0].GlobalCooldown; continue; } } UpTrinket(timer); currentStats = PlayerStats.Clone(); if (CalculationOptions.DrumsCount > 0 && drumsUpTimer > timer) { currentStats.SpellHasteRating += 80.0f; } GetTrinketBuff(timer, currentStats); Spell spell = GetCastSpell(timer); if (spell == null) { timer += 0.1f; continue; } Spell seqspell = SpellFactory.CreateSpell(spell.Name, currentStats, PlayerTalentTree); if (spell.CritCoef > 1.0f) { critableCount++; } if (spell.MagicSchool != MagicSchool.Shadow) { ssCount++; } if (spell.DebuffDuration > 0.0f || spell.Cooldown > 0.0f) { spell.SpellStatistics.CooldownReset = timer + (spell.DebuffDuration > spell.Cooldown ? spell.DebuffDuration : spell.Cooldown); } spell.SpellStatistics.HitCount++; Sequence.Add(timer, seqspell); timer += seqspell.CastTime > 0.0f ? seqspell.CastTime : seqspell.GlobalCooldown; castCount++; } int missCount = (int)Math.Round((Sequence.Count - ssCount) * (100.0f - ShadowHitChance) / 100.0f); int mbmissCount = (int)Math.Round((double)missCount / 2.0f); int critCount = (int)Math.Round(critableCount * ShadowCritChance / 100.0f); int mbcritCount = (int)Math.Round((double)critCount / 2.0f); int ssmissCount = (int)Math.Round(ssCount * (100.0f - HitChance) / 100.0f); foreach (Spell spell in SpellPriority) { if (spell.CritCoef > 1.0f) { if (spell.Name == "Mind Blast") { spell.SpellStatistics.HitCount -= mbmissCount; spell.SpellStatistics.MissCount = mbmissCount; spell.SpellStatistics.CritCount = mbcritCount; } else { spell.SpellStatistics.HitCount -= (missCount - mbmissCount); spell.SpellStatistics.MissCount = (missCount - mbmissCount); spell.SpellStatistics.CritCount = (critCount - mbcritCount); } spell.SpellStatistics.DamageDone += spell.SpellStatistics.CritCount * spell.AvgCrit; } if (spell.MagicSchool != MagicSchool.Shadow) { spell.SpellStatistics.HitCount -= ssmissCount; spell.SpellStatistics.MissCount = ssmissCount; } spell.SpellStatistics.DamageDone += (spell.SpellStatistics.HitCount - spell.SpellStatistics.CritCount) * spell.AvgDamage; OverallDamage += spell.SpellStatistics.DamageDone; } OverallDps = OverallDamage / CalculationOptions.FightDuration; }
public async Task Queue_Set_With_Set_Should_Insert_Sync_Job() { //Arrange var set1 = new Set(); var jobId1 = set1.Add <TestJobWithoutInput>(); var jobId2 = set1.Add <TestJobWithoutInput>(); var set2 = new Set(); var jobId3 = set2.Add <TestJobWithoutInput>(); var jobId4 = set2.Add <TestJobWithoutInput>(); var sequence = new Sequence(); sequence.Add(set1); sequence.Add(set2); var batch = new Batch(sequence); IEnumerable <JobDescription> jobs = null; await _store.AddJobsAsync(Arg.Do <IEnumerable <JobDescription> >(x => jobs = x)); //Act await _scheduler.QueueAsync(batch); //Assert await _store.Received(1).AddJobsAsync(jobs); var result1 = jobs.ElementAt(0); var result2 = jobs.ElementAt(1); var sync = jobs.ElementAt(2); var result3 = jobs.ElementAt(3); var result4 = jobs.ElementAt(4); Assert.Equal(batch.Id, result1.BatchId); Assert.Equal(batch.Id, result2.BatchId); Assert.Equal(batch.Id, sync.BatchId); Assert.Equal(batch.Id, result3.BatchId); Assert.Equal(batch.Id, result4.BatchId); Assert.Equal(_now, result1.CreatedTime); Assert.Equal(_now, result2.CreatedTime); Assert.Equal(_now, sync.CreatedTime); Assert.Equal(_now, result3.CreatedTime); Assert.Equal(_now, result4.CreatedTime); Assert.Equal(_now, result1.UpdatedTime); Assert.Equal(_now, result2.UpdatedTime); Assert.Equal(_now, sync.UpdatedTime); Assert.Equal(_now, result3.UpdatedTime); Assert.Equal(_now, result4.UpdatedTime); Assert.Equal(jobId1, result1.Id); Assert.Equal(jobId2, result2.Id); Assert.NotEqual(Guid.Empty, sync.Id); Assert.Equal(jobId3, result3.Id); Assert.Equal(jobId4, result4.Id); Assert.Equal(0, result1.WaitCount); Assert.Equal(0, result2.WaitCount); Assert.Equal(2, sync.WaitCount); Assert.Equal(1, result3.WaitCount); Assert.Equal(1, result4.WaitCount); Assert.Null(result1.PrevId); Assert.Null(result2.PrevId); Assert.Null(sync.PrevId); Assert.Equal(sync.Id, result3.PrevId); Assert.Equal(sync.Id, result4.PrevId); Assert.Equal(sync.Id, result1.NextId); Assert.Equal(sync.Id, result2.NextId); Assert.Null(sync.NextId); Assert.Null(result3.NextId); Assert.Null(result4.NextId); Assert.Equal(typeof(SyncJob).AssemblyQualifiedName, sync.Type); Assert.Null(sync.Input); Assert.Equal(ExecutionState.Waiting, sync.State); }
internal void SaveAsMIDI(string fileName) { if (NumTracks == 0) { throw new InvalidDataException("This song has no tracks."); } if (ROM.Instance.Game.Engine.Type != EngineType.M4A) { throw new PlatformNotSupportedException("Exporting to MIDI from this game engine is not supported at this time."); } CalculateTicks(); var midi = new Sequence(Engine.GetTicksPerBar() / 4) { Format = 2 }; for (int i = 0; i < NumTracks; i++) { var track = new Sanford.Multimedia.Midi.Track(); midi.Add(track); int endOfPattern = 0, startOfPatternTicks = 0, endOfPatternTicks = 0, shift = 0; var playing = new List <M4ANoteCommand>(); for (int j = 0; j < Commands[i].Count; j++) { var e = Commands[i][j]; int ticks = (int)(e.AbsoluteTicks + (endOfPatternTicks - startOfPatternTicks)); if (e.Command is KeyShiftCommand keysh) { shift = keysh.Shift; } else if (e.Command is M4ANoteCommand note) { int n = (note.Note + shift).Clamp(0, 127); track.Insert(ticks, new ChannelMessage(ChannelCommand.NoteOn, i, n, note.Velocity)); if (note.Duration != -1) { track.Insert(ticks + note.Duration, new ChannelMessage(ChannelCommand.NoteOff, i, n)); } else { playing.Add(note); } } else if (e.Command is EndOfTieCommand eot) { M4ANoteCommand nc = null; if (eot.Note == -1) { nc = playing.LastOrDefault(); } else { nc = playing.LastOrDefault(n => n.Note == eot.Note); } if (nc != null) { int no = (nc.Note + shift).Clamp(0, 127); track.Insert(ticks, new ChannelMessage(ChannelCommand.NoteOff, i, no)); playing.Remove(nc); } } else if (e.Command is VoiceCommand voice) { track.Insert(ticks, new ChannelMessage(ChannelCommand.ProgramChange, i, voice.Voice)); } else if (e.Command is VolumeCommand vol) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.Volume, vol.Volume)); } else if (e.Command is PanpotCommand pan) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.Pan, pan.Panpot + 0x40)); } else if (e.Command is BendCommand bend) { track.Insert(ticks, new ChannelMessage(ChannelCommand.PitchWheel, i, 0, bend.Bend + 0x40)); } else if (e.Command is BendRangeCommand bendr) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 20, bendr.Range)); } else if (e.Command is LFOSpeedCommand lfos) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 21, lfos.Speed)); } else if (e.Command is LFODelayCommand lfodl) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 26, lfodl.Delay)); } else if (e.Command is ModDepthCommand mod) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.ModulationWheel, mod.Depth)); } else if (e.Command is ModTypeCommand modt) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 22, modt.Type)); } else if (e.Command is TuneCommand tune) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 24, tune.Tune)); } else if (e.Command is TempoCommand tempo) { var change = new TempoChangeBuilder { Tempo = (60000000 / tempo.Tempo) }; change.Build(); track.Insert(ticks, change.Result); } else if (e.Command is CallCommand patt) { int callCmd = Commands[i].FindIndex(c => c.Offset == patt.Offset); endOfPattern = j; endOfPatternTicks = (int)e.AbsoluteTicks; j = callCmd - 1; // -1 for incoming ++ startOfPatternTicks = (int)Commands[i][j + 1].AbsoluteTicks; } else if (e.Command is ReturnCommand) { if (endOfPattern != 0) { j = endOfPattern; endOfPattern = startOfPatternTicks = endOfPatternTicks = 0; } } else if (i == 0 && e.Command is GoToCommand goTo) { track.Insert(ticks, new MetaMessage(MetaType.Marker, new byte[] { (byte)']' })); int jumpCmd = Commands[i].FindIndex(c => c.Offset == goTo.Offset); track.Insert((int)Commands[i][jumpCmd].AbsoluteTicks, new MetaMessage(MetaType.Marker, new byte[] { (byte)'[' })); } else if (e.Command is FinishCommand fine) { track.Insert(ticks, new MetaMessage(MetaType.EndOfTrack, new byte[0])); break; } } } midi.Save(fileName); }
public mCropCanvas(int ModeX, int ModeY, int CropWidth, int CropHeight, int ImageWidth, int ImageHeight, System.Drawing.Color FillColor) { Sequence.Clear(); BitmapType = mFilter.BitmapTypes.Rgb24bpp; int IW = ImageWidth; int IH = ImageHeight; int CW = CropWidth; int CH = CropHeight; int FX = 0; int FY = 0; int FW = CW; int FH = CH; if (IW > CW) { switch (ModeX) { case 0: Sequence.Add(new Crop(new System.Drawing.Rectangle(0, 0, CW, IH))); break; case 1: Sequence.Add(new Crop(new System.Drawing.Rectangle((IW - CW) / 2, 0, CW, IH))); break; case 2: Sequence.Add(new Crop(new System.Drawing.Rectangle((IW - CW), 0, CW, IH))); break; } } else { switch (ModeX) { case 0: Sequence.Add(new Crop(new System.Drawing.Rectangle(0, 0, CW, IH))); FW = CW - (CW - IW); break; case 1: Sequence.Add(new Crop(new System.Drawing.Rectangle(-(CW - IW) / 2, 0, CW, IH))); FX = (CW - IW) / 2; FW = CW - (CW - IW); break; case 2: Sequence.Add(new Crop(new System.Drawing.Rectangle(-(CW - IW), 0, CW, IH))); FX = (CW - IW); break; } } if (IH > CH) { switch (ModeY) { case 0: Sequence.Add(new Crop(new System.Drawing.Rectangle(0, 0, CW, CH))); break; case 1: Sequence.Add(new Crop(new System.Drawing.Rectangle(0, (IH - CH) / 2, CW, CH))); break; case 2: Sequence.Add(new Crop(new System.Drawing.Rectangle(0, (IH - CH), CW, CH))); break; } } else { switch (ModeY) { case 0: Sequence.Add(new Crop(new System.Drawing.Rectangle(0, 0, CW, CH))); FH = CH - (CH - IH); break; case 1: Sequence.Add(new Crop(new System.Drawing.Rectangle(0, -(CH - IH) / 2, CW, CH))); FY = (CH - IH) / 2; FH = CH - (CH - IH); break; case 2: Sequence.Add(new Crop(new System.Drawing.Rectangle(0, -(CH - IH), CW, CH))); FY = (CH - IH); break; } } Sequence.Add(new CanvasCrop(new System.Drawing.Rectangle(FX, FY, FW, FH), FillColor)); }
public async Task Queue_Set_With_Sequence() { //Arrange var set = new Set(); var jobId1 = set.Add <TestJobWithoutInput>(); var sequence = new Sequence(); var jobId2 = sequence.Add <TestJobWithoutInput>(); var jobId3 = sequence.Add <TestJobWithoutInput>(); set.Add(sequence); var jobId4 = set.Add <TestJobWithoutInput>(); var batch = new Batch(set); IEnumerable <JobDescription> jobs = null; await _store.AddJobsAsync(Arg.Do <IEnumerable <JobDescription> >(x => jobs = x)); //Act await _scheduler.QueueAsync(batch); //Assert await _store.Received(1).AddJobsAsync(jobs); var result1 = jobs.ElementAt(0); var result2 = jobs.ElementAt(1); var result3 = jobs.ElementAt(2); var result4 = jobs.ElementAt(3); Assert.Equal(batch.Id, result1.BatchId); Assert.Equal(batch.Id, result2.BatchId); Assert.Equal(batch.Id, result3.BatchId); Assert.Equal(batch.Id, result4.BatchId); Assert.Equal(_now, result1.CreatedTime); Assert.Equal(_now, result2.CreatedTime); Assert.Equal(_now, result3.CreatedTime); Assert.Equal(_now, result4.CreatedTime); Assert.Equal(_now, result1.UpdatedTime); Assert.Equal(_now, result2.UpdatedTime); Assert.Equal(_now, result3.UpdatedTime); Assert.Equal(_now, result4.UpdatedTime); Assert.Equal(jobId1, result1.Id); Assert.Equal(jobId2, result2.Id); Assert.Equal(jobId3, result3.Id); Assert.Equal(jobId4, result4.Id); Assert.Equal(0, result1.WaitCount); Assert.Equal(0, result2.WaitCount); Assert.Equal(1, result3.WaitCount); Assert.Equal(0, result4.WaitCount); Assert.Null(result1.PrevId); Assert.Null(result2.PrevId); Assert.Equal(result2.Id, result3.PrevId); Assert.Null(result4.PrevId); Assert.Null(result1.NextId); Assert.Null(result2.NextId); Assert.Null(result3.NextId); Assert.Null(result4.NextId); }
private IEnumerator ShotThree_Enter() { if (_player == null || _falcon == null) { yield break; } if (_shotThreeBullet == null) { yield break; } if (_shotThreeNumberPerCircle <= 0) { yield break; } if (_shotThreeShotTimes <= 0) { yield break; } if (_shotThreeInitVec < 0 || _shotThreeAccel > 0) { yield break; } if (_shotThreeMinShotInteral < 0f || _shotThreeMinShotInteral > _shotThreeMaxShotInterval) { yield break; } if (_shotThreeMinMoveDis < 0f || _shotThreeMinMoveDis > _shotThreeMaxMoveDis) { yield break; } for (int i = 0; i < _shotThreeShotTimes; i++) { float moveTime = Random.Range(_shotThreeMinShotInteral, _shotThreeMaxShotInterval); Vector3 dest = ShotThree_FindPropPos(); var moveEffect = new Effect <Transform, Vector3> (); moveEffect.Duration = moveTime; moveEffect.RetrieveStart = (falcon, lastValue) => falcon.position; moveEffect.RetrieveEnd = (falcon) => dest; moveEffect.OnUpdate = (falcon, pos) => falcon.position = pos; moveEffect.CalculatePercentDone = Easing.GetEase(Easing.EaseType.Pow2InOut); var moveSeq = new Sequence <Transform, Vector3> (); moveSeq.Reference = _falcon; moveSeq.Add(moveEffect); moveSeq.OnComplete = (falcon) => ShotThree_Shot(); var moveInstance = Movement.Run(moveSeq); while (moveTime > 0) { moveInstance.Timescale = JITimer.Instance.TimeScale; moveTime -= JITimer.Instance.DeltTime; yield return(null); } } if (_fsm.LastState == States.FullScreenWind || _fsm.LastState == States.SideWind) { yield return(new WaitForSeconds(2f)); } ShotThree_Transition(); }
public override void Create() { double[] currentDurationPhrase = MusicLibrary.CurrentSongDuration(); int[] currentPitchPhrase = MusicLibrary.CurrentSongPitch(); double[] rhythmInputs = MusicEnvironment.createDurationInputs(currentDurationPhrase); int[] pitchInputs = MusicEnvironment.createPitchInputs(currentPitchPhrase, currentDurationPhrase); string CHAMPION_FILE = @"..\..\..\NeatMusic\bin\Debug\host_parasite_champion.xml"; List <NeatGenome> anns; XmlConfigurator.Configure(new System.IO.FileInfo("log4net.properties")); // Load config XML. XmlDocument xmlConfig = new XmlDocument(); //load genomes // Save the best genome to file XmlReaderSettings xwSettings = new XmlReaderSettings(); using (XmlReader xw = XmlReader.Create(CHAMPION_FILE, xwSettings)) { anns = NeatGenomeXmlIO.ReadCompleteGenomeList(xw, false); } foreach (var neatGenome in anns) { Console.WriteLine("id_" + neatGenome.Id); } // Load config XML. XmlDocument xmlConfig1 = new XmlDocument(); xmlConfig1.Load(@"..\..\..\NeatMusic\bin\Debug\config.xml"); XmlElement xmlElement = xmlConfig1.DocumentElement; var activation = ExperimentUtils.CreateActivationScheme(xmlElement, "Activation"); IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = new NeatGenomeDecoder(activation); int MODULE_COUNT = anns.Count / 2; int LENGHT = rhythmInputs.Length; int LENGTHPITCH = currentPitchPhrase.Length; //int LENGTHPITCH = LENGHT; int SEED_PITCH = 0; var rhythmPlayers = new List <NeatPlayer>(); var pitchPlayers = new List <NeatPlayer>(); for (int i = 0; i < MODULE_COUNT; i++) { rhythmPlayers.Add(new NeatPlayer(genomeDecoder.Decode(anns[i]))); } for (int i = MODULE_COUNT; i < MODULE_COUNT * 2; i++) { pitchPlayers.Add(new NeatPlayer(genomeDecoder.Decode(anns[i]))); } double[][] rhythmOutput = new double[MODULE_COUNT][]; int[][] pitchOutput = new int[MODULE_COUNT][]; for (int i = 0; i < MODULE_COUNT; i++) { rhythmOutput[i] = new double[LENGHT]; pitchOutput[i] = new int[LENGTHPITCH]; } for (int i = 0; i < MODULE_COUNT; i++) { rhythmOutput[i] = new double[LENGHT]; pitchOutput[i] = new int[LENGHT]; } for (int i = 0; i < LENGHT; i++) { for (int p = 0; p < MODULE_COUNT; p++) { var brainInput = MusicEnvironment.getBrainInputDelayed(pitchOutput, pitchInputs, p, MODULE_COUNT, i); pitchOutput[p][i] = MusicEnvironment.convertToMidiClass(pitchPlayers[p].calculateOutput(brainInput)); } } for (int i = 0; i < LENGHT; i++) { for (int p = 0; p < MODULE_COUNT; p++) { var brainInput = MusicEnvironment.getBrainInputDelayed(rhythmOutput, rhythmInputs, p, MODULE_COUNT, i); rhythmOutput[p][i] = rhythmPlayers[p].calculateOutput(brainInput); } } printFitness(MODULE_COUNT, pitchPlayers, rhythmPlayers); //get standard deviation Console.WriteLine(@"Input deviation: {0}", SmoothedZSmoothening.StandardDeviation(rhythmInputs)); for (int i = 0; i < rhythmOutput.Length; i++) { double standardDev = SmoothedZSmoothening.StandardDeviation(rhythmOutput[i]); Console.WriteLine(@"Module {0} deviation: {1}", i, standardDev); } //look at outputs and find out when there are new notes and what they are //new note when current value is higher than previous one List <double>[] durationsLists = new List <double> [MODULE_COUNT]; List <int>[] pitchLists = new List <int> [MODULE_COUNT]; for (int i = 0; i < MODULE_COUNT; i++) { durationsLists[i] = new List <double>(); pitchLists[i] = new List <int>(); findNewNotesFromOutput(rhythmOutput[i], pitchOutput[i], LENGHT, out durationsLists[i], out pitchLists[i]); mergeRests(durationsLists[i], pitchLists[i]); printResults(durationsLists[i], pitchLists[i], i + 1); } Sequence seq = new Sequence(); seq.Add(getTrack(currentPitchPhrase, currentDurationPhrase, 60)); //save input phrase in separate file seq.Save("base.mid"); for (int i = 0; i < MODULE_COUNT; i++) { //int offset = i%2 == 0 ? 60 + 12 * (i/2 + 1) : 48 - 12 * (i/2 + 1); //how should this be done? int offset = 48; Track t = getTrack(pitchLists[i].ToArray(), durationsLists[i].ToArray(), offset); Sequence singleTrack = new Sequence(); singleTrack.Add(t); singleTrack.Save("track" + (i + 1) + ".mid"); seq.Add(t); } seq.Save("test.mid"); // Hit return to quit. Console.ReadLine(); }
public Sequence GetSequenceFromStaff(Staff staff) { List <string> notesOrderWithCrosses = new List <string>() { "c", "cis", "d", "dis", "e", "f", "fis", "g", "gis", "a", "ais", "b" }; int absoluteTicks = 0; Sequence sequence = new Sequence(); Track metaTrack = new Track(); sequence.Add(metaTrack); Track notesTrack = new Track(); sequence.Add(notesTrack); int speed = 60000000 / staff.GetTempo(); byte[] tempo = new byte[3]; tempo[0] = (byte)((speed >> 16) & 0xff); tempo[1] = (byte)((speed >> 8) & 0xff); tempo[2] = (byte)(speed & 0xff); metaTrack.Insert(0 /* Insert at 0 ticks*/, new MetaMessage(MetaType.Tempo, tempo)); List <MusicalSymbol> WPFStaffs = new List <MusicalSymbol>(); WPFManager.getMusicSymbols(staff, WPFStaffs); foreach (MusicalSymbol musicalSymbol in WPFStaffs) { int[] time; double absoluteLength; double relationToQuartNote; double percentageOfBeatNote; double deltaTicks; switch (musicalSymbol.Type) { case MusicalSymbolType.Note: Note note = musicalSymbol as Note; absoluteLength = 1.0 / (double)note.Duration; absoluteLength += (absoluteLength / 2.0) * note.NumberOfDots; time = staff.GetTime(); relationToQuartNote = time[1] / 4.0; percentageOfBeatNote = (1.0 / time[1]) / absoluteLength; deltaTicks = (sequence.Division / relationToQuartNote) / percentageOfBeatNote; // Calculate height int noteHeight = notesOrderWithCrosses.IndexOf(note.Step.ToLower()) + ((note.Octave + 1) * 12); noteHeight += note.Alter; notesTrack.Insert(absoluteTicks, new ChannelMessage(ChannelCommand.NoteOn, 1, noteHeight, 90)); // Data2 = volume absoluteTicks += (int)deltaTicks; notesTrack.Insert(absoluteTicks, new ChannelMessage(ChannelCommand.NoteOn, 1, noteHeight, 0)); // Data2 = volume break; case MusicalSymbolType.Rest: Rest rest = musicalSymbol as Rest; absoluteLength = 1.0 / (double)rest.Duration; absoluteLength += (absoluteLength / 2.0) * rest.NumberOfDots; time = staff.GetTime(); relationToQuartNote = time[1] / 4.0; percentageOfBeatNote = (1.0 / time[1]) / absoluteLength; deltaTicks = (sequence.Division / relationToQuartNote) / percentageOfBeatNote; absoluteTicks += (int)deltaTicks; break; case MusicalSymbolType.TimeSignature: time = staff.GetTime(); byte[] timeSignature = new byte[4]; timeSignature[0] = (byte)time[0]; timeSignature[1] = (byte)(Math.Log(time[1]) / Math.Log(2)); metaTrack.Insert(absoluteTicks, new MetaMessage(MetaType.TimeSignature, timeSignature)); break; default: break; } } notesTrack.Insert(absoluteTicks, MetaMessage.EndOfTrackMessage); metaTrack.Insert(absoluteTicks, MetaMessage.EndOfTrackMessage); return(sequence); }
// EVENT HANDLERS ---------------------------------------------------------------------------------------------------------------- void HandleInputManagerInstanceTouchJustUpDetected(object sender, BaseTouchEventArgs e) { var LastTouchPosition = TouchPosition.Xy; bool AdvancePanel = false; TouchPosition = e.touchPosition; // SWITCH ACTIVE PANELS IF PANEL MIDPOINT IS OFF THE SCREEN if (FMath.Abs(AnchorPoints[1].Node.Position.X - AnchorPoints[1].Position.X) > 0.5f*Width || FMath.Abs (TouchVelocity * (TouchPosition.X - TouchStartPosition.X)) > 4000.0f) { // SWIPE TO RIGHT? AdvancePanel = (TouchPosition.X - TouchStartPosition.X) > 0; // CHECK IF RIGHTWARD MOVEMENT IS POSSIBLE if (AnchorPoints[0].Node != null && AdvancePanel) { foreach (AnchorPoint point in AnchorPoints) { point.Index--; if (point.Index < 0){ point.Node = null; } else { point.Node = Panels[point.Index]; } } // CHECK IF LEFTWARD MOVEMENT IS POSSIBLE } else if (AnchorPoints[2].Node != null && !AdvancePanel) { foreach (AnchorPoint point in AnchorPoints) { point.Index++; if (point.Index == Panels.Count) { point.Node = null; } else { point.Node = Panels[point.Index]; } } } } // MOVE PANELS TO NEW RESTING PLACES foreach (AnchorPoint point in AnchorPoints) { if (point.Node == null) { continue; } point.Node.RunAction( new MoveTo(point.Position, 0.3f) { Tween = (t) => Sce.PlayStation.HighLevel.GameEngine2D.Base.Math.ExpEaseOut(t,4.0f) } ); point.Node.ScheduleUpdate(0); } Sequence sequence = new Sequence(); sequence.Add( new DelayTime(0.35f) ); sequence.Add ( new CallFunc( () => { EventHandler handler = OnSwipeComplete; if ( handler != null ) { handler( this, null ); } } ) ); this.RunAction(sequence); }
public void TestByteArray() { Sequence seq = new Sequence(Alphabets.DNA, Encodings.Ncbi2NA, "ACGTA"); Assert.AreEqual(seq.ToString(), "ACGTA"); seq = new Sequence(Alphabets.DNA); seq.Add(Alphabets.DNA.C); seq.Add(Alphabets.DNA.T); seq.Add(Alphabets.DNA.C); seq.IsReadOnly = true; Assert.AreEqual(seq.ToString(), "CTC"); foreach (IEncoding encoding in Encodings.All) { StringBuilder str = new StringBuilder(); foreach (ISequenceItem seqItem in encoding) { str.Append(seqItem.Symbol); } string seqString = str.ToString(); switch (encoding.Name) { case "IUPACna": case "NCBI2na": case "NCBI4na": Sequence dnaseq = new Sequence(Alphabets.DNA, encoding, seqString); Assert.AreEqual(dnaseq.ToString(), seqString); Sequence rnaseq = new Sequence(Alphabets.RNA, encoding, seqString.Replace('T', 'U')); Assert.AreEqual(rnaseq.ToString(), seqString.Replace('T', 'U')); break; case "NcbiEAAEncoding": case "NcbiStdAAEncoding": Sequence proSeq = new Sequence(Alphabets.Protein, encoding, seqString); Assert.AreEqual(proSeq.ToString(), seqString); break; } } seq = new Sequence(Alphabets.DNA); seq.IsReadOnly = true; seq.IsReadOnly = false; seq.Add(Alphabets.DNA.C); seq.Add(Alphabets.DNA.C); seq.Add(Alphabets.DNA.G); seq.Add(Alphabets.DNA.C); seq.Add(Alphabets.DNA.G); seq.Add(Alphabets.DNA.A); seq.IsReadOnly = true; Assert.AreEqual(seq.ToString(), "CCGCGA"); seq = new Sequence(Alphabets.DNA, Encodings.Ncbi2NA, "CCGCGA"); seq.IsReadOnly = true; seq.IsReadOnly = false; seq.Add(Alphabets.DNA.C); seq.Add(Alphabets.DNA.C); seq.Add(Alphabets.DNA.G); seq.Add(Alphabets.DNA.C); seq.Add(Alphabets.DNA.G); seq.Add(Alphabets.DNA.A); seq.Add(Alphabets.DNA.T); seq.IsReadOnly = true; Assert.AreEqual(seq.ToString(), "CCGCGACCGCGAT"); byte[] encodingValues = seq.EncodedValues; Assert.AreEqual(encodingValues[0], 1); Assert.AreEqual(encodingValues[1], 1); Assert.AreEqual(encodingValues[2], 2); Assert.AreEqual(encodingValues[3], 1); Assert.AreEqual(encodingValues[4], 2); Assert.AreEqual(encodingValues[5], 0); Assert.AreEqual(encodingValues[6], 1); Assert.AreEqual(encodingValues[7], 1); Assert.AreEqual(encodingValues[8], 2); Assert.AreEqual(encodingValues[9], 1); Assert.AreEqual(encodingValues[10], 2); Assert.AreEqual(encodingValues[11], 0); Assert.AreEqual(encodingValues[12], 3); seq = new Sequence(Alphabets.DNA, Encodings.IupacNA, "AAAAAAADGY"); encodingValues = seq.EncodedValues; Assert.AreEqual(encodingValues.Length, 10); Assert.AreEqual(encodingValues[0], 65); Assert.AreEqual(encodingValues[1], 65); Assert.AreEqual(encodingValues[2], 65); Assert.AreEqual(encodingValues[3], 65); Assert.AreEqual(encodingValues[4], 65); Assert.AreEqual(encodingValues[5], 65); Assert.AreEqual(encodingValues[6], 65); Assert.AreEqual(encodingValues[7], 68); Assert.AreEqual(encodingValues[8], 71); Assert.AreEqual(encodingValues[9], 89); seq = new Sequence(Alphabets.DNA); seq.IsReadOnly = true; encodingValues = seq.EncodedValues; Assert.AreEqual(encodingValues.Length, 0); }
/// <summary> /// This method validates the requirements under /// LDSConsistencyRules Scenario. /// </summary> public void ValidateLDSConsistencyRules() { #region MS-ADTS-Schema_R73 //The objectClass attribute of the attributeSchema equals the sequence [top, attributeSchema ] //Expected Sequence setting... Sequence <object> actualSeq = new Sequence <object>(); Sequence <object> expectedSeq = new Sequence <object>(); ModelObject objectFromModel = null; string requiredObjectDN = String.Empty; DirectoryEntry serverObject; expectedSeq = expectedSeq.Add("top".ToLower()).Add("classSchema".ToLower()); //Get attributeSchema from Server. requiredObjectDN = "CN=Attribute-Schema,CN=Schema,CN=Configuration," + adAdapter.LDSRootObjectName; if (!adAdapter.GetLdsObjectByDN(requiredObjectDN, out serverObject)) { DataSchemaSite.Assume.IsTrue(false, requiredObjectDN + " Object is not found in server"); } actualSeq = new Sequence <object>(); foreach (string valueString in serverObject.Properties[StandardNames.objectClass.ToLower()]) { actualSeq = actualSeq.Add(valueString.ToLower()); } //MS-ADTS-Schema_R73. DataSchemaSite.CaptureRequirementIfAreEqual <Sequence <object> >( expectedSeq, actualSeq, 73, "The objectClass attribute of the attributeSchema equals the sequence [top, classSchema ]."); #endregion #region MS-ADTS-Schema_R157 //The objectClass attribute of the classSchema equals the sequence [top, classSchema ]. //Expected Sequence setting... expectedSeq = new Sequence <object>(); expectedSeq = expectedSeq.Add("top".ToLower()).Add("classSchema".ToLower()); //Get classSchema from Server. requiredObjectDN = "CN=Class-Schema,CN=Schema,CN=Configuration," + adAdapter.LDSRootObjectName; if (!adAdapter.GetLdsObjectByDN(requiredObjectDN, out serverObject)) { DataSchemaSite.Assume.IsTrue(false, requiredObjectDN + " Object is not found in server"); } actualSeq = new Sequence <object>(); foreach (string valueString in serverObject.Properties[StandardNames.objectClass.ToLower()]) { actualSeq = actualSeq.Add(valueString.ToLower()); } //MS-ADTS-Schema_R157. DataSchemaSite.CaptureRequirementIfAreEqual <Sequence <object> >( expectedSeq, actualSeq, 157, "The objectClass attribute of the classSchema equals the sequence [top, classSchema ]."); #endregion #region MS-ADTS-Schema_R169 //The subClassOf attribute of the classSchema Specifies governsID of the superclass of the class. //Get classSchema from Model. objectFromModel = adamModel.GetClass("classSchema"); if (objectFromModel == null) { DataSchemaSite.Assume.IsNotNull(objectFromModel, "Class classSchema is not existing in Model"); } string expectedValue = (string)objectFromModel[StandardNames.subClassOf].UnderlyingValues.ToArray()[0]; #endregion #region MS-ADTS-Schema_R129-142,179 //Inheritance requirements IEnumerable <IObjectOnServer> serverObjects = (IEnumerable <IObjectOnServer>)adAdapter.GetAllLdsSchemaClasses(); if (serverObjects == null) { DataSchemaSite.Assume.IsNotNull(serverObjects, "Class objects are not existing in Model"); } //This method will validate the requirements MS-ADTS-Schema_R129-142,179 ValidateInheritanceRequirements(serverObjects, false); serverObjects = null; #endregion #region MS-ADTS-Schema_R143-146 //Covering ObjectClass requirements //Get domain NC for validation. DirectoryEntry domainEntry; if (!adAdapter.GetLdsObjectByDN("CN=Configuration," + adAdapter.LDSRootObjectName, out domainEntry)) { DataSchemaSite.Assume.IsTrue( false, "CN=Configuration," + adAdapter.LDSRootObjectName + " Object is not found in server"); } //This method validates teh requirements MS-ADTS-Schema_R143-146 ValidateObjectClassRequirements(domainEntry.Children, false); domainEntry = null; #endregion #region MS-ADTS-Schema_R149,175 //Coverring StructureRule requirements serverObjects = adAdapter.GetAllLdsSchemaClasses(); if (serverObjects == null) { DataSchemaSite.Assume.IsNotNull(serverObjects, "Class objects are not existing in Model"); } //This method validates the requirements MS-ADTS-Schema_R149,175 ValidateStructureRulesRequirements(serverObjects, false); #endregion #region MS-ADTS-Schema_R152,153 //Covering ContentRule requirements //Get the domain NC objects. if (!adAdapter.GetLdsObjectByDN("CN=Configuration," + adAdapter.LDSRootObjectName, out domainEntry)) { DataSchemaSite.Assert.IsTrue(false, "Configuration Object is not found in server"); } //This method validates the requirements MS-ADTS-Schema_R152,153. ValidateContentRulesRequirements(domainEntry.Children, serverObjects); #endregion #region MS-ADTS-Schema_R177 //The systemAuxiliaryClass attribute of the classSchema Specifies governsIDs of the classes that can //be parents of the class within an NC tree, where the parent-child relationships are required for //system operation. DirectoryEntry classSchemaObj; bool isAuxiliary = false; SetContainer <string> auxiliaryClassValue = new SetContainer <string>(); //Get class-schema class from server. if (!adAdapter.GetLdsObjectByDN( "CN=Class-Schema,CN=Schema,CN=Configuration," + adAdapter.LDSRootObjectName, out classSchemaObj)) { DataSchemaSite.Assume.IsTrue( false, "CN=Class-Schema,CN=Schema,CN=Configuration," + adAdapter.rootDomainDN + " Object is not found in server"); } //Collect its auxiliary class value. if (classSchemaObj.Properties.Contains("auxiliaryclass")) { //auxiliaryClassValue.Add foreach (string value in classSchemaObj.Properties["auxiliaryclass"]) { auxiliaryClassValue.Add(value); } } //Collect its system auxiliary class value. if (classSchemaObj.Properties.Contains("systemauxiliaryclass")) { //AuxiliaryClassValue.Add foreach (string value in classSchemaObj.Properties["systemauxiliaryclass"]) { auxiliaryClassValue.Add(value); } } if (auxiliaryClassValue.Count != 0) { //For each auxiliary class... foreach (string auxClass in auxiliaryClassValue) { isAuxiliary = false; foreach (IObjectOnServer serverObj in serverObjects) { //Get it from server. if (serverObj.Name.Equals(auxClass)) { //Get server object governsID. string governsID = (string)serverObj.Properties[StandardNames.governsId.ToLower()][0]; //It should be eqal to the auxiliary class name of the class. if (governsID.Equals(auxClass)) { isAuxiliary = true; continue; } } } if (isAuxiliary) { continue; } else { break; } } } #endregion }
public static Scene MakeTestActionsScene() { TextureInfo Characters = new TextureInfo(new Texture2D("/Application/Sample/GameEngine2D/FeatureCatalog/data/PlanetCute/Objects.png", false), new Vector2i(7, 3)); float world_scale = 0.036f; var sprite = new SpriteTile(); sprite.TextureInfo = Characters; sprite.TileIndex1D = 2; sprite.Quad.S = sprite.CalcSizeInPixels() * world_scale; sprite.CenterSprite(); sprite.Color = new Vector4(1.0f, 1.0f, 1.0f, 0.75f); sprite.BlendMode = BlendMode.Normal; var scene = new Scene() { Name = "Action tests" }; scene.AddChild(sprite); var pos = new Vector2(0.0f, 0.0f); int writing_color_tag = 333; int writing_position_tag = 65406; AddButton(scene, "MoveTo (0,0)", ref pos, () => { sprite.RunAction(new MoveTo(new Vector2(0.0f, 0.0f), 0.1f)); }); AddButton(scene, "MoveBy (3,0)", ref pos, () => { sprite.RunAction(new MoveBy(new Vector2(3.0f, 0.0f), 0.1f)); }); AddButton(scene, "ScaleBy (2,2)", ref pos, () => { sprite.RunAction(new ScaleBy(new Vector2(2.0f, 2.0f), 0.1f)); }); AddButton(scene, "ScaleBy (0.5,0.5)", ref pos, () => { sprite.RunAction(new ScaleBy(new Vector2(0.5f, 0.5f), 0.1f)); }); AddButton(scene, "TintTo White", ref pos, () => { // prevent from running an other action that writes the color if (sprite.GetActionByTag(writing_color_tag) != null) { sprite.StopActionByTag(writing_color_tag); } sprite.RunAction(new TintTo(Math.SetAlpha(Colors.White, 0.75f), 2.0f) { Tag = writing_color_tag }); } ); AddButton(scene, "TintTo Blue", ref pos, () => { // prevent from running an other action that writes the color if (sprite.GetActionByTag(writing_color_tag) != null) { sprite.StopActionByTag(writing_color_tag); } sprite.RunAction(new TintTo(Math.SetAlpha(Colors.Blue, 0.75f), 2.0f) { Tag = writing_color_tag }); } ); AddButton(scene, "Pingpong colors", ref pos, () => { // prevent from running an other action that writes the color if (sprite.GetActionByTag(writing_color_tag) != null) { sprite.StopActionByTag(writing_color_tag); } var action12 = new TintTo(Colors.Green, 0.5f) { Tween = (t) => FMath.Sin(t * Math.Pi * 0.5f), }; var action13 = new TintTo(Colors.Magenta, 0.5f) { Tween = (t) => FMath.Sin(t * Math.Pi * 0.5f), }; var seq = new Sequence(); seq.Add(action12); seq.Add(action13); var repeat0 = new RepeatForever() { InnerAction = seq, Tag = writing_color_tag }; sprite.RunAction(repeat0); } ); AddButton(scene, "Pingpong position", ref pos, () => { // prevent from running the same action twice // (we could also just hold an Action object somewhere and re-run, so that this check wouldn't be needed) if (sprite.GetActionByTag(writing_position_tag) != null) { sprite.StopActionByTag(writing_position_tag); } var action12 = new MoveTo(new Vector2(-5, 0), 0.5f) { Tween = (t) => FMath.Sin(t * Math.Pi * 0.5f), }; var action13 = new MoveTo(new Vector2(5, 0), 0.5f) { Tween = (t) => FMath.Sin(t * Math.Pi * 0.5f), }; var seq = new Sequence(); seq.Add(action12); seq.Add(action13); var repeat0 = new RepeatForever() { InnerAction = seq, Tag = writing_position_tag }; sprite.RunAction(repeat0); } ); AddButton(scene, "StopAllActions", ref pos, () => sprite.StopAllActions()); scene.RegisterDisposeOnExit((System.IDisposable)Characters); return(scene); }
private static void BuildRandomMidiFile() { Random rand = new Random(); Sequence seq = new Sequence(); Track track0 = new Track(); Track fifthTrack = new Track(); seq.Add(track0); seq.Add(fifthTrack); ChannelMessageBuilder channelBuilder = new ChannelMessageBuilder(); channelBuilder.MidiChannel = 0; int numNotes = 100; //length in ticks int minLength = 10; int maxLength = 50; int minNote = 24; //c2 int maxNote = 72; //c6 //percent chance int fifthChance = 25; int curTick = 0; for (int a = 0; a < numNotes; a++) { int note = rand.Next(minNote, maxNote); int noteLength = rand.Next(minLength, maxLength); int endTick = curTick + noteLength; //note channelBuilder.Command = ChannelCommand.NoteOn; channelBuilder.Data1 = note; channelBuilder.Data2 = 127; channelBuilder.Build(); track0.Insert(curTick, channelBuilder.Result); //note off channelBuilder.Command = ChannelCommand.NoteOff; channelBuilder.Data2 = 0; channelBuilder.Build(); track0.Insert(endTick, channelBuilder.Result); //add 5th note if (rand.Next(100) <= fifthChance) { //TODO: make sure fifth isn't too high or low int fifth = rand.Next(1) == 1 ? note + 7 : note - 7; //fifth is 7 intervals channelBuilder.Command = ChannelCommand.NoteOn; channelBuilder.Data1 = fifth; channelBuilder.Data2 = 127; channelBuilder.Build(); fifthTrack.Insert(curTick, channelBuilder.Result); channelBuilder.Command = ChannelCommand.NoteOff; channelBuilder.Data1 = fifth; channelBuilder.Data2 = 0; channelBuilder.Build(); fifthTrack.Insert(endTick, channelBuilder.Result); } //update curTick curTick = endTick; } seq.Save("random.mid"); }
/// <summary> /// Export the score to a MIDI file. /// </summary> /// <param name="filename">The .mid file to output data to.</param> public void ExportMidi(string filename) { // Info about MIDI specifications can be found here: // http://www.fileformat.info/format/midi/corion.htm var s = new Sequence(); var t = new Track(); var tickAtStartOfMeasure = TickBuffer; // Set up instruments and panning; unroll instrument tracks // (we don't need to unroll percussion because it // doesn't have any issue with overlapping notes) var channel = Channel.Channel1; var renderedInstruments = new List <RenderedInstrument>(); foreach (var instrumentTrack in _instrumentTracks) { renderedInstruments.Add(new RenderedInstrument { Channel = channel, Notes = Unroll(instrumentTrack.Notes).Select(n => new MidiNote(TickBuffer + n.StartInTicks(StandardMidiTicksPerBeat), n.LengthInTicks(StandardMidiTicksPerBeat), n.Pitch, n.Velocity)).ToList() }); t.Insert(0, new ChannelMessage(ChannelCommand.ProgramChange, (int)channel, (int)instrumentTrack.Instrument)); t.Insert(0, new ChannelMessage(ChannelCommand.Controller, (int)channel, (int)Control.Pan, (int)instrumentTrack.Pan)); channel++; if (channel == Channel.Channel10) { channel++; // skip over percussion } } for (var measure = 0; measure < _measureCount; measure++) { // Create tempo change (if one exists) if (_tempoChanges.ContainsKey(measure)) { t.Insert(tickAtStartOfMeasure, new MetaMessage(MetaType.Tempo, GetTempoBytes(_tempoChanges[measure]))); } // Create events for percussion foreach (var note in _percussionTrack.Notes[measure]) { t.Insert(tickAtStartOfMeasure + note.StartInTicks(StandardMidiTicksPerBeat), new ChannelMessage(ChannelCommand.NoteOn, (int)Channel.Channel10, (int)note.Percussion, (int)note.Velocity)); } tickAtStartOfMeasure += MeasureLengthInTicks(measure); } // Create events for unrolled instrument tracks foreach (var renderedInstrument in renderedInstruments) { foreach (var note in renderedInstrument.Notes) { t.Insert(note.Start, new ChannelMessage(ChannelCommand.NoteOn, (int)renderedInstrument.Channel, (int)note.Pitch, (int)note.Velocity)); if (!renderedInstrument.Notes.Any(e => e.Pitch == note.Pitch && e.Start == note.End)) { // NOTE: You cannot have NoteOff and NoteOn events for the same pitch // on the same tick. NoteOff gets priority and the second note will not // be played. So if two notes collide, don't write the NoteOff command // for the first one. t.Insert(note.End, new ChannelMessage(ChannelCommand.NoteOff, (int)renderedInstrument.Channel, (int)note.Pitch, (int)note.Velocity)); } } } // Add an empty note one measure after the actual end of the song, just for some extra buffer var endingBuffer = TimeSignatureAtMeasure(_measureCount - 1).BeatCount *StandardMidiTicksPerBeat; t.Insert(tickAtStartOfMeasure + endingBuffer, new ChannelMessage(ChannelCommand.NoteOff, (int)Channel.Channel10, 0)); // End meta message t.Insert(tickAtStartOfMeasure + endingBuffer, new MetaMessage(MetaType.EndOfTrack, new byte[0])); s.Add(t); s.Save(filename); }
// NOTE: no delta time, frame specific public void FrameUpdate() { Collider.Collide(); foreach (GameEntity e in RemoveQueue) World.RemoveChild(e,true); foreach (GameEntity e in AddQueue) World.AddChild(e); RemoveQueue.Clear(); AddQueue.Clear(); #if false // is player dead? if (PlayerDead) { if (PlayerInput.AnyButton()) { // ui will transition to title mode World.RemoveAllChildren(true); Collider.Clear(); PlayerDead = false; // hide UI and then null player to swap back to title UI.HangDownTarget = -1.0f; UI.HangDownSpeed = 0.175f; var sequence = new Sequence(); sequence.Add(new DelayTime() { Duration = 0.4f }); sequence.Add(new CallFunc(() => this.Player = null)); World.RunAction(sequence); } } #endif }
//------------------------------------------------------------------ public void AddInSequnce(Action action) { Sequence.Add(action); }
public DrumBotV1(Sequence seq, int songLength = 25000, int subDiv = 5, int sectionDiv = 1000, int restChance = 50, int drumChangeChance = 5, int pitchChangeChance = 10, int volChangeChance = 75) { var trackLog = new TrackLog(_track); var drum = _rnd.RandomDrum(); var pitch = _rnd.RandomMidiGeneral(); var vol = _rnd.RandomMidiGeneral(); for (var i = 0; i <= songLength; i += subDiv) { if (i >= sectionDiv && (i % sectionDiv) == 0) { restChance = _rnd.RandomPercent(); drumChangeChance = _rnd.RandomPercent(); pitchChangeChance = _rnd.RandomPercent(); volChangeChance = _rnd.RandomPercent(); } if (_rnd.Chance(restChance)) { continue; } if (_rnd.Chance(drumChangeChance)) { drum = _rnd.RandomDrum(); } if (_rnd.Chance(pitchChangeChance)) { pitch = _rnd.RandomMidiGeneral(); } if (_rnd.Chance(volChangeChance)) { vol = _rnd.RandomMidiGeneral(); } trackLog.InsertChannelMessage(i, ChannelCommand.PitchWheel, Channel, pitch, pitch); trackLog.InsertChannelMessage(i, ChannelCommand.NoteOn, Channel, drum, vol); trackLog.InsertChannelMessage(i + (subDiv - 1), ChannelCommand.NoteOff, Channel, drum); } seq.Add(_track); }
public override void SaveAsMIDI(string fileName) { if (NumTracks == 0) { throw new InvalidDataException("Questa canzone non ha tracce."); } CalculateTicks(); var midi = new Sequence(24) { Format = 1 }; var metaTrack = new Sanford.Multimedia.Midi.Track(); midi.Add(metaTrack); for (int i = 0; i < NumTracks; i++) { var track = new Sanford.Multimedia.Midi.Track(); midi.Add(track); int endOfPattern = 0, startOfPatternTicks = 0, endOfPatternTicks = 0, shift = 0; var playing = new List <M4ANoteCommand>(); for (int j = 0; j < Commands[i].Count; j++) { var e = Commands[i][j]; int ticks = e.AbsoluteTicks + (endOfPatternTicks - startOfPatternTicks); if (e.Command is KeyShiftCommand keysh) { shift = keysh.Shift; } else if (e.Command is M4ANoteCommand note) { int n = (note.Note + shift).Clamp(0, 0x7F); track.Insert(ticks, new ChannelMessage(ChannelCommand.NoteOn, i, n, note.Velocity)); if (note.Duration != -1) { track.Insert(ticks + note.Duration, new ChannelMessage(ChannelCommand.NoteOff, i, n)); } else { playing.Add(note); } } else if (e.Command is EndOfTieCommand eot) { M4ANoteCommand nc = null; if (eot.Note == -1) { nc = playing.LastOrDefault(); } else { nc = playing.LastOrDefault(n => n.Note == eot.Note); } if (nc != null) { int no = (nc.Note + shift).Clamp(0, 0x7F); track.Insert(ticks, new ChannelMessage(ChannelCommand.NoteOff, i, no)); playing.Remove(nc); } } else if (e.Command is VoiceCommand voice) { // TODO: Fork and remove restriction track.Insert(ticks, new ChannelMessage(ChannelCommand.ProgramChange, i, voice.Voice & 0x7F)); } else if (e.Command is VolumeCommand vol) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.Volume, vol.Volume)); } else if (e.Command is PanpotCommand pan) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.Pan, pan.Panpot + 0x40)); } else if (e.Command is BendCommand bend) { track.Insert(ticks, new ChannelMessage(ChannelCommand.PitchWheel, i, 0, bend.Bend + 0x40)); } else if (e.Command is BendRangeCommand bendr) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 20, bendr.Range)); } else if (e.Command is LFOSpeedCommand lfos) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 21, lfos.Speed)); } else if (e.Command is LFODelayCommand lfodl) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 26, lfodl.Delay)); } else if (e.Command is ModDepthCommand mod) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.ModulationWheel, mod.Depth)); } else if (e.Command is ModTypeCommand modt) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 22, modt.Type)); } else if (e.Command is TuneCommand tune) { track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 24, tune.Tune)); } else if (e.Command is TempoCommand tempo) { var change = new TempoChangeBuilder { Tempo = (60000000 / tempo.Tempo) }; change.Build(); metaTrack.Insert(ticks, change.Result); } else if (e.Command is CallCommand patt) { int callCmd = Commands[i].FindIndex(c => c.GetOffset() == patt.Offset); endOfPattern = j; endOfPatternTicks = e.AbsoluteTicks; j = callCmd - 1; // -1 for incoming ++ startOfPatternTicks = Commands[i][j + 1].AbsoluteTicks; } else if (e.Command is ReturnCommand) { if (endOfPattern != 0) { j = endOfPattern; endOfPattern = startOfPatternTicks = endOfPatternTicks = 0; } } else if (i == 0 && e.Command is GoToCommand goTo) { int jumpCmd = Commands[i].FindIndex(c => c.GetOffset() == goTo.Offset); metaTrack.Insert(Commands[i][jumpCmd].AbsoluteTicks, new MetaMessage(MetaType.Marker, new byte[] { (byte)'[' })); metaTrack.Insert(ticks, new MetaMessage(MetaType.Marker, new byte[] { (byte)']' })); } else if (e.Command is FinishCommand fine) { // TODO: Fix ticks before end of track event // Library automatically is updating track.EndOfTrackOffset for us break; } } } midi.Save(fileName); }
public override void ModifySequence(Sequence source, Sequence sequence) { sequence.Add(Modify(source[Index])); }
/// <summary> /// Performs Stage 1, 2, and 3 as described in class description. /// </summary> /// <param name="sequences">input unaligned sequences</param> public IList <MBF.Algorithms.Alignment.ISequenceAlignment> Align(IList <ISequence> sequences) { // Initializations if (sequences.Count > 0) { if (ConsensusResolver == null) { ConsensusResolver = new SimpleConsensusResolver(sequences[0].Alphabet); } else { ConsensusResolver.SequenceAlphabet = sequences[0].Alphabet; } } // Get ProfileAligner ready IProfileAligner profileAligner = null; switch (_profileAlignerName) { case (ProfileAlignerNames.NeedlemanWunschProfileAligner): if (_degreeOfParallelism == 1) { profileAligner = new NeedlemanWunschProfileAlignerSerial( SimilarityMatrix, _profileProfileFunctionName, GapOpenCost, GapExtensionCost, _numberOfPartitions); } else { profileAligner = new NeedlemanWunschProfileAlignerParallel( SimilarityMatrix, _profileProfileFunctionName, GapOpenCost, GapExtensionCost, _numberOfPartitions); } break; case (ProfileAlignerNames.SmithWatermanProfileAligner): if (_degreeOfParallelism == 1) { profileAligner = new SmithWatermanProfileAlignerSerial( SimilarityMatrix, _profileProfileFunctionName, GapOpenCost, GapExtensionCost, _numberOfPartitions); } else { profileAligner = new SmithWatermanProfileAlignerParallel( SimilarityMatrix, _profileProfileFunctionName, GapOpenCost, GapExtensionCost, _numberOfPartitions); } break; default: throw new ArgumentException("Invalid profile aligner name"); } _alignedSequences = new List <ISequence>(sequences.Count); float currentScore = 0; // STAGE 1 Performance.Snapshot("Stage 1"); // Generate DistanceMatrix KmerDistanceMatrixGenerator kmerDistanceMatrixGenerator = new KmerDistanceMatrixGenerator(sequences, _kmerLength, _moleculeType, _distanceFunctionName); // Hierarchical clustering IHierarchicalClustering hierarcicalClustering = new HierarchicalClusteringParallel (kmerDistanceMatrixGenerator.DistanceMatrix, _hierarchicalClusteringMethodName); // Generate Guide Tree BinaryGuideTree binaryGuideTree = new BinaryGuideTree(hierarcicalClustering); // Progressive Alignment IProgressiveAligner progressiveAlignerA = new ProgressiveAligner(profileAligner); progressiveAlignerA.Align(sequences, binaryGuideTree); currentScore = MsaUtils.MultipleAlignmentScoreFunction(progressiveAlignerA.AlignedSequences, SimilarityMatrix, GapOpenCost, GapExtensionCost); if (currentScore > _alignmentScoreA) { _alignmentScoreA = currentScore; _alignedSequencesA = progressiveAlignerA.AlignedSequences; } if (_alignmentScoreA > _alignmentScore) { _alignmentScore = _alignmentScoreA; _alignedSequences = _alignedSequencesA; } if (PAMSAMMultipleSequenceAligner.FasterVersion) { _alignedSequencesB = _alignedSequencesA; _alignedSequencesC = _alignedSequencesA; _alignmentScoreB = _alignmentScoreA; _alignmentScoreC = _alignmentScoreA; } else { BinaryGuideTree binaryGuideTreeB = null; IHierarchicalClustering hierarcicalClusteringB = null; KimuraDistanceMatrixGenerator kimuraDistanceMatrixGenerator = new KimuraDistanceMatrixGenerator(); if (PAMSAMMultipleSequenceAligner.UseStageB) { // STAGE 2 Performance.Snapshot("Stage 2"); // Generate DistanceMatrix from Multiple Sequence Alignment int iterateTime = 0; while (true) { ++iterateTime; kimuraDistanceMatrixGenerator.GenerateDistanceMatrix(_alignedSequences); // Hierarchical clustering hierarcicalClusteringB = new HierarchicalClusteringParallel (kimuraDistanceMatrixGenerator.DistanceMatrix, _hierarchicalClusteringMethodName); // Generate Guide Tree binaryGuideTreeB = new BinaryGuideTree(hierarcicalClusteringB); BinaryGuideTree.CompareTwoTrees(binaryGuideTreeB, binaryGuideTree); binaryGuideTree = binaryGuideTreeB; // Progressive Alignment IProgressiveAligner progressiveAlignerB = new ProgressiveAligner(profileAligner); progressiveAlignerB.Align(sequences, binaryGuideTreeB); currentScore = MsaUtils.MultipleAlignmentScoreFunction(progressiveAlignerB.AlignedSequences, SimilarityMatrix, GapOpenCost, GapExtensionCost); if (currentScore > _alignmentScoreB) { _alignmentScoreB = currentScore; _alignedSequencesB = progressiveAlignerB.AlignedSequences; break; } else { break; } } if (_alignmentScoreB > _alignmentScore) { _alignmentScore = _alignmentScoreB; _alignedSequences = _alignedSequencesB; } } else { binaryGuideTreeB = binaryGuideTree; } // STAGE 3 Performance.Snapshot("Stage 3"); // refinement //int maxRefineMentTime = sequences.Count * 2 - 2; int maxRefineMentTime = 1; if (sequences.Count == 2) { maxRefineMentTime = 0; } int refinementTime = 0; _alignedSequencesC = new List <ISequence>(sequences.Count); for (int i = 0; i < sequences.Count; ++i) { _alignedSequencesC.Add(new Sequence(_alphabet, _alignedSequences[i].ToString())); } List <int>[] leafNodeIndices = null; List <int>[] allIndelPositions = null; IProfileAlignment[] separatedProfileAlignments = null; List <int>[] eStrings = null; while (refinementTime < maxRefineMentTime) { ++refinementTime; Performance.Snapshot("Refinement iter " + refinementTime.ToString()); bool needRefinement = false; for (int edgeIndex = 0; edgeIndex < binaryGuideTreeB.NumberOfEdges; ++edgeIndex) { leafNodeIndices = binaryGuideTreeB.SeparateSequencesByCuttingTree(edgeIndex); allIndelPositions = new List <int> [2]; separatedProfileAlignments = ProfileAlignment.ProfileExtraction(_alignedSequencesC, leafNodeIndices[0], leafNodeIndices[1], out allIndelPositions); eStrings = new List <int> [2]; if (separatedProfileAlignments[0].NumberOfSequences < separatedProfileAlignments[1].NumberOfSequences) { profileAligner.Align(separatedProfileAlignments[0], separatedProfileAlignments[1]); eStrings[0] = profileAligner.GenerateEString(profileAligner.AlignedA); eStrings[1] = profileAligner.GenerateEString(profileAligner.AlignedB); } else { profileAligner.Align(separatedProfileAlignments[1], separatedProfileAlignments[0]); eStrings[0] = profileAligner.GenerateEString(profileAligner.AlignedB); eStrings[1] = profileAligner.GenerateEString(profileAligner.AlignedA); } for (int set = 0; set < 2; ++set) { Parallel.ForEach(leafNodeIndices[set], PAMSAMMultipleSequenceAligner.parallelOption, i => { Sequence seq = new Sequence(_alphabet, ""); seq.IsReadOnly = false; int indexAllIndel = 0; for (int j = 0; j < _alignedSequencesC[i].Count; ++j) { if (indexAllIndel < allIndelPositions[set].Count && j == allIndelPositions[set][indexAllIndel]) { ++indexAllIndel; } else { seq.Add(_alignedSequencesC[i][j]); } } seq = profileAligner.GenerateSequenceFromEString(eStrings[set], seq); seq.IsReadOnly = true; _alignedSequencesC[i] = seq; }); } currentScore = MsaUtils.MultipleAlignmentScoreFunction(_alignedSequencesC, SimilarityMatrix, GapOpenCost, GapExtensionCost); if (currentScore > _alignmentScoreC) { _alignmentScoreC = currentScore; needRefinement = true; // recreate the tree kimuraDistanceMatrixGenerator.GenerateDistanceMatrix(_alignedSequencesC); hierarcicalClusteringB = new HierarchicalClusteringParallel (kimuraDistanceMatrixGenerator.DistanceMatrix, _hierarchicalClusteringMethodName); binaryGuideTreeB = new BinaryGuideTree(hierarcicalClusteringB); break; } } if (!needRefinement) { refinementTime = maxRefineMentTime; break; } } if (_alignmentScoreC > _alignmentScore) { _alignmentScore = _alignmentScoreC; _alignedSequences = _alignedSequencesC; } Performance.Snapshot("Stop Stage 3"); } //just for the purpose of integrating PW and MSA with the same output IList <MBF.Algorithms.Alignment.ISequenceAlignment> results = new List <MBF.Algorithms.Alignment.ISequenceAlignment>(); return(results); }
protected void Initialize(float pWidth, float pHeight) { DismissDelay = 0.0f; // dismiss only with ok button! Height = pHeight; Width = pWidth; var xScale = pWidth/16.0f; var yScale = pHeight/16.0f; SlideInDirection = SlideDirection.RIGHT; SlideOutDirection = SlideDirection.LEFT; Background = Support.UnicolorSprite("bg", (byte)(LevelManager.Instance.BackgroundColor.R * 255.0f), (byte)(LevelManager.Instance.BackgroundColor.G * 255.0f), (byte)(LevelManager.Instance.BackgroundColor.B * 255.0f), 255); Background.Scale = new Vector2(xScale, yScale); this.AddChild(Background); _okButton = new BetterButton(256.0f, 64.0f) { Text = "okay", Position = Vector2.Zero }; _okButton.background.RegisterPalette(2); // this.AddChild(_okButton); // BIG CIRCLE BULLET POINT ICONS circleOneImg = Support.SpriteFromAtlas("crystallonUI", "1.png"); circleOneImg.Position = new Vector2(CIRCLE_ONE_X, CIRCLE_ONE_Y); circleTwoImg = Support.SpriteFromAtlas("crystallonUI", "2.png"); circleTwoImg.Position = new Vector2(CIRCLE_ONE_X, CIRCLE_ONE_Y - CIRCLE_DELTA_Y); circleThreeImg = Support.SpriteFromAtlas("crystallonUI", "3.png"); circleThreeImg.Position = new Vector2(CIRCLE_ONE_X, CIRCLE_ONE_Y - 2.0f * CIRCLE_DELTA_Y); // DIAGRAMS //--------- ORIENTATION DOESN'T MATTER cubeOneTop = Support.SpriteFromAtlas("gamePieces", "set1_v0_T.png"); cubeOneTop.RegisterPalette(0); cubeOneTop.Position = new Vector2(344.0f, (float)(544-81)); cubeOneTop.Scale = new Vector2(0.66f, 0.66f); cubeOneRight = Support.SpriteFromAtlas("gamePieces", "set1_v0_R.png"); cubeOneRight.RegisterPalette(1); cubeOneRight.Position = new Vector2(386.0f, (float)(544-130)); cubeOneRight.Scale = new Vector2(0.66f, 0.66f); cubeOneLeft = Support.SpriteFromAtlas("gamePieces", "set1_v0_T.png"); cubeOneLeft.RegisterPalette(2); cubeOneLeft.Position = new Vector2(247.0f, (float)(544-114)); cubeOneLeft.Scale = new Vector2(0.66f, 0.66f); //--------- WILDCARD wildcardImg = Support.SpriteFromAtlas("gamePieces", "set1_v0_T.png"); wildcardImg.RegisterPalette(0); wildcardImg.Scale = new Vector2(0.66f, 0.66f); wildcardImg.Position = new Vector2(247.0f, (float)(544-240)); Sequence sequence = new Sequence(); sequence.Add( new CallFunc( () => { wildcardImg.ShiftSpriteColor(QColor.palette[1], 0.08f); }) ); sequence.Add( new DelayTime(0.08f) ); sequence.Add( new CallFunc( () => { wildcardImg.ShiftSpriteColor(QColor.palette[2], 0.08f); }) ); sequence.Add( new DelayTime(0.08f) ); sequence.Add( new CallFunc( () => { wildcardImg.ShiftSpriteColor(QColor.palette[0], 0.08f); }) ); sequence.Add( new DelayTime(0.08f) ); wildcardImg.RunAction( new RepeatForever() { InnerAction=sequence, Tag = 40 } ); //---------- STRIKES heartOne = Support.SpriteFromAtlas("crystallonUI", "heart.png"); heartOne.RegisterPalette(1); heartOne.Position = new Vector2(247.0f, (float)(544-380)); heartTwo = Support.SpriteFromAtlas("crystallonUI", "heart.png"); heartTwo.RegisterPalette(1); heartTwo.Position = new Vector2(304.0f, (float)(544-380)); heartThree = Support.SpriteFromAtlas("crystallonUI", "heart.png"); heartThree.RegisterPalette(1); heartThree.Position = new Vector2(362.0f, (float)(544-380)); strikeFour = Support.SpriteFromAtlas("crystallonUI", "strike.png"); strikeFour.RegisterPalette(2); strikeFour.Position = new Vector2(666.0f, (float)(544-379)); heartFive = Support.SpriteFromAtlas("crystallonUI", "heart.png"); heartFive.RegisterPalette(1); heartFive.Position = new Vector2(716.0f, (float)(544-380)); heartSix = Support.SpriteFromAtlas("crystallonUI", "heart.png"); heartSix.RegisterPalette(1); heartSix.Position = new Vector2(774.0f, (float)(544-380)); cubeTwoTop = Support.SpriteFromAtlas("gamePieces", "set1_v0_T.png"); cubeTwoTop.RegisterPalette(2); cubeTwoTop.Position = new Vector2(491.0f, (float)(544-360)); cubeTwoTop.Scale = new Vector2(0.66f, 0.66f); cubeTwoRight = Support.SpriteFromAtlas("gamePieces", "set1_v0_R.png"); cubeTwoRight.RegisterPalette(1); cubeTwoRight.Position = new Vector2(533.0f, (float)(544-409)); cubeTwoRight.Scale = new Vector2(0.66f, 0.66f); cubeTwoLeft = Support.SpriteFromAtlas("gamePieces", "set1_v0_L.png"); cubeTwoLeft.RegisterPalette(1); cubeTwoLeft.Position = new Vector2(491.0f, (float)(544-409)); cubeTwoLeft.Scale = new Vector2(0.66f, 0.66f); plus = Support.SpriteFromAtlas("crystallonUI", "plus.png"); plus.Color = Colors.Black; plus.Scale = new Vector2(0.66f, 0.66f); plus.Position = new Vector2(432.0f, (float)(544-372)); arrow = Support.SpriteFromAtlas("crystallonUI", "arrow.png"); arrow.Color = Colors.Black; arrow.Scale = new Vector2(0.5f, 0.5f); arrow.Position = new Vector2(607.0f, (float)(544-372)); // equationLabel = new Label() { // Text = "+ =", // Color = Colors.Black, // FontMap = FontManager.Instance.GetMap( FontManager.Instance.GetInGame("Bariol", 25, "Bold") ), // Position = new Vector2(432.0f, (float)(544-372)) // }; // TEXT LABELS instructionOneLabel = new Label() { Text = INSTRUCTION_ONE_TEXT, Color = Colors.Black, FontMap = FontManager.Instance.GetMap( FontManager.Instance.GetInGame("Bariol", 25, "Bold") ), Position = new Vector2(453.0f, 466.0f) }; instructionTwoLabel = new Label() { Text = INSTRUCTION_TWO_TEXT, Color = Colors.Black, FontMap = FontManager.Instance.GetMap( FontManager.Instance.GetInGame("Bariol", 25, "Bold") ), Position = new Vector2(358.0f, 315.0f) }; instructionThreeLabel = new Label() { Text = INSTRUCTION_THREE_TEXT, Color = Colors.Black, FontMap = FontManager.Instance.GetMap( FontManager.Instance.GetInGame("Bariol", 25, "Bold") ), Position = new Vector2(249.0f, 98.0f) }; this.AddChild(_okButton); this.AddChild(circleOneImg); this.AddChild(circleTwoImg); this.AddChild(circleThreeImg); this.AddChild(cubeOneTop); this.AddChild(cubeOneRight); this.AddChild(cubeOneLeft); this.AddChild(wildcardImg); this.AddChild(heartOne); this.AddChild(heartTwo); this.AddChild(heartThree); this.AddChild(strikeFour); this.AddChild(heartFive); this.AddChild(heartSix); this.AddChild(cubeTwoTop); this.AddChild(cubeTwoRight); this.AddChild(cubeTwoLeft); // this.AddChild(equationLabel); this.AddChild(plus); this.AddChild(arrow); this.AddChild(instructionOneLabel); this.AddChild(instructionTwoLabel); this.AddChild(instructionThreeLabel); }
public override void SaveAsMIDI(string fileName) { if (NumTracks == 0) { throw new InvalidDataException("This song has no tracks."); } CalculateTicks(); var midi = new Sequence(24) { Format = 1 }; var metaTrack = new Sanford.Multimedia.Midi.Track(); midi.Add(metaTrack); for (int i = 0; i < NumTracks; i++) { var track = new Sanford.Multimedia.Midi.Track(); midi.Add(track); int endOfPattern = 0, startOfPatternTicks = 0, endOfPatternTicks = 0, shift = 0; var playing = new List <M4ANoteCommand>(); for (int j = 0; j < Commands[i].Count; j++) { var e = Commands[i][j]; int ticks = e.AbsoluteTicks + (endOfPatternTicks - startOfPatternTicks); switch (e.Command) { case KeyShiftCommand keysh: shift = keysh.Shift; break; case M4ANoteCommand note: int n = (note.Note + shift).Clamp(0, 0x7F); track.Insert(ticks, new ChannelMessage(ChannelCommand.NoteOn, i, n, note.Velocity)); if (note.Duration != -1) { track.Insert(ticks + note.Duration, new ChannelMessage(ChannelCommand.NoteOff, i, n)); } else { playing.Add(note); } break; case EndOfTieCommand eot: M4ANoteCommand nc = null; if (eot.Note == -1) { nc = playing.LastOrDefault(); } else { nc = playing.LastOrDefault(no => no.Note == eot.Note); } if (nc != null) { n = (nc.Note + shift).Clamp(0, 0x7F); track.Insert(ticks, new ChannelMessage(ChannelCommand.NoteOff, i, n)); playing.Remove(nc); } break; case PriorityCommand prio: track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.VolumeFine, prio.Priority)); break; case VoiceCommand voice: track.Insert(ticks, new ChannelMessage(ChannelCommand.ProgramChange, i, voice.Voice)); break; case VolumeCommand vol: track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.Volume, vol.Volume)); break; case PanpotCommand pan: track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.Pan, pan.Panpot + 0x40)); break; case BendCommand bend: track.Insert(ticks, new ChannelMessage(ChannelCommand.PitchWheel, i, 0, bend.Bend + 0x40)); break; case BendRangeCommand bendr: track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 20, bendr.Range)); break; case LFOSpeedCommand lfos: track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 21, lfos.Speed)); break; case LFODelayCommand lfodl: track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 26, lfodl.Delay)); break; case ModDepthCommand mod: track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.ModulationWheel, mod.Depth)); break; case ModTypeCommand modt: track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 22, modt.Type)); break; case TuneCommand tune: track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 24, tune.Tune)); break; case LibraryCommand xcmd: track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 30, xcmd.Command)); track.Insert(ticks, new ChannelMessage(ChannelCommand.Controller, i, 29, xcmd.Argument)); break; case TempoCommand tempo: var change = new TempoChangeBuilder { Tempo = (60000000 / tempo.Tempo) }; change.Build(); metaTrack.Insert(ticks, change.Result); break; case CallCommand patt: int callCmd = Commands[i].FindIndex(c => c.GetOffset() == patt.Offset); endOfPattern = j; endOfPatternTicks = e.AbsoluteTicks; j = callCmd - 1; // -1 for incoming ++ startOfPatternTicks = Commands[i][j + 1].AbsoluteTicks; break; case ReturnCommand _: if (endOfPattern != 0) { j = endOfPattern; endOfPattern = startOfPatternTicks = endOfPatternTicks = 0; } break; case GoToCommand goTo: if (i == 0) { int jumpCmd = Commands[i].FindIndex(c => c.GetOffset() == goTo.Offset); metaTrack.Insert(Commands[i][jumpCmd].AbsoluteTicks, new MetaMessage(MetaType.Marker, new byte[] { (byte)'[' })); metaTrack.Insert(ticks, new MetaMessage(MetaType.Marker, new byte[] { (byte)']' })); } break; case FinishCommand _: goto endOfTrack; } } endOfTrack :; } midi.Save(fileName); }
private void Shake(Strike strike) { var origin = strike.Position; strike.StopAllActions(); Sequence s = new Sequence(); s.Add( new MoveBy(new Vector2(2.0f, 0.0f), 0.005f) { Tween = Sce.PlayStation.HighLevel.GameEngine2D.Base.Math.Linear }); s.Add( new MoveBy(new Vector2(-4.0f, 0.0f), 0.01f){ Tween = Sce.PlayStation.HighLevel.GameEngine2D.Base.Math.Linear }); s.Add( new MoveTo(origin, 0.005f){ Tween = Sce.PlayStation.HighLevel.GameEngine2D.Base.Math.Linear }); strike.RunAction(new Repeat(s, 6)); }
internal void SwitchOff() { gpiPin.Write(GpioPinValue.Low); Sequence.Add(new Tuple <Color, string>(this.color, gpiPin.Read().ToString())); }
public void SlideOut(SlideDirection pDirection) { InputManager.Instance.TapDetected -= HandleInputManagerInstanceTapDetected; InputManager.Instance.DragDetected -= HandleInputManagerInstanceDragDetected; Vector2 Destination; Destination = Offset; if (SourceObject != null) { Destination += SourceObject.Position; } switch(pDirection){ case(SlideDirection.LEFT): Destination += new Vector2(-Width, 0.0f); break; case(SlideDirection.DOWN): Destination += new Vector2(0.0f, -Height); break; default: break; } Sequence sequence = new Sequence(); sequence.Add( new CallFunc( () => { EventHandler handler = OnSlideOutStart; if ( handler != null ) { handler( this, null ); } } ) ); sequence.Add( new MoveTo( Destination, MoveDuration) ); sequence.Add( new CallFunc( () => { // Visible=false; EventHandler handler = OnSlideOutComplete; if ( handler != null ) { handler( this, null ); } } ) ); this.RunAction(sequence); }
public void AllEditableScenarios() { string filepathOriginal = @"TestData\Fasta\5_sequences.fasta"; Assert.IsTrue(File.Exists(filepathOriginal)); FastaParser fastaParser = new FastaParser(); IList <ISequence> sequences; string[] expectedSequences = new string[] { "KRIPKSQNLRSIHSIFPFLEDKLSHLN", "LNIPSLITLNKSIYVFSKRKKRLSGFLHN", "HEAGAWGHEEHEAGAWGHEEHEAGAWGHEE", "PAWHEAEPAWHEAEPAWHEAEPAWHEAEPAWHEAE", "CGGUCCCGCGGUCCCGCGGUCCCGCGGUCCCG" }; fastaParser.EnforceDataVirtualization = true; sequences = fastaParser.Parse(filepathOriginal, true); int sequenceCount = sequences.Count; for (int i = 0; i < sequenceCount; i++) { Sequence actualSequence = sequences[i] as Sequence; actualSequence.IsReadOnly = false; ISequenceItem item = actualSequence[1]; actualSequence.Add(item); expectedSequences[i] += item.Symbol; Assert.AreEqual(expectedSequences[i], actualSequence.ToString()); actualSequence.Remove(item); int indexOfItem = expectedSequences[i].IndexOf(item.Symbol); expectedSequences[i] = expectedSequences[i].Remove(indexOfItem, 1); Assert.AreEqual(expectedSequences[i], actualSequence.ToString()); actualSequence.RemoveAt(0); expectedSequences[i] = expectedSequences[i].Remove(0, 1); Assert.AreEqual(expectedSequences[i], actualSequence.ToString()); actualSequence.RemoveRange(2, 5); expectedSequences[i] = expectedSequences[i].Remove(2, 5); Assert.AreEqual(expectedSequences[i], actualSequence.ToString()); actualSequence.Replace(0, 'C'); expectedSequences[i] = expectedSequences[i].Remove(0, 1); expectedSequences[i] = expectedSequences[i].Insert(0, "C"); Assert.AreEqual(expectedSequences[i], actualSequence.ToString()); actualSequence.ReplaceRange(3, "GG"); expectedSequences[i] = expectedSequences[i].Remove(3, 2); expectedSequences[i] = expectedSequences[i].Insert(3, "GG"); Assert.AreEqual(expectedSequences[i], actualSequence.ToString()); actualSequence.Insert(3, item); expectedSequences[i] = expectedSequences[i].Insert(3, item.Symbol.ToString()); Assert.AreEqual(expectedSequences[i], actualSequence.ToString()); actualSequence.InsertRange(2, "CC"); expectedSequences[i] = expectedSequences[i].Insert(2, "CC"); Assert.AreEqual(expectedSequences[i], actualSequence.ToString()); bool actualContainsValue = actualSequence.Contains(actualSequence[3]); bool expectedContainsValue = expectedSequences[i].Contains(actualSequence[3].Symbol.ToString()); Assert.AreEqual(actualContainsValue, expectedContainsValue); } }
/// <summary> /// This method validates the requirements under /// ConsistencyRules Scenario. /// </summary> public void ValidateConsistencyRules() { #region MS-ADTS-Schema_R73 //The objectClass attribute of the attributeSchema equals the sequence [top, attributeSchema ] //Expected Sequence setting... Sequence <string> expectedSeq = new Sequence <string>(); Sequence <string> actualSeq = new Sequence <string>(); DirectoryEntry serverObject; string requiredObjectDN = String.Empty; expectedSeq.Add("top"); expectedSeq.Add("classSchema"); //Get attributeSchema from Server. requiredObjectDN = "CN=Attribute-Schema,CN=Schema,CN=Configuration," + adAdapter.rootDomainDN; if (!adAdapter.GetObjectByDN(requiredObjectDN, out serverObject)) { DataSchemaSite.Assume.IsTrue(false, requiredObjectDN + " Object is not found in server"); } foreach (string valueString in serverObject.Properties[StandardNames.objectClass.ToLower()]) { actualSeq.Add(valueString.ToLower()); } //MS-ADTS-Schema_R73. DataSchemaSite.CaptureRequirementIfAreEqual <Sequence <string> >( expectedSeq, actualSeq, 73, "The objectClass attribute of the attributeSchema equals the sequence [top, classSchema ]."); #endregion #region MS-ADTS-Schema_R157 //The objectClass attribute of the classSchema equals the sequence [top, classSchema ]. //Get classSchema from Server. requiredObjectDN = "CN=Class-Schema,CN=Schema,CN=Configuration," + adAdapter.rootDomainDN; if (!adAdapter.GetObjectByDN(requiredObjectDN, out serverObject)) { DataSchemaSite.Assume.IsTrue(false, requiredObjectDN + " Object is not found in server"); } actualSeq = new Sequence <string>(); foreach (string valueString in serverObject.Properties[StandardNames.objectClass.ToLower()]) { actualSeq.Add(valueString.ToLower()); } //MS-ADTS-Schema_R157. DataSchemaSite.CaptureRequirementIfAreEqual <Sequence <string> >( expectedSeq, actualSeq, 157, "The objectClass attribute of the classSchema equals the sequence [top, classSchema ]."); #endregion #region MS-ADTS-Schema_R128-133,136-142,179 //Inheritance rule requirements IEnumerable <IObjectOnServer> serverObjects = adAdapter.GetAllSchemaClasses(); if (serverObjects == null) { DataSchemaSite.Assume.IsNotNull(serverObjects, "Class objects are not existing in Server"); } DataSchemaSite.Log.Add(LogEntryKind.Comment, "Begin ValidateInheritanceRequirements"); //This method will validate the requirements MS-ADTS-Schema_R128-133,136-142,179. ValidateInheritanceRequirements(serverObjects, true); #endregion #region MS-ADTS-Schema_R143-146 //Covering ObjectClass requirements //Get domain NC for validation. DirectoryEntry domainEntry; if (!adAdapter.GetObjectByDN(adAdapter.rootDomainDN, out domainEntry)) { DataSchemaSite.Assume.IsTrue(false, adAdapter.rootDomainDN + " Object is not found in server"); } DataSchemaSite.Log.Add(LogEntryKind.Comment, "Begin ValidateObjectClassRequirements"); //This method validates teh requirements MS-ADTS-Schema_R143-146 ValidateObjectClassRequirements(domainEntry.Children, true); #endregion #region MS-ADTS-Schema_R149,175 //Coverring StructureRule requirements DataSchemaSite.Log.Add(LogEntryKind.Comment, "Begin ValidateStructureRulesRequirements"); //This method validates the requirements MS-ADTS-Schema_R149,175 ValidateStructureRulesRequirements(serverObjects, true); #endregion #region MS-ADTS-Schema_R152,153 //Covering ContentRule requirements DataSchemaSite.Log.Add(LogEntryKind.Comment, "Begin ValidateContentRulesRequirements"); //This method validates the requirements MS-ADTS-Schema_R152,153. ValidateContentRulesRequirements(domainEntry.Children, serverObjects); #endregion #region MS-ADTS-Schema_R177 //The systemAuxiliaryClass attribute of the classSchema Specifies governsIDs of the classes that can //be parents of the class within an NC tree, where the parent-child relationships are required for //system operation. DirectoryEntry classSchemaObj; bool isAuxiliary = false; SetContainer <string> auxiliaryClassValue = new SetContainer <string>(); //Get class-schema class from server. if (!adAdapter.GetObjectByDN("CN=Class-Schema,CN=Schema,CN=Configuration," + adAdapter.rootDomainDN, out classSchemaObj)) { DataSchemaSite.Assume.IsTrue( false, "CN=Class-Schema,CN=Schema,CN=Configuration," + adAdapter.rootDomainDN + " Object is not found in server"); } //Collect its auxiliary class value. if (classSchemaObj.Properties.Contains("auxiliaryclass")) { //AuxiliaryClassValue.Add foreach (string value in classSchemaObj.Properties["auxiliaryclass"]) { auxiliaryClassValue.Add(value); } } //Collect its system auxiliary class value. if (classSchemaObj.Properties.Contains("systemauxiliaryclass")) { //AuxiliaryClassValue.Add foreach (string value in classSchemaObj.Properties["systemauxiliaryclass"]) { auxiliaryClassValue.Add(value); } } if (auxiliaryClassValue.Count != 0) { //For each auxiliary class... foreach (string auxClass in auxiliaryClassValue) { isAuxiliary = false; foreach (IObjectOnServer serverObj in serverObjects) { //Get it from server. if (serverObj.Name.Equals(auxClass)) { //Get server object governsID. string governsID = (string)serverObj.Properties[StandardNames.governsId.ToLower()][0]; //It should be eqal to the auxiliary class name of the class. if (governsID.Equals(auxClass)) { isAuxiliary = true; continue; } } } if (isAuxiliary) { continue; } else { break; } } } //MS-ADTS-Schema_R177. DataSchemaSite.Log.Add(LogEntryKind.Comment, "SystemAuxiliaryClass TDI is resolved"); #endregion }
public void SwitchOn() { gpiPin.Write(GpioPinValue.High); Sequence.Add(new Tuple <Color, string>(this.color, gpiPin.Read().ToString())); }
protected void Slide(bool pUp, int pDestPage) { Sequence s = new Sequence() {Tag = (int)Tags.TRANSLATION}; s.Add( new DelayTime(3.0f) ); s.Add( new MoveBy( pUp ? SLIDE_VECTOR : -SLIDE_VECTOR, 2.0f) ); // s.Add( new DelayTime(1.0f) ); s.Add( new CallFunc( () => { if ( ( pUp && possibleSolutions < ((1+pDestPage) * MAX_VIEWABLE_SOLUTIONS)) || ( !pUp && pDestPage-1 < 0) ) { pUp = !pUp; } pDestPage = pUp ? pDestPage + 1 : pDestPage - 1; Slide (pUp, pDestPage); // Console.WriteLine("{0} {1} {2}", pUp, pDestPage, this.Position); })); this.RunAction( s ); }
public void MyNewCollection_Change(object sender, MyNewCollectionEventArgs e) { list.Add(new JournalEntry(e.CollectionName, e.ChangeDescription, e.ChangedItem)); }
protected void SpawnIcons(ICrystallonEntity pParent, Dictionary<string,int> pQualities, Vector4 pColor) { icon = null; Sequence sequence = new Sequence(); foreach( string key in pQualities.Keys) { if (icon != null) { continue; } if(key=="Orientation") { continue; } switch(key){ case("Color"): icon = ColorIcon.Instance; break; default: int ix = (int)EnumHelper.FromString<Crystallography.Icons>(key); icon = Support.TiledSpriteFromFile("/Application/assets/images/icons/icons.png", 4, 2 ); (icon as SpriteTile).TileIndex1D = ix; (icon as SpriteBase).RegisterPalette((int)FMath.Floor(GameScene.Random.NextFloat()*3)); break; } } icon.Position = pParent.Parent.Parent.Position.Xy - iconSize/2.0f; if(icon.Parent != null){ icon.Parent.RemoveChild(icon, false); } GameScene.Layers[2].AddChild(icon); sequence.Add( new DelayTime(0.1f)); sequence.Add( new CallFunc( () => {icon.Visible = false;})); sequence.Add (new DelayTime(0.05f)); sequence.Add( new CallFunc( () => {icon.Visible = true;})); sequence.Add( new DelayTime(0.1f)); sequence.Add( new CallFunc( () => {icon.Visible = false;})); sequence.Add (new DelayTime(0.05f)); sequence.Add( new CallFunc( () => {icon.Visible = true;})); sequence.Add( new DelayTime(0.75f)); sequence.Add( new CallFunc( () => {icon.Visible = false;})); sequence.Add(new CallFunc( () => { icon.Visible = true; GameScene.Layers[2].RemoveChild(icon, true); })); icon.RunAction(sequence); }
/// <summary> /// We create MIDI from WPF staffs, 2 different dependencies, not a good practice. /// TODO: Create MIDI from our own domain classes. /// TODO: Our code doesn't support repeats (rendering notes multiple times) in midi yet. Maybe with a COMPOSITE this will be easier? /// </summary> /// <returns></returns> private Sequence GetSequenceFromWPFStaffs() { List <string> notesOrderWithCrosses = new List <string>() { "c", "cis", "d", "dis", "e", "f", "fis", "g", "gis", "a", "ais", "b" }; int absoluteTicks = 0; Sequence sequence = new Sequence(); Track metaTrack = new Track(); sequence.Add(metaTrack); // Calculate tempo int speed = (60000000 / _bpm); byte[] tempo = new byte[3]; tempo[0] = (byte)((speed >> 16) & 0xff); tempo[1] = (byte)((speed >> 8) & 0xff); tempo[2] = (byte)(speed & 0xff); metaTrack.Insert(0 /* Insert at 0 ticks*/, new MetaMessage(MetaType.Tempo, tempo)); Track notesTrack = new Track(); sequence.Add(notesTrack); for (int i = 0; i < WPFStaffs.Count; i++) { var musicalSymbol = WPFStaffs[i]; switch (musicalSymbol.Type) { case MusicalSymbolType.Note: Note note = musicalSymbol as Note; // Calculate duration double absoluteLength = 1.0 / (double)note.Duration; absoluteLength += (absoluteLength / 2.0) * note.NumberOfDots; double relationToQuartNote = _beatNote / 4.0; double percentageOfBeatNote = (1.0 / _beatNote) / absoluteLength; double deltaTicks = (sequence.Division / relationToQuartNote) / percentageOfBeatNote; // Calculate height int noteHeight = notesOrderWithCrosses.IndexOf(note.Step.ToLower()) + ((note.Octave + 1) * 12); noteHeight += note.Alter; notesTrack.Insert(absoluteTicks, new ChannelMessage(ChannelCommand.NoteOn, 1, noteHeight, 90)); // Data2 = volume absoluteTicks += (int)deltaTicks; notesTrack.Insert(absoluteTicks, new ChannelMessage(ChannelCommand.NoteOn, 1, noteHeight, 0)); // Data2 = volume break; case MusicalSymbolType.TimeSignature: byte[] timeSignature = new byte[4]; timeSignature[0] = (byte)_beatsPerBar; timeSignature[1] = (byte)(Math.Log(_beatNote) / Math.Log(2)); metaTrack.Insert(absoluteTicks, new MetaMessage(MetaType.TimeSignature, timeSignature)); break; default: break; } } notesTrack.Insert(absoluteTicks, MetaMessage.EndOfTrackMessage); metaTrack.Insert(absoluteTicks, MetaMessage.EndOfTrackMessage); return(sequence); }
public override void SaveAsMIDI(string fileName) { if (NumTracks == 0) { throw new InvalidDataException("Questa canzone non ha tracce."); } CalculateTicks(); var midi = new Sequence(96) { Format = 1 }; var metaTrack = new Sanford.Multimedia.Midi.Track(); midi.Add(metaTrack); for (int i = 0; i < NumTracks; i++) { var track = new Sanford.Multimedia.Midi.Track(); midi.Add(track); FreeNoteCommand freeNote = null; MidiEvent freeNoteOff = null; for (int j = 0; j < Commands[i].Count; j++) { var e = Commands[i][j]; // Extended note ended ended and wasn't renewed if (freeNoteOff != null && freeNoteOff.AbsoluteTicks < e.AbsoluteTicks * 2) { freeNote = null; freeNoteOff = null; } if (e.Command is VolumeCommand vol) { track.Insert(e.AbsoluteTicks * 2, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.Volume, vol.Volume / 2)); } else if (e.Command is VoiceCommand voice) { // TODO: Fork and remove restriction track.Insert(e.AbsoluteTicks * 2, new ChannelMessage(ChannelCommand.ProgramChange, i, voice.Voice & 0x7F)); } else if (e.Command is PanpotCommand pan) { track.Insert(e.AbsoluteTicks * 2, new ChannelMessage(ChannelCommand.Controller, i, (int)ControllerType.Pan, pan.Panpot / 2 + 0x40)); } else if (e.Command is BendCommand bend) { track.Insert(e.AbsoluteTicks * 2, new ChannelMessage(ChannelCommand.PitchWheel, i, 0, bend.Bend / 2 + 0x40)); } else if (e.Command is BendRangeCommand bendr) { track.Insert(e.AbsoluteTicks * 2, new ChannelMessage(ChannelCommand.Controller, i, 20, bendr.Range / 2)); } else if (e.Command is MLSSNoteCommand note) { // Extended note is playing and it should be extended by this note if (freeNote != null && freeNote.Note - 0x80 == note.Note) { // Move the note off command track.Move(freeNoteOff, freeNoteOff.AbsoluteTicks + note.Duration * 2); } // Extended note is playing but this note is different OR there is no extended note playing // Either way we play a new note and forget that one else { track.Insert(e.AbsoluteTicks * 2, new ChannelMessage(ChannelCommand.NoteOn, i, note.Note, 0x7F)); track.Insert(e.AbsoluteTicks * 2 + note.Duration * 2, new ChannelMessage(ChannelCommand.NoteOff, i, note.Note)); freeNote = null; freeNoteOff = null; } } else if (e.Command is FreeNoteCommand free) { // Extended note is playing and it should be extended if (freeNote != null && freeNote.Note == free.Note) { // Move the note off command track.Move(freeNoteOff, freeNoteOff.AbsoluteTicks + free.Duration * 2); } // Extended note is playing but this note is different OR there is no extended note playing // Either way we play a new note and forget that one else { track.Insert(e.AbsoluteTicks * 2, new ChannelMessage(ChannelCommand.NoteOn, i, free.Note - 0x80, 0x7F)); track.Insert(e.AbsoluteTicks * 2 + free.Duration * 2, new ChannelMessage(ChannelCommand.NoteOff, i, free.Note - 0x80)); freeNote = free; freeNoteOff = track.GetMidiEvent(track.Count - 2); // -1 would be the end of track event } } else if (i == 0 && e.Command is TempoCommand tempo) { var change = new TempoChangeBuilder { Tempo = (60000000 / tempo.Tempo) }; change.Build(); metaTrack.Insert(e.AbsoluteTicks * 2, change.Result); } else if (i == 0 && e.Command is GoToCommand goTo) { int jumpCmd = Commands[i].FindIndex(c => c.GetOffset() == goTo.Offset); metaTrack.Insert(Commands[i][jumpCmd].AbsoluteTicks * 2, new MetaMessage(MetaType.Marker, new byte[] { (byte)'[' })); metaTrack.Insert(e.AbsoluteTicks * 2, new MetaMessage(MetaType.Marker, new byte[] { (byte)']' })); } else if (e.Command is FinishCommand fine) { // TODO: Fix ticks before end of track event // Library automatically is updating track.EndOfTrackOffset for us break; } } } midi.Save(fileName); }
public override void ModifySequence(Sequence source, Sequence sequence) { sequence.Add(Lingon); }
/// Add action to the code public void Add(IScriptAction action) { string methodId; for (int n = 0; ; ++n) { if (string.IsNullOrEmpty(action.Id)) methodId = "_" + CustomAttributeHelper.First<XsTypeAttribute>(action.GetType()).Name; else methodId = action.Id; if (n != 0) methodId += n; if (!_methodNames.ContainsKey(methodId)) { _methodNames[methodId] = true; break; } } if (action is Script || methodId==action.Id || action is Sub) { Methods.Add(action); } else { Sequence b = new Sequence { Id = methodId }; b.Add(action); Methods.Add(b); Value += Environment.NewLine + "{ object __ret=" + methodId + "_inline(); if (__ret!=null) return __ret;}"; } }
/// <summary> /// Format the raw text into an easier (aka faster) format to parse. /// * Process \n such that they are removed and 'new lines' created /// * Break down the text into lines that fit the requested width /// </summary> /// <param name="text">The raw text to parse</param> private void format(string text) { //Debug.Log("Formatting: " + text); _guiStyle = new GUIStyle(); int endIndex; _line = new StringBuilder(); _fLine = new FormattedLine(); addLineHeight(false); _lineLength = 0; _lineHeight = 0.0f; StringBuilder word = new StringBuilder(); _sequence = new Sequence(); _nextSequence = new Sequence(); for (int letterIndex = 0; letterIndex < text.Length; letterIndex++) { int currentLetterIndex = letterIndex; if (text[letterIndex] == '\\' && text.Length > letterIndex + 1 && text[letterIndex + 1] == '\\') { // Escaped '\' word.Append("\\"); letterIndex++; // Skip the second '\' } else if (text[letterIndex] == '\n') { // New line addWordToLine(word.ToString()); createNewLine(); word.Length = 0; } else if (text[letterIndex] == ' ' && word.Length != 0) { // Reached a word boundary addWordToLine(word.ToString()); word.Length = 0; word.Append(' '); } else if (text[letterIndex] == '[' && text.Length > letterIndex + 1 && text[letterIndex + 1] == '[') { // Escaped '[' word.Append("[["); letterIndex++; // Skip the second '[' } else if (text[letterIndex] == '[' && text.Length > letterIndex + 1 && (endIndex = text.IndexOf(']', letterIndex)) != -1) { // Command addWordToLine(word.ToString()); word.Length = 0; string command = text.Substring(letterIndex + 1, endIndex - letterIndex - 1); letterIndex += command.Length + 1; string[] commandList = command.Split(' '); for (int commandIndex = 0; commandIndex < commandList.Length; commandIndex++) { command = commandList[commandIndex].ToUpper(); if (command.IsEqual("NL") || command.IsEqual("NEWLINE")) { createNewLine(); } else if (command.IsEqual("BC") || command.IsEqual("BACKCOLOR")) //if (command == "BC" || command == "BACKCOLOR") { // Background Color if (commandList.Length > commandIndex + 1) { commandIndex++; Color color; if (commandList[commandIndex] == "?") { _nextSequence.Add(new BackColor(_guiStyle.normal.background)); addCommandToLine("BC " + commandList[commandIndex]); } else if (HexUtil.HexToColor(commandList[commandIndex], out color)) { _nextSequence.Add(new BackColor(commandList[commandIndex])); addCommandToLine("BC " + commandList[commandIndex]); } else { Debug.LogError("The 'BackColor' command requires a color parameter of RRGGBBAA or '?'."); } } else { Debug.LogError("The 'BackColor' command requires a color parameter of RRGGBBAA or '?'."); } } else if (command.IsEqual("C") || command.IsEqual("COLOR")) { // Color if (commandList.Length > commandIndex + 1) { commandIndex++; Color color; if (commandList[commandIndex] == "?" || HexUtil.HexToColor(commandList[commandIndex], out color)) { _nextSequence.Add(new FontColor(color)); addCommandToLine("C " + commandList[commandIndex]); } else { Debug.LogError("The 'color' command requires a color parameter of RRGGBBAA or '?'."); } } else { Debug.LogError("The 'color' command requires a color parameter of RRGGBBAA:\n" + text); } } else if (command.IsEqual("F") || command.IsEqual("FONT")) { // Font if (commandList.Length > commandIndex + 1) { commandIndex++; Font font = (Font)fontTable[commandList[commandIndex]]; if (font == null) { Debug.LogError("The font '" + commandList[commandIndex] + "' does not exist within Assets/Resources/Fonts/"); } else { _guiStyle.font = font; // Update the font to properly measure text addCommandToLine("F " + commandList[commandIndex]); _nextSequence.Add(new CustomFont(font)); } if (commandList.Length > commandIndex + 1) { commandIndex++; int fontSize; if (System.Int32.TryParse(commandList[commandIndex], out fontSize)) { addCommandToLine("FS " + commandList[commandIndex]); _nextSequence.Add(new FontSize(fontSize)); _guiStyle.fontSize = fontSize; // Update the size to properly measure text } else { Debug.LogError("The font size '" + commandList[commandIndex] + "' is not a valid integer"); } } } else { Debug.LogError("The 'font' command requires a font name parameter and an optional font size parameter."); } } else if (command.IsEqual("FA") || command.IsEqual("FONTATTRIBUTE")) { // Font Attribute if (commandList.Length > commandIndex + 1) { commandIndex++; string attribute = commandList[commandIndex].ToUpper(); switch (attribute) { case "U": case "UNDERLINE": attribute = "U"; _nextSequence.underline = true; break; case "-U": case "-UNDERLINE": attribute = "-U"; _nextSequence.underline = false; break; case "S": case "STRIKETHROUGH": attribute = "S"; Debug.Log("strike ? " + _nextSequence.txt); _nextSequence.strikeThrough = true; break; case "-S": case "-STRIKETHROUGH": attribute = "-S"; _nextSequence.strikeThrough = false; break; default: attribute = ""; Debug.LogError("The 'font attribute' command requires a font parameter of U (underline on), -U (underline off), S (strikethrough on) or -S (strikethrough off)."); break; } if (attribute.Length != 0) { addCommandToLine("FA " + attribute); } } else { Debug.LogError("The 'font attribute' command requires a font parameter of U (underline on), -U (underline off), S (strikethrough on) or -S (strikethrough off)."); } } else if (command.IsEqual("FS") || command.IsEqual("FONTSIZE")) { // Font Size if (commandList.Length > commandIndex + 1) { commandIndex++; int fontSize; if (System.Int32.TryParse(commandList[commandIndex], out fontSize)) { addCommandToLine("FS " + commandList[commandIndex]); _nextSequence.Add(new FontSize(fontSize)); _guiStyle.fontSize = fontSize; // Update the size to properly measure text } else { Debug.LogError("The font size '" + commandList[commandIndex] + "' is not a valid integer"); } } else { Debug.LogError("The 'font size' command requires a font size parameter."); } } else if (command.IsEqual("H") || command.IsEqual("HYPERLINK")) { // Hyperlink on if (commandList.Length > commandIndex + 1) { commandIndex++; addCommandToLine("H " + commandList[commandIndex]); _nextSequence.hyperlinkId = HYPERLINK_TAG + commandList[commandIndex]; } else { Debug.LogError("The 'hyperlink' command requires an hyperlink id parameter."); } } else if (command.IsEqual("-H") || command.IsEqual("-HYPERLINK")) { // Hyperlink off addCommandToLine("-H"); _nextSequence.hyperlinkId = ""; } else if (command.IsEqual("HA") || command.IsEqual("HALIGN")) { // Horizontal line alignment if (commandList.Length > commandIndex + 1) { commandIndex++; string alignment = commandList[commandIndex].ToUpper(); switch (alignment) { case "L": case "LEFT": alignment = "L"; _fLine.alignement = TextAlignment.Left; break; case "R": case "RIGHT": alignment = "R"; _fLine.alignement = TextAlignment.Right; break; case "C": case "CENTER": alignment = "C"; _fLine.alignement = TextAlignment.Center; break; default: alignment = ""; Debug.LogError("The 'HAlign' command requires an alignment parameter of L (left), R (right), or C (center)."); break; } if (alignment.Length != 0) { addCommandToLine("HA " + alignment); } } else { Debug.LogError("The 'HAlign' command requires an alignment parameter of L (left), R (right), or C (center)."); } } else if (command.IsEqual("S") || command.IsEqual("SPACE")) { // Space (pixels) if (commandList.Length > commandIndex + 1) { commandIndex++; int spaceSize; if (System.Int32.TryParse(commandList[commandIndex], out spaceSize)) { addCommandToLine("S " + commandList[commandIndex]); _nextSequence.Add(new AddSpace(spaceSize)); _lineLength += spaceSize; } else { Debug.LogError("The space size '" + commandList[commandIndex] + "' is not a valid integer"); } } else { Debug.LogError("The 'space' command requires a pixel count parameter."); } } else if (command.IsEqual("VA") || command.IsEqual("VALIGN")) { // Vertical alignment if (commandList.Length > commandIndex + 1) { commandIndex++; string alignment = commandList[commandIndex].ToUpper(); switch (alignment) { case "?": alignment = "?"; _nextSequence.alignBottom = false; break; case "B": case "BOTTOM": alignment = "B"; _nextSequence.alignBottom = true; break; default: alignment = ""; Debug.LogError("The 'VAlign' command requires an alignment parameter of ? (default) or B (bottom)."); break; } if (alignment.Length != 0) { addCommandToLine("VA " + alignment); } } else { Debug.LogError("The 'VAlign' command requires an alignment parameter of ? (default) or B (bottom)."); } } else { //Pass through any invalid commands or let words with brackets with out using double bracket //and decide what to do with it later invalidCommand = true; } } if (invalidCommand) { addCommandToLine(string.Format("{0}", text.Substring(currentLetterIndex + 1, endIndex - currentLetterIndex - 1))); //Debug.Log(string.Format("Invalid Command: {0}", commandList[commandIndex])); invalidCommand = false; } addSequenceToLine(); } else { // Add letter to the word word.Append(text[letterIndex]); } } addWordToLine(word.ToString()); addLineToLines(); }