public void Write(Mix mix, string filename) { if (mix == null) throw new ArgumentNullException("mix"); if (filename == null) throw new ArgumentNullException("filename"); File.WriteAllLines(filename, mix.Tracks.Select(t => t.File.FullName)); }
public EightTracksMixTrackStream(Mix startMix, IToastService toastService) { _startMix = startMix; _toastService = toastService; _currentMix = startMix; Description = _currentMix.Name; }
public Channel(string baseAddress) { _baseAddress = baseAddress; Config = new Config(_baseAddress); Preamp = new Preamp(_baseAddress); Gate = new Gate(_baseAddress); Dyn = new Dyn(_baseAddress); Eq = new Eq4(_baseAddress); Mix = new Mix(_baseAddress); Grp = new Grp(_baseAddress); Automix = new Automix(_baseAddress); }
public void Load() { if (Loaded) { return; } MusicHandle = Mix.LoadMUS(Filename); if (MusicHandle != IntPtr.Zero) { Loaded = true; } else { throw new FileLoadException(); } }
public IActionResult SaveMix() { int level = Convert.ToInt32(Request.Form["level"]); string name = Request.Form["text"]; bool add = (Request.Form["add"] == "on")?true:false; bool edit = (Request.Form["edit"] == "on") ? true : false; using (SQLContext DB = new SQLContext()) { Mix mix = new Mix() { MixName = name, Allowadd = add, Allowedit = edit, }; } return(RedirectToAction("EditMix", new { text = "ok" })); }
/// <summary> Проба получения новых данных заливки с контроллера, вызов с таймера </summary> /// <param name="secondsBegin">секунд продолжается заливка</param> /// <param name="error">ошибка чтения ПЛК</param> /// <param name="mix">данные заливки</param> /// <returns>Есть новые данные по заливке</returns> public bool TryNewMixTick(out int secondsBegin, out int error, out Mix mix) { var result = false; secondsBegin = 0; error = 0; mix = null; var r = _client.ConnectTo(_address, 0, 2); if (r == 0) { var run = _connector.NowMixRunning(out secondsBegin, out bool begin, out bool end); _connector.GetNewDataFromPLCToBuffetDbTick(); var count = _connector.UpdateBuffer(begin); if (begin) { _edgeFrontBegin = true; } if (_edgeFrontBegin && count <= 1) { _connector.SetNewMixFromBuffer(); _connector.ClearBuffer(); _edgeFrontBegin = false; } if (end) { mix = _connector.GetUpdatedMix(); if (mix != null) { result = true; } } if (_edgeFrontBegin) { Debug.WriteLine($"Начало заливки начато, число компонентов не в смесителе: {count}"); } } else { error = r; } _client.Disconnect(); return(result); }
public void Load() { if (Loaded) { return; } ChunkHandle = Mix.LoadWAV_RW(Resources.CreateRWFromFile(Filename, FileAssembly), 1); if (ChunkHandle != IntPtr.Zero) { Mix.VolumeChunk(ChunkHandle, (int)(128 * BaseVolume)); Loaded = true; } else { throw new FileLoadException(); } }
public void TestNicotineWeightCalculator() { //Testing the nicotine weight calculator with a known g/ml value // of 48mg nicotine base(in PG) https://www.liquidbarn.com/pages/calculating-the-specific-gravity-of-your-nicotine-solution //This should weigh 1.035g/ml Mix tempMix = new Mix(); TextBox tempBox = new TextBox(); tempBox.Text = "48"; //sets the NicotineGramsPerMl property tempMix.NicotineWeightCalculator(tempBox); double expectedValue = 1.035; expectedValue.CompareTo(tempMix.NicotineGramsPerMl); //Doesn't pass because we are comparing doubles that are very //close but not the same Assert.AreEqual(expectedValue, tempMix.NicotineGramsPerMl); }
private int[] getIndexesOfKEigenvalues(double[] d, int k) { Mix[] mixes = new Mix[d.Count()]; int i; for (i = 0; i < d.Count(); i++) { mixes[i] = new Mix(i, d[i]); } Array.Sort(mixes); int[] result = new int[k]; for (i = 0; i < k; i++) { result[i] = mixes[i].index; } return(result); }
public ActionResult Edit(Mix model) { RouteValueDictionary parameters = Request.QueryString.ToRouteValues(); if (model.Action == "Delete") { Mix entity = CarraraSQL.Mixes.Find(model.MixID); if (entity.Beds.Any() || entity.Pours.Any() || entity.RediMixOrders.Any()) { Page.Title = "The Mix Is In Use And Was NOT Deleted!"; Page.Message = "Set the Mix to Inactive if you do not intend to use this Mix again."; return(View("Manage", model)); } try { CarraraSQL.Mixes.Attach(model); CarraraSQL.Mixes.Remove(model); CarraraSQL.SaveChanges(); HttpContext.Cache.Remove("MixesSelectList"); TempData["Page.Title"] = "The Mix Was Deleted Successfully"; return(RedirectToAction("Index", parameters)); } catch (Exception ex) { Page.Title = "The Mix Was NOT Deleted! " + ex.Message; return(View("Manage", model)); } } if (ModelState.IsValid) { CarraraSQL.Entry(model).State = EntityState.Modified; CarraraSQL.SaveChanges(); HttpContext.Cache.Remove("MixesSelectList"); TempData["Page.Title"] = "The Mix Was Updated Successfully"; return(RedirectToAction("Index", parameters)); } Page.Title = "The Mix Was NOT Updated!"; Page.Message = "Please correct the following errors:"; return(View("Manage", model)); }
public Form1(Mix mix) : this() { _mix = mix; foreach (var item in mix.ActiveCourses) { _dataSource.Add(item); } RefreshResult(); panel1.Visible = false; panel2.Height = 195; colButton.Visible = false; colType.ReadOnly = true; colAmount.ReadOnly = true; colInterest.ReadOnly = true; colPeriod.ReadOnly = true; grdCourses.Enabled = false; colActive.Visible = false; }
private async void SaveRecipeClickAsync(object sender, RoutedEventArgs e) { if (mixMadeSuccesfully) { //Making a list of ingredients since we havent made a mix object TextBox[] flavouringNamesInput = GetFlavouringNameInputTextBoxes(); TextBox[] flavouringPercentagesInput = GetFlavouringPercentageInputTextBoxes(); Mix tempMix = MakeMixObjectFromInput(flavouringNamesInput, flavouringPercentagesInput); await Mix.SaveMix(userErrorInfo, desiredNicotineConcInput, nicotineBaseConcInput, volumeRequiredInput, tempMix.Ingredients, desiredPGPercentageInput, desiredVGPercentageInput); } else { userErrorInfo.Text = "To save a mix you must first calculate this successfully."; } }
public void PlayMusic(Mix mix, string name) { if (!Enabled) { return; } if (mix.FileExists(name)) { StopMusic(); var data = mix.GetBytes(name); var fCSex = new FMOD.CreateSoundExInfo() { Size = 216, Length = (uint)data.Length }; CheckError(system.CreateSound(data, FMOD.SoundMode.LoopNormal | FMOD.SoundMode.OpenMemory, ref fCSex, ref music)); system.PlaySound(music, false, ref musicChannel); musicChannel.SetVolume(0.5f); } }
public override void ApplyToDsp(Dsp effect, time_t qnDur, float alpha = 0) { base.ApplyToDsp(effect, qnDur, alpha); if (effect is BiQuadFilter filter) { switch (Type) { case EffectType.PeakingFilter: filter.SetPeaking(Q.Sample(alpha), Freq.Sample(alpha), Gain.Sample(alpha)); break; case EffectType.LowPassFilter: filter.SetLowPass(Q.Sample(alpha) * Mix.Sample(alpha) + 0.1f, Freq.Sample(alpha)); break; case EffectType.HighPassFilter: filter.SetHighPass(Q.Sample(alpha) * Mix.Sample(alpha) + 0.1f, Freq.Sample(alpha)); break; } } }
/// <summary> /// Start playlist and change UVC state /// </summary> private async Task StartPlayback(int InternalID = 0) { if (InternalID != 0) { CurrentMix = Playlist.Single(m => m.InternalID == InternalID); if (CurrentMix != null) { playbackStartedPreviously = true; await PlayCurrentMix(); return; } } // If playback was already started once we can just resume playing. if (!playbackStartedPreviously) { playbackStartedPreviously = true; // If the task was cancelled we would have saved the current track and its position. We will try playback from there. var currentTrackId = ApplicationSettingsHelper.ReadResetSettingsValue(ApplicationSettingsConstants.TrackId); if (currentTrackId != null) { CurrentMix = Playlist.Single(m => m.InternalID == (int)currentTrackId); if (CurrentMix == null) { CurrentMix = Playlist.FirstOrDefault(); } await PlayCurrentMix(); } } else { BackgroundMediaPlayer.Current.Play(); } }
private async void LoadRecipeClick(object sender, RoutedEventArgs e) { Windows.Storage.StorageFile file = await Mix.LoadMix(userErrorInfo); //Read the file and throw each line into an array. IList <String> mixInfoList = await Windows.Storage.FileIO.ReadLinesAsync(file); //go through the lines and input the data into the correct textboxes nicotineBaseConcInput.Text = mixInfoList[0]; desiredNicotineConcInput.Text = mixInfoList[1]; volumeRequiredInput.Text = mixInfoList[2]; desiredPGPercentageInput.Text = mixInfoList[3]; desiredVGPercentageInput.Text = mixInfoList[4]; //find out how many lines are in the list int numberOfFlavouringUsageEntries = mixInfoList.Count(); TextBox[] flavouringNamesInput = GetFlavouringNameInputTextBoxes(); TextBox[] flavouringPercentagesInput = GetFlavouringPercentageInputTextBoxes(); //Filling in the name text boxes int j = 0; for (int i = 5; i < mixInfoList.Count(); i += 2) { flavouringNamesInput[j].Text = mixInfoList[i]; j += 1; } //Filling in the percentage text boxes int k = 0; for (int i = 6; i < mixInfoList.Count(); i += 2) { flavouringPercentagesInput[k].Text = mixInfoList[i]; k += 1; } }
/// <summary> /// Start playing the music. /// volume and balance will set the Volume and Balance before the music starts. (For convenience.) /// </summary> public void Play(bool looping = false, float volume = 1f, float balance = 0f) { if (!Loaded) { throw new NotLoadedException(); } Paused = false; Mix.VolumeMusic((int)(128 * BaseVolume * volume)); if (looping) { Mix.PlayMusic(MusicHandle, -1); } else { Mix.PlayMusic(MusicHandle, 0); } Resources.CurrentlyPlayingMusic = this; }
public static void HandleInterrupt(Mix mix, Interrupt interrupt) { if (mix.Mode == ModuleBase.RunMode.Control) { if (interrupt.Type != Interrupt.Types.Forced) { throw new InvalidOperationException("Only Forced interrupts are allowed in Control mode"); } mix.ProgramCounter = mix.Registers.LoadFromMemory(mix.FullMemory, registerStorageAddressBase); mix.Mode = ModuleBase.RunMode.Normal; mix.SignalInterruptExecuted(); } else { mix.Mode = ModuleBase.RunMode.Control; mix.Registers.SaveToMemory(mix.FullMemory, registerStorageAddressBase, interrupt.Type == Interrupt.Types.Forced ? mix.ProgramCounter + 1 : mix.ProgramCounter); switch (interrupt.Type) { case Interrupt.Types.Forced: mix.ProgramCounter = forcedInterruptAddress; break; case Interrupt.Types.Timer: mix.ProgramCounter = timerInterruptAddress; break; case Interrupt.Types.Device: mix.ProgramCounter = deviceInterruptAddressBase - interrupt.DeviceID; break; } } }
public void SetUp() { fileSystemBrowserStub = new FileSystemBrowserStub(); downloadingMediaContent = Features.DownloadingMediaContent; testScheduler = new TestScheduler(); origSched = RxApp.DeferredScheduler; RxApp.DeferredScheduler = testScheduler; aMix = new Mix(new MixElement(), 0); lockObject = new ManualResetEvent(false); audioPlayer = new AudioPlayerStub(); requestExecutor = new RequestExecutorStub(); playbackController = new PlaybackController(audioPlayer, requestExecutor); mediaLibraryBrowser = new MediaLibraryBrowser(requestExecutor); userLoggedInSubject = new Subject <bool>(); mixViewModel = new MixViewModel(aMix, playbackController, mediaLibraryBrowser, userLoggedInSubject); mixViewModel.FileSystemBrowser = fileSystemBrowserStub; mixViewModel.WebAccessProxy = new WebAccessProxyStub(); lockObject.Reset(); }
//Метод расчета теплоемкости с подключением библиотеки TechDotNetLib public double CalculateCapacity() { double _capacityValue; try { mix = new Mix(PercDescription, PercArray); if (Temperature != null) { _capacityValue = mix.GetCapacity(Temperature.Val_R, Pressure?.Val_R + AtmoPressure * 0.0001f); } else { _capacityValue = -1; } } catch (Exception) { _capacityValue = -1; } ValCalc = (short)(_capacityValue + DeltaC * 0.1); return(_capacityValue); }
public void UpdateMix(Mix mix) { UpdateItem(mix); }
public void Reset() { _currentMix = _startMix; _playToken = null; _currentPlayResponse = null; }
public async Task TestMixIdPropertyIsRequiredForPlay() { Mix mix = new Mix(); await mix.Play(); }
/// <summary> /// This event is raised when a message is recieved from BackgroundAudioTask /// </summary> async void BackgroundMediaPlayer_MessageReceivedFromBackground(object sender, MediaPlayerDataReceivedEventArgs e) { TrackChangedMessage trackChangedMessage; if (MessageService.TryParseMessage(e.Data, out trackChangedMessage)) { // When foreground app is active change track based on background message await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // If playback stopped then clear the UI if (trackChangedMessage.InternalMixID == 0) { Stop(); RefreshBindings(); return; } CurrentTrack = TrackQueue.Single(s => s.InternalID == trackChangedMessage.InternalMixID); // Ensure track buttons are re-enabled since they are disabled when pressed foreach (Mix m in TrackQueue.Where(m => m.Playing)) { m.Playing = false; } CurrentTrack.Playing = true; NextButtonIsEnabled = true; PreviousButtonIsEnabled = true; RefreshBindings(); }); return; } BackgroundAudioTaskStartedMessage backgroundAudioTaskStartedMessage; if (MessageService.TryParseMessage(e.Data, out backgroundAudioTaskStartedMessage)) { // StartBackgroundAudioTask is waiting for this signal to know when the task is up and running // and ready to receive messages Debug.WriteLine("BackgroundAudioTask started"); return; } UpdateMediaPlayerInfoMessage updateMediaPlayerInfoMessage; if (MessageService.TryParseMessage(e.Data, out updateMediaPlayerInfoMessage)) { // StartBackgroundAudioTask is waiting for this signal to know when the task is up and running // and ready to receive messages // When foreground app is active change track based on background message await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { if (MainpageViewModel.instance.GetMixesTask != null && MainpageViewModel.instance.GetMixesTask.IsCompleted == false) { await MainpageViewModel.instance.GetMixesTask; } if (updateMediaPlayerInfoMessage.InternalMixID != 0) { if (TrackQueue == null) { TrackQueue = MainpageViewModel.instance.Mixes; } Mix PlayingTrack = CurrentTrack; CurrentTrack = TrackQueue.Where(s => s.InternalID == updateMediaPlayerInfoMessage.InternalMixID).FirstOrDefault(); if (CurrentTrack == null) { CurrentTrack = PlayingTrack; } // Ensure track buttons are re-enabled since they are disabled when pressed foreach (Mix m in TrackQueue.Where(m => m.Playing)) { if (m != CurrentTrack) { m.Playing = false; } } if (CurrentTrack != null) { CurrentTrack.Playing = true; NextButtonIsEnabled = true; PreviousButtonIsEnabled = true; RefreshBindings(); } } }); Debug.WriteLine("Updating MediaInfo"); return; } }
private void PlayCurrentTrack(Mix mix) { Track track = mix.GetCurrentTrack(); audioPlayerProxy.Open(track.Uri); }
public async Task <IActionResult> UpdateMix([FromBody] Mix mix) { return(Ok()); }
public async Task <IActionResult> CreateMix([FromBody] Mix mix) { return(Ok()); // Should be created. }
public bool MoveNext(CancellationToken token) { using (var session = new EightTracksSession(EightTracksModule.ApiKey)) { if (_playToken == null) { _playToken = session.Query<Play>().GetPlayToken(); } if (_currentPlayResponse == null) { _currentPlayResponse = session.Query<Play>().Execute(_playToken.PlayToken, _currentMix.ID); } else if (!_currentPlayResponse.Set.AtEnd) { _currentPlayResponse = session.Query<Play>().Next(_playToken.PlayToken, _currentMix.ID); } if (_currentPlayResponse.Errors != null) { var errorNodes = _currentPlayResponse.Errors as XmlNode[]; if (errorNodes != null && errorNodes.Any()) { var errorNode = errorNodes.FirstOrDefault(); if (errorNode != null && (errorNode.Name != "nil" && errorNode.Value != "true")) { var errorText = errorNode.InnerText; _toastService.Show(errorText); } } } if (MoveToNextSimilarMixAtEnd) { if (_currentPlayResponse.Set == null || _currentPlayResponse.Set.AtEnd) { if (_currentMix != null) { var nextMixResponse = session.Query<Mixes>().GetNextMix(_playToken.PlayToken, _currentMix.ID); _currentMix = nextMixResponse.NextMix; if (_currentMix != null) { Description = _currentMix.Name; _currentPlayResponse = session.Query<Play>().Execute(_playToken.PlayToken, _currentMix.ID); } } // TODO : Add user-notification and logging if there is any errors } } if (_currentPlayResponse.Set == null) { return false; } } return _currentPlayResponse != null && !_currentPlayResponse.Set.AtEnd; }
private void ExecutePlayMix(Mix mix) { Radio.Play(new EightTracksMixTrackStream(mix, ToastService)); }
// меняет 2 элемента местами IEnumerator SwapByPlayerRoutine(Chip a, Chip b, bool onlyForMatching, bool byAI = false) { System.Action breaker = () => { if (a && !a.destroying) { a.busy = false; } if (b && !b.destroying) { b.busy = false; } swaping = false; }; if (!isPlaying) { yield break; } if (!iteraction && !byAI) { yield break; } if (swaping) { yield break; } if (!a || !b) { yield break; } if (a.destroying || b.destroying) { yield break; } if (Chip.busyList.Count > 0) { yield break; } if (a.slot.block || b.slot.block) { yield break; } if (movesCount <= 0 || eat <= 0 || energy <= 0 || hygiene <= 0 || coffee <= 0) { yield break; } Mix mix = mixes.Find(x => x.Compare(a.chipType, b.chipType)); int move = 0; swaping = true; Vector3 posA = a.slot.transform.position; Vector3 posB = b.slot.transform.position; float progress = 0; Vector3 normal = a.slot.x == b.slot.x ? Vector3.right : Vector3.up; float time = 0; a.busy = true; b.busy = true; while (progress < ProjectParameters.main.swap_duration) { if (!a || !b) { breaker.Invoke(); yield break; } time = EasingFunctions.easeInOutQuad(progress / ProjectParameters.main.swap_duration); a.transform.position = Vector3.Lerp(posA, posB, time) + normal * Mathf.Sin(3.14f * time) * 0.2f; if (mix == null) { b.transform.position = Vector3.Lerp(posB, posA, time) - normal * Mathf.Sin(3.14f * time) * 0.2f; } progress += Time.deltaTime; yield return(0); } a.transform.position = posB; if (mix == null) { b.transform.position = posA; } a.movementID = main.GetMovementID(); b.movementID = main.GetMovementID(); if (mix != null) { swaping = false; a.busy = false; b.busy = false; MixChips(a, b); yield return(new WaitForSeconds(0.3f)); MovesFunction(1); swapEvent++; yield break; } Slot slotA = a.slot; Slot slotB = b.slot; if (!slotB || !slotB || !a || !b) { breaker.Invoke(); yield break; } slotB.chip = a; slotA.chip = b; move++; int count = 0; Solution solution; solution = MatchAnaliz(slotA); if (solution != null) { count += solution.count; } solution = MatchSquareAnaliz(slotA); if (solution != null) { count += solution.count; } solution = MatchAnaliz(slotB); if (solution != null) { count += solution.count; } solution = MatchSquareAnaliz(slotB); if (solution != null) { count += solution.count; } if (count == 0 && !onlyForMatching) { AudioAssistant.Shot("SwapFailed"); while (progress > 0) { if (!a || !b) { breaker.Invoke(); yield break; } time = EasingFunctions.easeInOutQuad(progress / ProjectParameters.main.swap_duration); a.transform.position = Vector3.Lerp(posA, posB, time) - normal * Mathf.Sin(3.14f * time) * 0.2f; b.transform.position = Vector3.Lerp(posB, posA, time) + normal * Mathf.Sin(3.14f * time) * 0.2f; progress -= Time.deltaTime; yield return(0); } a.transform.position = posA; b.transform.position = posB; a.movementID = GetMovementID(); b.movementID = GetMovementID(); slotB.chip = b; slotA.chip = a; move--; } else { AudioAssistant.Shot("SwapSuccess"); swapEvent++; } firstChipGeneration = false; if (!byAI) { Debug.Log("move = " + move); MovesFunction(move); } EventCounter(); a.busy = false; b.busy = false; swaping = false; }
public void SetUp() { _out = new ConstantSignal <double>(() => 0.0); if (_midiManager != null) { _plugin.MidiProcessor.NoteOff -= _midiManager.NoteOff; _plugin.MidiProcessor.NoteOn -= _midiManager.NoteOn; } _midiManager = new MidiManager(NoteChannels); _plugin.MidiProcessor.NoteOff += _midiManager.NoteOff; _plugin.MidiProcessor.NoteOn += _midiManager.NoteOn; _scratchBuffer1 = new double[this.BlockSize, 1]; _scratchBuffer2 = new double[this.BlockSize, 1]; _scratchBuffer3 = new double[this.BlockSize, 1]; _scratchBuffer4 = new double[this.BlockSize, 1]; _scratchBuffer5 = new double[this.BlockSize, 1]; _scratchBuffer6 = new double[this.BlockSize, 1]; _scratchBufferChannels1 = new double[this.BlockSize, NoteChannels]; _scratchBufferChannels2 = new double[this.BlockSize, NoteChannels]; _scratchBufferChannels3 = new double[this.BlockSize, NoteChannels]; _scratchBufferChannels4 = new double[this.BlockSize, NoteChannels]; _scratchBufferChannels5 = new double[this.BlockSize, NoteChannels]; _scratchBufferChannels6 = new double[this.BlockSize, NoteChannels]; _blockSize = BlockSize; _sampleRate = SampleRate; var sine1 = new Oscillator(NoteChannels, this.SampleRate) { Shape = Oscillator.WaveShape.Sine, Frequency = _midiManager.ChannelFrequencies, OctaveShift = new ConstantSignal <int>(() => _plugin.Model.Path1OctaveShift), Amplitude = new ConstantSignal <double>(() => _plugin.Model.Sine) }; sine1.Out.Buffer = _scratchBufferChannels1; var square1 = new Oscillator(NoteChannels, this.SampleRate) { Shape = Oscillator.WaveShape.Square, Frequency = _midiManager.ChannelFrequencies, OctaveShift = new ConstantSignal <int>(() => _plugin.Model.Path1OctaveShift), Amplitude = new ConstantSignal <double>(() => _plugin.Model.Square) }; square1.Out.Buffer = _scratchBufferChannels2; var triangle1 = new Oscillator(NoteChannels, this.SampleRate) { Shape = Oscillator.WaveShape.Triangle, Frequency = _midiManager.ChannelFrequencies, OctaveShift = new ConstantSignal <int>(() => _plugin.Model.Path1OctaveShift), Amplitude = new ConstantSignal <double>(() => _plugin.Model.Triangle) }; triangle1.Out.Buffer = _scratchBufferChannels3; var sine2 = new Oscillator(NoteChannels, this.SampleRate) { Shape = Oscillator.WaveShape.Sine, Frequency = _midiManager.ChannelFrequencies, OctaveShift = new ConstantSignal <int>(() => _plugin.Model.Path2OctaveShift), Amplitude = new ConstantSignal <double>(() => _plugin.Model.Sine) }; sine2.Out.Buffer = _scratchBufferChannels4; var square2 = new Oscillator(NoteChannels, this.SampleRate) { Shape = Oscillator.WaveShape.Square, Frequency = _midiManager.ChannelFrequencies, OctaveShift = new ConstantSignal <int>(() => _plugin.Model.Path2OctaveShift), Amplitude = new ConstantSignal <double>(() => _plugin.Model.Square) }; square2.Out.Buffer = _scratchBufferChannels5; var triangle2 = new Oscillator(NoteChannels, this.SampleRate) { Shape = Oscillator.WaveShape.Triangle, Frequency = _midiManager.ChannelFrequencies, OctaveShift = new ConstantSignal <int>(() => _plugin.Model.Path2OctaveShift), Amplitude = new ConstantSignal <double>(() => _plugin.Model.Triangle) }; triangle2.Out.Buffer = _scratchBufferChannels6; var sourceSum1 = new Sum("sourceSum"); sourceSum1.Inputs.Add(sine1.Out); sourceSum1.Inputs.Add(square1.Out); sourceSum1.Inputs.Add(triangle1.Out); sourceSum1.Buffer = _scratchBufferChannels1; var sourceSum2 = new Sum("sourceSum2"); sourceSum2.Inputs.Add(sine2.Out); sourceSum2.Inputs.Add(square2.Out); sourceSum2.Inputs.Add(triangle2.Out); sourceSum2.Buffer = _scratchBufferChannels4; var adsr1 = new Adsr(NoteChannels, this.SampleRate) { ReleaseDuration = new ConstantSignal <double>(() => _plugin.Model.ReleaseDuration / 5), AttackDuration = new ConstantSignal <double>(() => _plugin.Model.AttackDuration / 10), DecayDuration = new ConstantSignal <double>(() => _plugin.Model.DecayDuration / 10), Attack = new ConstantSignal <double>(() => _plugin.Model.AttackStrength), Sustain = new ConstantSignal <double>(() => _plugin.Model.SustainStrength), Triggers = _midiManager.ChannelTriggers, Input = sourceSum1 }; adsr1.Out.Buffer = _scratchBufferChannels1; var adsr2 = new Adsr(NoteChannels, this.SampleRate) { ReleaseDuration = new ConstantSignal <double>(() => _plugin.Model.ReleaseDuration / 5), AttackDuration = new ConstantSignal <double>(() => _plugin.Model.AttackDuration / 10), DecayDuration = new ConstantSignal <double>(() => _plugin.Model.DecayDuration / 10), Attack = new ConstantSignal <double>(() => _plugin.Model.AttackStrength), Sustain = new ConstantSignal <double>(() => _plugin.Model.SustainStrength), Triggers = _midiManager.ChannelTriggers, Input = sourceSum2 }; adsr2.Out.Buffer = _scratchBufferChannels4; var delayOsc = new Oscillator(1, SampleRate) { Shape = Oscillator.WaveShape.Triangle, Frequency = new ConstantSignal <double>(() => _plugin.Model.Delay1PlaybackSpeedFreq), Amplitude = new ConstantSignal <double>(() => Math.Pow(_plugin.Model.Delay1PlaybackSpeedMod, 3) / 2), Base = new ConstantSignal <double>(() => 1) }; delayOsc.Out.Buffer = _scratchBuffer1; var delay1 = new Delay() { DelayLength = new ConstantSignal <int>(() => _plugin.Model.Delay1Length), PlaybackSpeed = delayOsc.Out, Gain = new ConstantSignal <double>(() => _plugin.Model.Delay1Gain) }; delay1.Out.Buffer = _scratchBuffer2; var combine1 = new Mix("Combine"); combine1.Inputs.Add(delay1.Out); combine1.Inputs.Add(adsr1.Out.Flat((sum, cur) => sum + cur, 0d)); combine1.Strengths.Add(new ConstantSignal <double>(() => _plugin.Model.Wet1)); combine1.Strengths.Add(new ConstantSignal <double>(() => 1 - _plugin.Model.Wet1)); combine1.Buffer = _scratchBuffer3; var lowPass1 = new LowPass("lowpass1") { Scale = new ConstantSignal <int>(() => _plugin.Model.Filter1), Input = combine1 }; lowPass1.Buffer = _scratchBuffer4; delay1.Input = lowPass1; var combine2 = new Mix("Combine2"); combine2.Inputs.Add(delay1.Out); combine2.Inputs.Add(adsr2.Out.Flat((sum, cur) => sum + cur, 0d)); combine2.Strengths.Add(new ConstantSignal <double>(() => _plugin.Model.Gain1)); combine2.Strengths.Add(new ConstantSignal <double>(() => _plugin.Model.Gain2)); combine2.Buffer = _scratchBuffer6; var softClip = new ApplyFunction(sample => sample / (1 + Math.Abs(sample)), "SoftClip") { Buffer = _scratchBuffer6, Input = combine2 }; _out = softClip; }
/// <summary> /// Sets up a window and enters the gameloop. (Code after this call won't run until the game has exited.) /// </summary> public static void Run(float speed = 100f) { SDL.Init(SDL.InitFlags.EVERYTHING); IMG.Init(IMG.InitFlags.EVERYTHING); Mix.Init(Mix.InitFlags.EVERYTHING); TTF.Init(); //open window SDL.SetHint(SDL.HINT_RENDER_VSYNC, "1"); SDL.SetHint(SDL.HINT_RENDER_SCALE_QUALITY, "2"); WindowHandle = SDL.CreateWindow("HatlessEngine", SDL.WINDOWPOS_UNDEFINED, SDL.WINDOWPOS_UNDEFINED, 800, 600, SDL.WindowFlags.WINDOW_SHOWN | SDL.WindowFlags.WINDOW_RESIZABLE | SDL.WindowFlags.WINDOW_INPUT_FOCUS); RendererHandle = SDL.CreateRenderer(WindowHandle, -1, (uint)(SDL.RendererFlags.RENDERER_ACCELERATED | SDL.RendererFlags.RENDERER_PRESENTVSYNC)); SDL.SetRenderDrawBlendMode(RendererHandle, SDL.BlendMode.BLENDMODE_BLEND); Window.SetIcon(); //add default view that spans the current window new View("default", new Rectangle(Point.Zero, Window.Size), new Rectangle(Point.Zero, new Point(1f, 1f))); //initialize audio system and let Resources handle sound expiration Mix.OpenAudio(44100, SDL.AUDIO_S16SYS, 2, 4096); Mix.AllocateChannels((int)(speed * 2)); //might want to dynamically create and remove channels during runtime Mix.ChannelFinished(new Mix.ChannelFinishedDelegate(Resources.SoundChannelFinished)); Mix.HookMusicFinished(new Mix.MusicFinishedDelegate(Resources.MusicFinished)); //initialize loop StepsPerSecond = speed; Running = true; if (Started != null) { Started(null, EventArgs.Empty); } Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); //do a step before the first draw can occur Step(); long lastStepTick = 0; long lastDrawTick = 0; long lastStepTime = 0; long lastDrawTime = 0; while (Running) { //perform step when needed if (stopWatch.ElapsedTicks >= lastStepTick + TicksPerStep) { if (CatchUpSteps) { lastStepTick = lastStepTick + TicksPerStep; } else { lastStepTick = stopWatch.ElapsedTicks; } Step(); _ActualSPS = (int)(Stopwatch.Frequency / (stopWatch.ElapsedTicks - lastStepTime)); lastStepTime = stopWatch.ElapsedTicks; } //perform draw when ready for a new one if (!RenderframeReady && Running && stopWatch.ElapsedTicks >= lastDrawTick + TicksPerDraw) { lastDrawTick = lastDrawTick + TicksPerDraw; Draw(); _ActualFPS = (int)(Stopwatch.Frequency / (stopWatch.ElapsedTicks - lastDrawTime)); lastDrawTime = stopWatch.ElapsedTicks; } } //cleanup and uninitialization Resources.UnloadAllExternalResources(); Log.CloseAllStreams(); Input.CloseGamepads(); SDL.DestroyWindow(WindowHandle); WindowHandle = IntPtr.Zero; SDL.DestroyRenderer(RendererHandle); RendererHandle = IntPtr.Zero; Mix.CloseAudio(); SDL.Quit(); IMG.Quit(); Mix.Quit(); TTF.Quit(); }
/// <summary> /// Routes clicks on an MusicItem to the right place... /// </summary> /// <param name="item">The item.</param> /// <returns>A boolean indicating if we rooted the object successfully</returns> public bool RouteItemClick(object item) { Artist artist = item as Artist; if (artist != null) { string thumb = string.Empty; if (artist.Thumb200Uri != null) { thumb = HttpUtility.UrlEncode(artist.Thumb200Uri.ToString()); } this.RootFrame.Navigate(new Uri("/ArtistPage.xaml?" + App.IdParam + "=" + artist.Id + "&" + App.NameParam + "=" + HttpUtility.UrlEncode(artist.Name) + "&" + App.ThumbParam + "=" + thumb, UriKind.Relative)); return(true); } Product product = item as Product; if (product != null) { if (product.Category == Category.Track) { ShowProductTask task = new ShowProductTask() { ProductId = product.Id }; task.Show(); } else { string thumb = string.Empty; if (product.Thumb200Uri != null) { thumb = HttpUtility.UrlEncode(product.Thumb200Uri.ToString()); } this.RootFrame.Navigate(new Uri("/AlbumPage.xaml?" + App.IdParam + "=" + product.Id + "&" + App.NameParam + "=" + HttpUtility.UrlEncode(product.Name) + "&" + App.ThumbParam + "=" + thumb, UriKind.Relative)); } return(true); } Genre genre = item as Genre; if (genre != null) { this.RootFrame.Navigate(new Uri("/GenrePage.xaml?" + IdParam + "=" + genre.Id + "&" + App.NameParam + "=" + HttpUtility.UrlEncode(genre.Name), UriKind.Relative)); return(true); } MixGroup group = item as MixGroup; if (group != null) { this.RootFrame.Navigate(new Uri("/ShowListPage.xaml?" + ShowListPage.MethodParam + "=" + MethodCall.GetMixes + "&" + IdParam + "=" + group.Id + "&" + NameParam + "=" + HttpUtility.UrlEncode(group.Name), UriKind.Relative)); return(true); } Mix mix = item as Mix; if (mix != null) { PlayMixTask mixPlayer = new PlayMixTask() { MixId = mix.Id }; mixPlayer.Show(); return(true); } return(false); }
/// <summary> /// Routes clicks on an MusicItem to the right place... /// </summary> /// <param name="item">The item.</param> /// <returns>A boolean indicating if we rooted the object successfully</returns> public async Task <bool> RouteItemClick(object item) { Artist artist = item as Artist; if (artist != null) { string thumb = string.Empty; if (artist.Thumb200Uri != null) { thumb = HttpUtility.UrlEncode(artist.Thumb200Uri.ToString()); } string musicbrainzId = string.Empty; if (!string.IsNullOrEmpty(artist.MusicBrainzId)) { musicbrainzId = "&" + App.MbIdParam + "=" + artist.MusicBrainzId; } this.RootFrame.Navigate(new Uri( "/ArtistPage.xaml?" + App.IdParam + "=" + artist.Id + "&" + App.NameParam + "=" + HttpUtility.UrlEncode(artist.Name) + "&" + App.ThumbParam + "=" + thumb + musicbrainzId, UriKind.Relative)); return(true); } Product product = item as Product; if (product != null) { if (product.Category == Category.Track) { ShowProductTask task = new ShowProductTask() { ClientId = ApiKeys.ClientId, ProductId = product.Id }; await task.Show(); } else { string thumb = string.Empty; if (product.Thumb200Uri != null) { thumb = HttpUtility.UrlEncode(product.Thumb200Uri.ToString()); } this.RootFrame.Navigate(new Uri("/AlbumPage.xaml?" + App.IdParam + "=" + product.Id + "&" + App.NameParam + "=" + HttpUtility.UrlEncode(product.Name) + "&" + App.ThumbParam + "=" + thumb, UriKind.Relative)); } return(true); } Genre genre = item as Genre; if (genre != null) { this.RootFrame.Navigate(new Uri("/GenrePage.xaml?" + IdParam + "=" + genre.Id + "&" + App.NameParam + "=" + HttpUtility.UrlEncode(genre.Name), UriKind.Relative)); return(true); } MixGroup group = item as MixGroup; if (group != null) { this.RootFrame.Navigate(new Uri("/ShowListPage.xaml?" + ShowListPage.MethodParam + "=" + MethodCall.GetMixes + "&" + IdParam + "=" + group.Id + "&" + NameParam + "=" + HttpUtility.UrlEncode(group.Name), UriKind.Relative)); return(true); } Mix mix = item as Mix; if (mix != null) { await mix.Play(); return(true); } return(false); }
private void CalculateButton_Click(object sender, RoutedEventArgs e) { //Most of the inards of this method should be delegated to other methods if we want to return a Mix object. Mix tempMix = new Mix(); //make sure the mix has at least one flavouring percentage and the neccasary information to calculate it if (String.IsNullOrWhiteSpace(flavouring1PercentageInput.Text) || String.IsNullOrWhiteSpace(nicotineBaseConcInput.Text) || String.IsNullOrWhiteSpace(desiredNicotineConcInput.Text) || String.IsNullOrWhiteSpace(volumeRequiredInput.Text) || String.IsNullOrWhiteSpace(desiredPGPercentageInput.Text) || String.IsNullOrWhiteSpace(desiredVGPercentageInput.Text)) { userErrorInfo.Text = "You are missing key information to calculate this mix."; } else { //make sure the mix makes mathematical sense try { //make sure pg vg ratio adds up to 100 put this in if statement Mix.PGVGValidator(desiredPGPercentageInput, desiredVGPercentageInput); TextBox[] flavouringNamesInput = GetFlavouringNameInputTextBoxes(); TextBlock[] flavouringNamesOutput = GetFlavouringNamesOutput(); int i = 0; foreach (TextBox flavouringName in flavouringNamesInput) { if (String.IsNullOrWhiteSpace(flavouringName.Text)) { i += 1; continue; } else { flavouringNamesOutput[i].Text = Convert.ToString(flavouringName.Text); i += 1; } } tempMix.NicotineWeightCalculator(nicotineBaseConcInput); TextBox[] flavouringPercentagesInput = GetFlavouringPercentageInputTextBoxes(); tempMix.CalculateMixInVolume(desiredNicotineConcInput, volumeRequiredInput, nicotineBaseConcInput, desiredVGPercentageInput, desiredPGPercentageInput, flavouringPercentagesInput); TextBlock[] flavouringVolumeOutput = GetFlavouringVolumeOutput(); tempMix.DisplayMixResultsVolume(nicotineBaseVolumeOutput, pgBaseVolumeOutput, vgVolumeOutput, flavouringVolumeOutput); TextBlock[] flavouringWeightOutput = GetFlavouringWeightOutput(); tempMix.DisplayMixResultsWeight(nicotineBaseGramsOutput, pgGramsOutput, vgGramsOutput, flavouringWeightOutput); TextBlock[] flavouringPercentageOutput = GetFlavouringPercentageOutput(); tempMix.DisplayMixResultsPercentage(nicotineBasePercentageOutput, vgPercentageOutput, pgPercentageOutput, flavouringPercentagesInput, flavouringPercentageOutput); //Displaying totals. Could do this with a generic? List <TextBlock> percentageOutputList = new List <TextBlock>(); percentageOutputList.AddRange(flavouringPercentageOutput); percentageOutputList.Add(nicotineBasePercentageOutput); percentageOutputList.Add(pgPercentageOutput); percentageOutputList.Add(vgPercentageOutput); List <TextBlock> volumeOutputList = new List <TextBlock>(); volumeOutputList.AddRange(flavouringVolumeOutput); volumeOutputList.Add(nicotineBaseVolumeOutput); volumeOutputList.Add(vgVolumeOutput); volumeOutputList.Add(pgBaseVolumeOutput); List <TextBlock> weightOutputList = new List <TextBlock>(); weightOutputList.AddRange(flavouringWeightOutput); weightOutputList.Add(nicotineBaseGramsOutput); weightOutputList.Add(vgGramsOutput); weightOutputList.Add(pgGramsOutput); tempMix.DisplayTotals(volumeOutputList, weightOutputList, percentageOutputList, flavouringPercentagesInput, totalVolumeOutput, totalGramsOutput, totalPercentageOutput, totalFlavourPercentageOutput); mixMadeSuccesfully = true; } catch (Exception ex) { userErrorInfo.Text = Convert.ToString(ex.Message); } } }