예제 #1
0
 private void btnReiniciar_Click(object sender, EventArgs e)
 {
     controladora.ResetGame();
     score = 0;
     if (pausado)
     {
         pausado          = false;
         tmrPaint.Enabled = true;
         btnComenzar.Text = "Pausar";
         AudioPlayback.StopAllSounds();
     }
 }
예제 #2
0
 private void btnRestart_Click(object sender, EventArgs e)
 {
     con.ResetGame();
     score = 0;
     if (stop)
     {
         stop             = false;
         tmrPaint.Enabled = true;
         btnStart.Text    = "Pause";
         AudioPlayback.StopAllSounds();
     }
 }
예제 #3
0
 public void UpdateSongPosition(float seconds)
 {
     if (EnableSong && !Track.Paused && Track.Animating &&
         !((HorizontalIntSlider)Canvas.FindChildByName("timeslider")).Held)
     {
         AudioPlayback.Resume(CurrentSong.Offset + seconds, (Scheduler.UpdatesPerSecond / 40f));
     }
     else
     {
         AudioPlayback.Pause();
     }
 }
예제 #4
0
 void Awake()
 {
     // Check if instance already exists
     if (instance == null)
     {
         // if not, set instance to this
         instance = this;
     }
     // If instance already exists (not null) and it is not this
     else if (instance != this)
     {
         // Then destroy this gameobject. This enforces our singleton pattern, meaning there can only ever be one instance of this manager
         Destroy(this.gameObject);
     }
 }
예제 #5
0
        public void Stop()
        {
            if (Animating)
            {
                Animating = false;
                Paused    = false;

                Zoom = _oldZoom;
                Camera.SetPosition(_oldPos);
                _track.RiderState.Reset(_track.Start, _track);
                Camera.ViewPosition             = _oldPos;
                Camera.AimPosition              = Camera.ViewPosition;
                game.Scheduler.UpdatesPerSecond = 40;
                foreach (var v in ActiveTriggers)
                {
                    v.Reset();
                }
                ActiveTriggers.Clear();
                if (game.EnableSong)
                {
                    AudioPlayback.Stop();
                }
                var canvas  = game.Canvas;
                var buttons = canvas.FindChildByName("buttons");
                buttons.FindChildByName("pause").IsHidden = true;
                buttons.FindChildByName("start").IsHidden = false;
                var slider = canvas.FindChildByName("timeslider");
                slider.IsHidden = true;
                game.Canvas.FindChildByName("labeliterations").IsHidden = true;
                game.Canvas.FindChildByName("vslider", true).IsHidden   = false;
                canvas.FindChildByName("btnfastforward").IsHidden       = true;
                canvas.FindChildByName("btnslowmo").IsHidden            = true;

                //incase recording mode was enabled at the start. There's a risk it was disabled during playback
                //if that's the case checking game.RecordingMode would fail but controls would remain invisible.
                //instead, we just by default ensure visibility
                {
                    buttons.IsHidden = false;
                    game.Canvas.FindChildByName("fps", true).IsHidden           = false;
                    game.Canvas.FindChildByName("ppf", true).IsHidden           = false;
                    game.Canvas.FindChildByName("labelplayback", true).IsHidden = false;
                    game.Canvas.FindChildByName("trackname", true).IsHidden     = false;
                }
                game.Invalidate();
            }
        }
예제 #6
0
        public MainForm()
        {
            InitializeComponent();
            //identificador del lugar en donde voy a dibujar
            hdc = (uint)this.Handle;
            //toma el error que sucedio
            string error = "";

            //Comando de inicializacion de la ventana grafica
            OpenGLControl.OpenGLInit(ref hdc, this.Width, this.Height, ref error);

            if (error != "")
            {
                MessageBox.Show("Ocurrio un error al inicializar OpenGl");
            }

            //Habilita las luces
            Lighting.SetupLighting();
            ContentManager.SetTextureList("texturas_low\\"); //especifico la ubicacion de las texturas
            ContentManager.LoadTextures();                   //las cargo
            ContentManager.SetModelList("modelo\\");         // especifico la ubicacion de la oficina
            ContentManager.LoadModels();                     // la cargo
            AudioPlayback.SoundDir = "sonidos\\";
            AudioPlayback.LoadSounds();

            //Color de fondo
            Gl.glClearColor(0.3f, 0.6f, 1, 1);//red green blue alpha

            controladora.Create();
            //controladora.Camara.EstablecerPerspectiva();
            controladora.Camara.SetCamara(1);

            //formularios
            PracticaForm.Instancia      = new PracticaForm();
            AcercaDeForm.Instancia      = new AcercaDeForm();
            DatosPracticaForm.Instancia = new DatosPracticaForm();

            Ayuda.Instancia = new Ayuda();

            instancia = this;

            this.MouseWheel += new MouseEventHandler(MainForm_MouseWheel);
            this.MouseMove  += new MouseEventHandler(MainForm_MouseWheel);
        }
예제 #7
0
 // Token: 0x0600006C RID: 108 RVA: 0x0000C560 File Offset: 0x0000A760
 protected override void OnActivated(object sender, EventArgs args)
 {
     if (StageSystem.stageMode == 2)
     {
         if (GlobalAppDefinitions.gameMode == 7)
         {
             GlobalAppDefinitions.gameMode    = 1;
             GlobalAppDefinitions.gameMessage = 4;
         }
     }
     else
     {
         if (GlobalAppDefinitions.gameMode == 7)
         {
             GlobalAppDefinitions.gameMode = 1;
         }
         GlobalAppDefinitions.gameMessage = 2;
         AudioPlayback.ResumeSound();
     }
     base.OnActivated(sender, args);
 }
예제 #8
0
        // Token: 0x06000070 RID: 112 RVA: 0x0000C6F0 File Offset: 0x0000A8F0
        protected override void Update(GameTime gameTime)
        {
            int num = 0;

            InputSystem.CheckKeyboardInput();
            TouchCollection state = TouchPanel.GetState();

            InputSystem.ClearTouchData();
            foreach (TouchLocation touchLocation in state)
            {
                switch (touchLocation.State)
                {
                case TouchLocationState.Pressed:
                    InputSystem.AddTouch(touchLocation.Position.X, touchLocation.Position.Y, num);
                    break;

                case TouchLocationState.Moved:
                    InputSystem.AddTouch(touchLocation.Position.X, touchLocation.Position.Y, num);
                    break;
                }
                num++;
            }
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            {
                if (FileIO.activeStageList == 0)
                {
                    switch (StageSystem.stageListPosition)
                    {
                    case 4:
                    case 5:
                        InputSystem.touchData.start = 1;
                        break;

                    default:
                        InputSystem.touchData.buttonB = 1;
                        break;
                    }
                }
                else if (StageSystem.stageMode == 2)
                {
                    if (ObjectSystem.objectEntityList[9].state == 3 && GlobalAppDefinitions.gameMode == 1)
                    {
                        ObjectSystem.objectEntityList[9].state    = 4;
                        ObjectSystem.objectEntityList[9].value[0] = 0;
                        ObjectSystem.objectEntityList[9].value[1] = 0;
                        ObjectSystem.objectEntityList[9].alpha    = 248;
                        AudioPlayback.PlaySfx(27, 0);
                    }
                }
                else
                {
                    GlobalAppDefinitions.gameMessage = 2;
                }
            }
            if (StageSystem.stageMode != 2)
            {
                EngineCallbacks.ProcessMainLoop();
            }
            try
            {
                base.Update(gameTime);
            }
            catch (GameUpdateRequiredException e)
            {
                this.HandleGameUpdateRequired(e);
            }
        }
예제 #9
0
 internal static void LoadVideo(string path)
 {
     Source = new DataSource(path);
     Video  = Source.VideoPlayback;
     Audio  = Source.AudioPlayback;
 }
예제 #10
0
파일: Lathe.cs 프로젝트: yagoanjos/3d-lathe
        public void MoverBase(Movement movement)
        {
            if (encendido == false)
            {
                return;
            }
            if (Main.Instancia.PracticaIniciada == false)
            {
                return;
            }
            Vector3 posC1 = new Vector3(cuchillaPos1);
            Vector3 posC2 = new Vector3(cuchillaPos2);

            Vector3 posTorno = new Vector3(baseTornoPos);

            switch (movement)
            {
            case Movement.Backward:
                posC1.Z    += speed;
                posC2.Z    += speed;
                posTorno.Z += speed;
                break;

            case Movement.Forward:
                posC1.Z    -= speed;
                posC2.Z    -= speed;
                posTorno.Z -= speed;
                break;

            case Movement.Left:
                posC1.X    -= speed;
                posC2.X    -= speed;
                posTorno.X -= speed;
                break;

            case Movement.Right:
                posC1.X    += speed;
                posC2.X    += speed;
                posTorno.X += speed;
                break;
            }
            if (Main.Instancia.Escena.Pieza.ChequearCollision(posC1) ||
                Main.Instancia.Escena.Pieza.ChequearCollision(posC2))
            {
                speed = Main.Instancia.Escena.Pieza.Material.Resistencia / 350;
                AudioPlayback.Play("rebajado.mp3");
                Vector3 v = new Vector3(cuchillaPos1);
                v.Scale(scale);
                Main.Instancia.Escena.AddGenerator(new ChispaGenerator(v));
            }
            else
            {
                counterSpeed++;
                if (counterSpeed == 22)
                {
                    counterSpeed = 0;
                    speed        = speedBase;
                }

                //if (movement == Movement.Left || movement == Movement.Right)
                //{
                //    Controladora.Instancia.CleanGenerator();
                //}
            }
            if (movement == Movement.Left || movement == Movement.Right)
            {
                Main.Instancia.Escena.ClearGenerator();
            }
            if (movement == Movement.Backward)
            {
                Main.Instancia.Escena.CleanGenerator();
                AudioPlayback.StopSound("rebajado.mp3");
            }

            if (posTorno.Z < 2.37f && posTorno.Z > 0.06f && // aki se dan los topes
                (movement == Movement.Forward || movement == Movement.Backward))
            {
                baseTornoPos.Z = posTorno.Z;
                cuchillaPos1.Z = posC1.Z;
                cuchillaPos2.Z = posC2.Z;
            }
            if (posTorno.X > -5.84 && posTorno.X < 3.25f &&
                (movement == Movement.Left || movement == Movement.Right))
            {
                baseTornoPos.X = posTorno.X;
                cuchillaPos1.X = posC1.X;
                cuchillaPos2.X = posC2.X;
            }


            if (posC1.Y < 0.1f)// para que no parta la pieza
            {
                return;
            }

            Main.Instancia.Escena.Pieza.RebajarPieza(cuchillaPos1);
            Main.Instancia.Escena.Pieza.RebajarPieza(cuchillaPos2);
        }
예제 #11
0
 public void Dispose()
 {
     Player?.Dispose();
     Player = null;
 }
예제 #12
0
        static void Main(string[] args)
        {
            RenderWindow window = new RenderWindow(new VideoMode(640, 480), "MotionNET Playback Example");

            window.SetVerticalSyncEnabled(true);

            // Create some buttons to control the playback
            VertexArray playbutton = new VertexArray(PrimitiveType.Triangles, 3);

            playbutton[0] = new Vertex(new Vector2f(255, 350), Color.Green);
            playbutton[1] = new Vertex(new Vector2f(275, 360), Color.Green);
            playbutton[2] = new Vertex(new Vector2f(255, 370), Color.Green);
            VertexArray pausebutton = new VertexArray(PrimitiveType.Quads, 8);

            pausebutton[0] = new Vertex(new Vector2f(305, 350), Color.Blue);
            pausebutton[1] = new Vertex(new Vector2f(310, 350), Color.Blue);
            pausebutton[2] = new Vertex(new Vector2f(310, 370), Color.Blue);
            pausebutton[3] = new Vertex(new Vector2f(305, 370), Color.Blue);
            pausebutton[4] = new Vertex(new Vector2f(320, 350), Color.Blue);
            pausebutton[5] = new Vertex(new Vector2f(325, 350), Color.Blue);
            pausebutton[6] = new Vertex(new Vector2f(325, 370), Color.Blue);
            pausebutton[7] = new Vertex(new Vector2f(320, 370), Color.Blue);
            VertexArray stopbutton = new VertexArray(PrimitiveType.Quads, 4);

            stopbutton[0] = new Vertex(new Vector2f(355, 350), Color.Red);
            stopbutton[1] = new Vertex(new Vector2f(375, 350), Color.Red);
            stopbutton[2] = new Vertex(new Vector2f(375, 370), Color.Red);
            stopbutton[3] = new Vertex(new Vector2f(355, 370), Color.Red);

            DataSource datasource = new DataSource();          // create the data source from which playback will happen

            if (!datasource.LoadFromFile("{video file path}")) // load a file into the data source
            {
                return;
            }

            AudioPlayback audioplayback = new AudioPlayback(datasource); // create an audio playback from our data source
            VideoPlayback videoplayback = new VideoPlayback(datasource); // create a video playback from our data source

            // scale video to fit the window
            videoplayback.Scale = new Vector2f(640f / (float)datasource.VideoSize.X, 480f / (float)datasource.VideoSize.Y);

            // standard SFML.NET game loop and event handling
            window.Closed             += (sender, e) => { window.Close(); };
            window.MouseButtonPressed += (sender, e) =>
            {
                Vector2f mousepos = window.MapPixelToCoords(new Vector2i(e.X, e.Y));
                if (playbutton.Bounds.Contains(mousepos.X, mousepos.Y))
                {
                    datasource.Play();
                }
                else if (pausebutton.Bounds.Contains(mousepos.X, mousepos.Y))
                {
                    datasource.Pause();
                }
                else if (stopbutton.Bounds.Contains(mousepos.X, mousepos.Y))
                {
                    datasource.Stop();
                }
            };
            while (window.IsOpen)
            {
                window.DispatchEvents();

                datasource.Update(); // update the data source - this is required for any playbacks

                window.Clear();
                window.Draw(videoplayback); // draw the video playback
                // draw the buttons
                window.Draw(playbutton);
                window.Draw(pausebutton);
                window.Draw(stopbutton);
                window.Display();
            }
        }
예제 #13
0
        public void ShowSongWindow()
        {
            if (GetOpenWindows().Count != 0)
            {
                return;
            }
            game.Track.Stop();
            var wc = new WindowControl(this, "Song Sync", false)
            {
                DeleteOnClose = true
            };

            wc.MakeModal(true);

            wc.MinimumSize = new System.Drawing.Point(220, 240);

            wc.Width  = 220;
            wc.Height = 240;
            wc.SetPosition((int)(Width / 2) - (wc.Width / 2), (int)(Height / 2) - (wc.Height / 2));
            //wc.DisableResizing();
            var enablesongcb = new LabeledCheckBox(wc);

            enablesongcb.CheckChanged += (o, e) => { game.EnableSong = enablesongcb.IsChecked; };
            enablesongcb.IsChecked     = game.EnableSong;
            enablesongcb.Text          = "Enable Song";
            enablesongcb.Dock          = Pos.Top;
            var gb = new GroupBox(wc);

            gb.Text = "Song Selection";
            gb.Dock = Pos.Fill;
            var Songs = new TreeControl(gb);

            Songs.Height = 100;
            Songs.Margin = new Margin()
            {
                Bottom = 10
            };
            Songs.Dock = Pos.Fill;
            Songs.Name = "songtv";

            var filedir = Program.CurrentDirectory + "Songs";

            if (Directory.Exists(filedir))
            {
                var      songfiles          = Directory.GetFiles(filedir, "*.*");
                var      supportedfiles     = new List <string>();
                string[] supportedfiletypes = new string[]
                {
                    ".mp3", ".wav", ".wave", ".ogg", ".wma", ".m4a", ".aac"
                };

                foreach (var file in songfiles)
                {
                    var lower = file.ToLower(Program.Culture);
                    foreach (var type in supportedfiletypes)
                    {
                        if (lower.EndsWith(type, StringComparison.OrdinalIgnoreCase))
                        {
                            supportedfiles.Add(file);
                            break;
                        }
                    }
                }

                foreach (var sf in supportedfiles)
                {
                    var name     = Path.GetFileName(sf);
                    var nodename = name.ToLower().Contains(".ogg") ? name : "[convert] " + name;
                    var node     = Songs.AddNode(nodename);
                    node.UserData = name;
                    if (name == game.CurrentSong?.Location)
                    {
                        node.IsSelected = true;
                    }
                }
            }
            Songs.SelectionChanged += (snd, ev) =>
            {
                var tc   = (TreeControl)wc.FindChildByName("songtv", true);
                var list = (List <TreeNode>)tc.SelectedChildren;
                if (list.Count == 1)
                {
                    game.CurrentSong.Location = (string)list[0].UserData;
                }
            };
            wc.IsHiddenChanged += (o, e) =>
            {
                if (!wc.IsHidden)
                {
                    return;
                }
                if (game.EnableSong)
                {
                    var fn = Program.CurrentDirectory + "Songs" +
                             Path.DirectorySeparatorChar +
                             game.CurrentSong.Location;
                    if (File.Exists(fn))
                    {
                        game.Loading = true;
                        AudioPlayback.LoadFile(ref fn);
                        game.Loading = false;
                    }
                }
                try
                {
                    var svolume =
                        (HorizontalSlider)wc.FindChildByName("volume", true);
                    Settings.Default.Volume = svolume.Value;
                    Settings.Default.Save();
                }
                catch
                {
                    // ignored
                }
            };
            var container = new ControlBase(gb);

            container.Dock   = Pos.Bottom;
            container.Height = 20;
            var offset = new NumericUpDown(container);

            offset.ValueChanged += (snd, ev) => { game.CurrentSong.Offset = offset.Value; };
            offset.Min           = 0;
            offset.Max           = 10000;
            offset.Value         = game.CurrentSong.Offset;
            offset.Dock          = Pos.Right;
            var label = new Label(container);

            label.Dock = Pos.Left;
            label.Text = "Offset (secs)";
            gb.Height  = 150;
            var container2 = new ControlBase(wc);

            container2.Dock   = Pos.Bottom;
            container2.Height = 40;
            label             = new Label(container2);
            label.Margin      = new Margin()
            {
                Top = 13
            };
            label.Dock = Pos.Left;
            label.Text = "Volume:";
            var volume = new HorizontalSlider(container2);

            volume.Min = 0;
            volume.Max = 100;
            if (Settings.Default.Volume > 100)
            {
                Settings.Default.Volume = 100;
            }
            if (Settings.Default.Volume < 0)
            {
                Settings.Default.Volume = 0;
            }
            volume.Value                = Settings.Default.Volume;
            volume.Name                 = "volume";
            volume.SnapToNotches        = false;
            volume.KeyboardInputEnabled = false;
            volume.Width                = 150;
            volume.Dock                 = Pos.Right;
            wc.Show();
            game.Cursor = MouseCursor.Default;
        }
예제 #14
0
        protected override void LoadContent()
        {
            this.spriteBatch = new SpriteBatch(GraphicsDevice);
            this.font        = Content.Load <SpriteFont>("Content/Consolas");

            this.basicEffect = new BasicEffect(GraphicsDevice);
            this.basicEffect.VertexColorEnabled = true;
            this.basicEffect.World = Matrix.Identity;

            this.input = new Input();

            /// Color Palettes

            var inputColorPalettesJson = System.IO.File.ReadAllText("Content/ColorPalettes.json"); // TODO: Make safe
            var inputColorPalettes     = JsonConvert.DeserializeObject <IList <ColorPalette> >(inputColorPalettesJson, new Json.PaletteConverter());

            nextColorPalette = 0;
            colorPalettes    = new List <ColorPalette>(inputColorPalettes);

            if (colorPalettes.Count == 0)
            {
                colorPalettes.Add(new ColorPalette("coup de grâce", "99B898", "FECEA8", "FF847C", "E84A5F", "2A363B"));
            }

            /// Visualizations

            nextVisualization = 0;
            visualizations    = new List <Visualization>();
            visualizations.AddRange(
                from type in Assembly.GetExecutingAssembly().GetTypes().OrderBy(x => x.Name)
                where type.IsSubclassOf(typeof(Visualization)) && type.GetCustomAttribute <ObsoleteAttribute>() == null
                select(Visualization) Activator.CreateInstance(type));

            // Experimental Visualizations
            //visualizations = new List<Visualization>(
            //    new Visualization[]
            //    {
            //        new TestShape(),
            //        new CircleSnakesVisualization(),
            //        new ThicklinesVisualization(),
            //        new WavesVisualization()
            //    });

            NextVisualization();

            /// Audio

            this.audioPlayback = new AudioPlayback(this);
            this.audioAnalyzer = new AudioAnalyzer(audioPlayback);

#if DEBUG
            var songPath = @"F:\Music\ODESZA - Sun Models (feat. Madelyn Grant).mp3";
#else
            var openFileDialog = new System.Windows.Forms.OpenFileDialog();
            openFileDialog.Filter = "All Supported Files (*.wav;*.mp3)|*.wav;*.mp3|All Files (*.*)|*.*";

            var result = openFileDialog.ShowDialog();
            if (result != System.Windows.Forms.DialogResult.OK)
            {
                Exit();
            }

            var songPath = openFileDialog.FileName;
#endif

            this.audioPlayback.Load(songPath);
            this.audioPlayback.Play();

            gameConsole.WriteLine($"-- Playing {Path.GetFileNameWithoutExtension(songPath)}", Color.White, TimeSpan.FromSeconds(10));
        }
        public MainViewModel()
        {
            if (IsInDesignMode)
            {
                // Code runs in Blend --> create design time data.
                Title      = _title;
                NeteaseUrl = "http://music.163.com/#/my/m/music/playlist?id=6435531";
                SongCollection.Add(new Song()
                {
                    Title   = new Title("Clover Heart's"),
                    Artists = new Artists(new string[] { "榊原ゆい", "榊原ゆい" }),
                    Album   = new Album("Boommmmm", "http://p4.music.126.net/n189nEFRefNaucKD8akNQw==/7886796906449604.jpg"),
                });
                SongCollection.Add(new Song()
                {
                    Title   = new Title("Clover Heart's"),
                    Artists = new Artists(new string[] { "榊原ゆい" }),
                    Album   = new Album("Boommmmm", "http://p4.music.126.net/n189nEFRefNaucKD8akNQw==/7886796906449604.jpg"),
                });
                SongCollection.Add(new Song()
                {
                    Title   = new Title("Clover Heart's"),
                    Artists = new Artists(new string[] { "榊原ゆい" }),
                    Album   = new Album("Boommmmm", "http://p4.music.126.net/n189nEFRefNaucKD8akNQw==/7886796906449604.jpg"),
                });
                SelectedSong = SongCollection.First();
            }
            else
            {
                // Code runs "for real"
                Title                      = _title;
                NeteaseUrl                 = "http://music.163.com/playlist?id=6435531";
                Progress                   = 0;
                audioPlayback              = new AudioPlayback();
                audioPlayback.Volume       = Volume;
                audioPlayback.EndCallback += (handle, channel, data, user) =>
                {
                    int index = -1;
                    if ((index = SongCollection.IndexOf(CurrentPlaySong)) != -1)
                    {
                        ListenCommand.Execute(SongCollection.ElementAt((index + 1) % SongCollection.Count));
                    }
                    else
                    {
                        audioPlayback.Stop();
                        NowPlaying = "";
                        CurrentPlaySong.PlayProgress = 0;
                        CurrentPlaySong.PlayStatus   = PlayStatus.Play;
                        timer.Enabled = false;
                        timer.Stop();
                    }
                };

                timer.Tick += (sender, args) =>
                {
                    Title = string.Format("{0}/{1} - {2}", audioPlayback.CurrentLength, audioPlayback.TotalLength, _title);
                    RaisePropertyChanged("Title");
                    CurrentPlaySong.PlayProgress = audioPlayback.Progress;
                };

                GetSongsCommand = new RelayCommand(async() =>
                {
                    if (string.IsNullOrWhiteSpace(NeteaseUrl))
                    {
                        return;
                    }
                    var id      = "";
                    var urlType = "";
                    var reg     = new Regex(@".*/(.*?)\?id=(\d*)").Match(NeteaseUrl);
                    if (reg.Success)
                    {
                        urlType = reg.Groups[1].Value;
                        id      = reg.Groups[2].Value;
                        SongCollection.Clear();
                        switch (urlType)
                        {
                        case "album":
                            foreach (var song in await NeteaseUtil.GetSongsFromAlbum(id))
                            {
                                SongCollection.Add(song);
                                RaisePropertyChanged("TotalCount");
                            }
                            break;

                        case "artist":
                            foreach (var song in await NeteaseUtil.GetSongsFromArtist(id))
                            {
                                SongCollection.Add(song);
                                RaisePropertyChanged("TotalCount");
                            }
                            break;

                        case "playlist":
                            foreach (var song in await NeteaseUtil.GetSongsFromPlaylist(id))
                            {
                                SongCollection.Add(song);
                                RaisePropertyChanged("TotalCount");
                            }
                            break;

                        case "song":
                            foreach (var song in await NeteaseUtil.GetSongDetail(id))
                            {
                                SongCollection.Add(song);
                                RaisePropertyChanged("TotalCount");
                            }
                            break;
                        }
                    }
                    else
                    {
                        SongCollection.Clear();
                        foreach (var song in await NeteaseUtil.SearchSongs(NeteaseUrl))
                        {
                            SongCollection.Add(song);
                            RaisePropertyChanged("TotalCount");
                        }
                    }
                });

                PlaylistDownloadCommand = new RelayCommand <Song>((song) =>
                {
                    SelectedSong = song;
                    if (string.IsNullOrWhiteSpace(SongTrackUrl))
                    {
                        return;
                    }
                    var downloader = new DownloadUtils();
                    downloader.DownloadProgressChanged += (sender, args) =>
                    {
                        song.DownProgress   = args.ProgressPercentage;
                        BytesReceived       = args.BytesReceived.ToString();
                        TotalBytesToReceive = args.TotalBytesToReceive.ToString();
                    };
                    downloader.DownloadFileCompleted += (sender, args) =>
                    {
                        if (DownloadNext)
                        {
                            int index = -1;
                            if ((index = SongCollection.IndexOf(song)) != -1 && index + 1 < SongCollection.Count)
                            {
                                PlaylistDownloadCommand.Execute(SongCollection.ElementAt(index + 1));
                            }
                        }
                        else
                        {
                            BytesReceived       = "0";
                            TotalBytesToReceive = "0";
                        }
                    };
                    downloader.Get(SongTrackUrl, Path.Combine("music", FileUtils.GetSafeFileName(song.SongFileName)));
                });

                ListenCommand = new RelayCommand <Song>((song) =>
                {
                    SelectedSong = song;
                    if (string.IsNullOrWhiteSpace(SongTrackUrl))
                    {
                        return;
                    }
                    if (song.PlayStatus == PlayStatus.Play)
                    {
                        if (CurrentPlaySong != null && CurrentPlaySong != song)
                        {
                            audioPlayback.Stop();
                            CurrentPlaySong.PlayProgress = 0;
                            CurrentPlaySong.PlayStatus   = PlayStatus.Play;
                        }

                        audioPlayback.Load(SongTrackUrl);
                        audioPlayback.Play();

                        CurrentPlaySong = song;
                        NowPlaying      = string.Format("Now Playing {0} - {1}", song.Artists, song.Title);
                        timer.Enabled   = true;
                        timer.Start();
                        song.PlayProgress = 0;
                        song.PlayStatus   = PlayStatus.Stop;
                    }
                    else
                    {
                        audioPlayback.Stop();
                        NowPlaying        = "";
                        song.PlayStatus   = PlayStatus.Play;
                        song.PlayProgress = 0;
                        timer.Enabled     = false;
                        timer.Stop();
                    }
                });

                OpenUrlCommand = new RelayCommand <string>((link) =>
                {
                    System.Diagnostics.Process.Start(link);
                });

                CopyUrlCommand = new RelayCommand <string>((link) =>
                {
                    Clipboard.SetText(link);
                });

                WindowClosing = new RelayCommand(() =>
                {
                    Properties.Settings.Default.Save();
                });
            }
        }
예제 #16
0
 protected virtual void InitStart()
 {
     GameManager.instance.AddNoun(nameString);
     audioSource = GameManager.instance.audioSource;
 }
예제 #17
0
        public static Track LoadTrackTRK(string track, string savename)
        {
            var ret = new Track();

            ret.Name = track;
            var addedlines = new Dictionary <int, StandardLine>();
            var extensions = new List <Extensionentry>();
            var location   = Program.CurrentDirectory + "Tracks" + Path.DirectorySeparatorChar + track;

            if (savename != null)
            {
                location += Path.DirectorySeparatorChar + savename + ".trk";
            }
            else
            {
                location += ".trk";
            }
            using (var file =
                       File.Open(location, FileMode.Open))
            {
                var br    = new BinaryReader(file);
                int magic = br.ReadInt32();
                if (magic == ('T' | 'R' << 8 | 'K' << 16 | 0xF2 << 24))
                {
                    byte     version  = br.ReadByte();
                    string[] features = Encoding.ASCII.GetString(br.ReadBytes(br.ReadInt16())).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    if (version != 1)
                    {
                        throw new Exception("Unsupported version");
                    }
                    bool redmultipier     = false;
                    bool scenerywidth     = false;
                    bool supports61       = false;
                    bool songinfo         = false;
                    bool ignorabletrigger = false;
                    for (int i = 0; i < features.Length; i++)
                    {
                        switch (features[i])
                        {
                        case "REDMULTIPLIER":
                            redmultipier = true;
                            break;

                        case "SCENERYWIDTH":
                            scenerywidth = true;
                            break;

                        case "6.1":
                            supports61 = true;
                            break;

                        case "SONGINFO":
                            songinfo = true;
                            break;

                        case "IGNORABLE_TRIGGER":
                            ignorabletrigger = true;
                            break;

                        case "ZEROSTART":
                            ret.ZeroStart = true;
                            break;

                        default:
                            throw new Exception("Unsupported feature");
                        }
                    }
                    if (supports61)
                    {
                        ret.SetVersion(6.1m);
                    }
                    else
                    {
                        ret.SetVersion(6.2m);
                    }
                    if (songinfo)
                    {
                        var song = br.ReadString();
                        try
                        {
                            var strings = song.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            var fn      = Program.CurrentDirectory + "Songs" +
                                          Path.DirectorySeparatorChar +
                                          strings[0];
                            if (File.Exists(fn))
                            {
                                if (AudioPlayback.LoadFile(ref fn))
                                {
                                    game.CurrentSong = new Song(Path.GetFileName(fn), float.Parse(strings[1]));
                                    game.EnableSong  = true;
                                }
                                else
                                {
                                    Program.NonFatalError("An unknown error occured trying to load the song file");
                                }
                            }
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                    ret.Start = new Vector2d(br.ReadDouble(), br.ReadDouble());
                    var lines = br.ReadInt32();
                    for (var i = 0; i < lines; i++)
                    {
                        Line        l;
                        byte        ltype      = br.ReadByte();
                        var         lt         = (LineType)(ltype & 0x1F);//we get 5 bits
                        var         inv        = (ltype >> 7) != 0;
                        var         lim        = (ltype >> 5) & 0x3;
                        var         ID         = -1;
                        var         prvID      = -1;
                        var         nxtID      = -1;
                        var         multiplier = 1;
                        var         linewidth  = 1f;
                        LineTrigger tr         = ignorabletrigger ? new LineTrigger() : null;
                        if (redmultipier)
                        {
                            if (lt == LineType.Red)
                            {
                                multiplier = br.ReadByte();
                            }
                        }
                        if (lt == LineType.Blue || lt == LineType.Red)
                        {
                            if (ignorabletrigger)
                            {
                                bool zoomtrigger = br.ReadBoolean();
                                if (zoomtrigger)
                                {
                                    tr.Zoomtrigger = true;
                                    var target = br.ReadSingle();
                                    var frames = br.ReadInt16();
                                    tr.ZoomFrames = frames;
                                    tr.ZoomTarget = target;
                                }
                                else
                                {
                                    tr = null;
                                }
                            }
                            ID = br.ReadInt32();
                            if (lim != 0)
                            {
                                prvID = br.ReadInt32();
                                nxtID = br.ReadInt32();
                            }
                        }
                        if (lt == LineType.Scenery)
                        {
                            if (scenerywidth)
                            {
                                float b = br.ReadByte();
                                linewidth = b / 10f;
                            }
                        }
                        var x1 = br.ReadDouble();
                        var y1 = br.ReadDouble();
                        var x2 = br.ReadDouble();
                        var y2 = br.ReadDouble();
                        switch (lt)
                        {
                        case LineType.Blue:
                            var bl = new StandardLine(new Vector2d(x1, y1), new Vector2d(x2, y2), inv);
                            bl.ID = ID;
                            bl.SetExtension(lim);
                            l = bl;
                            if (prvID != -1)
                            {
                                extensions.Add(new Extensionentry {
                                    Line = bl, Linkid = prvID, Next = false
                                });
                            }
                            if (nxtID != -1)
                            {
                                extensions.Add(new Extensionentry {
                                    Line = bl, Linkid = nxtID, Next = true
                                });
                            }
                            bl.Trigger = tr;
                            break;

                        case LineType.Red:
                            var rl = new RedLine(new Vector2d(x1, y1), new Vector2d(x2, y2), inv);
                            rl.ID = ID;
                            rl.SetExtension(lim);
                            if (redmultipier)
                            {
                                rl.Multiplier = multiplier;
                            }
                            l = rl;
                            if (prvID != -1)
                            {
                                extensions.Add(new Extensionentry {
                                    Line = rl, Linkid = prvID, Next = false
                                });
                            }
                            if (nxtID != -1)
                            {
                                extensions.Add(new Extensionentry {
                                    Line = rl, Linkid = nxtID, Next = true
                                });
                            }
                            rl.Trigger = tr;
                            break;

                        case LineType.Scenery:
                            l = new SceneryLine(new Vector2d(x1, y1), new Vector2d(x2, y2))
                            {
                                Width = linewidth
                            };

                            break;

                        default:
                            throw new Exception("Invalid line type");
                        }
                        if (l is StandardLine)
                        {
                            if (!addedlines.ContainsKey(l.ID))
                            {
                                addedlines[ID] = (StandardLine)l;
                                ret.AddLines(l);
                            }
                        }
                        else
                        {
                            ret.AddLines(l);
                        }
                    }
                }
            }
            foreach (var v in extensions)
            {
                if (v.Next)
                {
                    StandardLine sl;
                    if (addedlines.TryGetValue(v.Linkid, out sl))
                    {
                        //if (sl.Extension == StandardLine.ExtensionDirection.Right || sl.Extension == StandardLine.ExtensionDirection.Both)
                        {
                            v.Line.Next = sl;
                            sl.Prev     = v.Line;
                        }
                    }
                }
                else //prev
                {
                    StandardLine sl;
                    if (addedlines.TryGetValue(v.Linkid, out sl))
                    {
                        //if (sl.Extension == StandardLine.ExtensionDirection.Left || sl.Extension == StandardLine.ExtensionDirection.Both)
                        {
                            v.Line.Prev = sl;
                            sl.Next     = v.Line;
                        }
                    }
                }
            }
            ret.ResetUndo();
            ret.ResetChanges();
            return(ret);
        }
예제 #18
0
        public static void RecordTrack(GLWindow game, bool is1080P)
        {
            var flag = game.Track.GetFlag();

            if (flag == null)
            {
                return;
            }
            var resolution = new Size(is1080P ? 1920 : 1280, is1080P ? 1080 : 720);
            var oldsize    = game.RenderSize;
            var invalid    = false;
            var state      = new Rider();

            game.Track.Reset(state);
            var frame = flag.Frame;

            Recording      = true;
            Recording1080p = is1080P;
            game.Canvas.SetSize(game.RenderSize.Width, game.RenderSize.Height);
            game.Canvas.FindChildByName("buttons").Position(Pos.CenterH);

            if (frame > 400)                  //many frames, will likely lag the game. Update the window as a fallback.
            {
                if (frame > (20 * (60 * 40))) //too many frames, could lag the game very bad.
                {
                    return;
                }
                game.Title = Program.WindowTitle + " [Validating flag]";
                game.ProcessEvents();
            }
            for (var i = 0; i < frame; i++)
            {
                game.Track.Tick(state);
            }
            for (var i = 0; i < state.ModelAnchors.Length; i++)
            {
                if (state.ModelAnchors[i].Position != flag.State.ModelAnchors[i].Position ||
                    state.ModelAnchors[i].Prev != flag.State.ModelAnchors[i].Prev)
                {
                    invalid = true;
                    break;
                }
            }
            var frontbuffer = SafeFrameBuffer.GenFramebuffer();

            SafeFrameBuffer.BindFramebuffer(FramebufferTarget.Framebuffer, frontbuffer);

            var rbo2 = SafeFrameBuffer.GenRenderbuffer();

            SafeFrameBuffer.BindRenderbuffer(RenderbufferTarget.Renderbuffer, rbo2);
            SafeFrameBuffer.RenderbufferStorage(RenderbufferTarget.Renderbuffer, RenderbufferStorage.Rgb8, resolution.Width, resolution.Height);
            SafeFrameBuffer.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, RenderbufferTarget.Renderbuffer, rbo2);

            SafeFrameBuffer.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0);
            if (!invalid)
            {
                string errormessage = "An unknown error occured during recording.";
                game.Title = Program.WindowTitle + " [Recording | Hold ESC to cancel]";
                game.ProcessEvents();
                var filename   = Program.CurrentDirectory + game.Track.Name + ".mp4";
                var flagbackup = flag;
                var hardexit   = false;
                game.Track.Flag();
                var recmodesave = game.SettingRecordingMode;
                game.SettingRecordingMode = true;
                game.Track.Start(true, true, false, false);
                game.Render();
                var dir = Program.CurrentDirectory + game.Track.Name + "_rec";
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                var firstframe = GrabScreenshot(game, frontbuffer);
                SaveScreenshot(game.RenderSize.Width, game.RenderSize.Height, firstframe, dir + Path.DirectorySeparatorChar + "tmp" + 0 + ".png");
                int[] savethreads = { 0 };
                for (var i = 0; i < frame; i++)
                {
                    if (hardexit)
                    {
                        break;
                    }
                    game.Track.Update(1);
                    game.Render();
                    var screenshot = GrabScreenshot(game, frontbuffer);
                    var objtopass  = new Tuple <byte[], int>(screenshot, i + 1);
                    savethreads[0] += 1;
                    var save = new Task(t =>
                    {
                        var passed = (Tuple <byte[], int>)t;
                        try
                        {
                            SaveScreenshot(game.RenderSize.Width, game.RenderSize.Height, passed.Item1, dir + Path.DirectorySeparatorChar + "tmp" + passed.Item2 + ".png");
                        }
                        catch
                        {
                            hardexit     = true;
                            errormessage = "An error occured when saving the frame.";
                        }
                        finally
                        {
                            Interlocked.Decrement(ref savethreads[0]);
                        }
                    }, objtopass);

                    save.Start();
                    if (Keyboard.GetState()[Key.Escape])
                    {
                        hardexit     = true;
                        errormessage = "The user manually cancelled recording.";
                    }
                    if (i % 40 == 0)
                    {
                        game.Title = string.Format("{0} [Recording {1:P}% | Hold ESC to cancel]", Program.WindowTitle, i / (double)frame);
                        game.ProcessEvents();
                    }
                }

                if (!hardexit)
                {
                    var parameters = new FFMPEGParameters();
                    parameters.AddOption("framerate", "40");
                    parameters.AddOption("i", "\"" + dir + Path.DirectorySeparatorChar + "tmp%d.png" + "\"");
                    parameters.AddOption("vf", "vflip");//we save images upside down expecting ffmpeg to flip more efficiently.
                    parameters.AddOption("c:v", "libx264");
                    parameters.AddOption("preset", "veryfast");
                    parameters.AddOption("qp", "0");

                    //    parameters.AddOption("scale",is1080p?"1920:1080":"1280:720");
                    parameters.OutputFilePath = filename;
                    var failed = false;
                    while (savethreads[0] != 0)
                    {
                        Thread.Sleep(1);
                    }
                    if (File.Exists(filename))
                    {
                        try
                        {
                            File.Delete(filename);
                        }
                        catch
                        {
                            Program.NonFatalError("A file with the name " + game.Track.Name + ".mp4 already exists");
                            failed       = true;
                            errormessage = "Cannot replace a file of the existing name " + game.Track.Name + ".mp4.";
                        }
                    }
                    if (!failed)
                    {
                        game.Title = Program.WindowTitle + " [Encoding Video | 0%]";
                        game.ProcessEvents();
                        try
                        {
                            FFMPEG.Execute(parameters, (string s) =>
                            {
                                int idx = s.IndexOf("frame=", StringComparison.InvariantCulture);
                                if (idx != -1)
                                {
                                    idx += "frame=".Length;
                                    for (; idx < s.Length; idx++)
                                    {
                                        if (char.IsNumber(s[idx]))
                                        {
                                            break;
                                        }
                                    }
                                    var space = s.IndexOf(" ", idx, StringComparison.InvariantCulture);
                                    if (space != -1)
                                    {
                                        var sub       = s.Substring(idx, space - idx);
                                        var parsedint = -1;
                                        if (int.TryParse(sub, out parsedint))
                                        {
                                            game.Title = Program.WindowTitle + string.Format(" [Encoding Video | {0:P}% | Hold ESC to cancel]", parsedint / (double)frame);
                                            game.ProcessEvents();
                                            if (Keyboard.GetState()[Key.Escape])
                                            {
                                                hardexit     = true;
                                                errormessage = "The user manually cancelled recording.";
                                                return(false);
                                            }
                                        }
                                    }
                                }
                                return(true);
                            });
                        }
                        catch (Exception e)
                        {
                            Program.NonFatalError("ffmpeg error.\r\n" + e);
                            hardexit     = true;
                            errormessage = "An ffmpeg error occured.";
                        }
                    }
                }
                try
                {
                    Directory.Delete(dir, true);
                }
                catch
                {
                    Program.NonFatalError("Unable to delete " + dir);
                }
                if (hardexit)
                {
                    try
                    {
                        File.Delete(filename);
                    }
                    catch
                    {
                        Program.NonFatalError("Unable to delete " + filename);
                    }
                }
                game.SettingRecordingMode = recmodesave;
                game.Title = Program.WindowTitle;
                game.Track.RestoreFlag(flagbackup);
                game.Track.Stop();
                game.ProcessEvents();
                var openwindows = game.Canvas.GetOpenWindows();
                foreach (var window in openwindows)
                {
                    var w = window as WindowControl;
                    w?.Close();
                }
                if (File.Exists(filename))
                {
                    try
                    {
                        AudioPlayback.Init();
                        MemoryStream ms = new MemoryStream(GameResources.beep);

                        SoundStream str = new SoundStream(ms);
                        str.Play(0, 1);
                        int count = 0;
                        while (str.Playing)
                        {
                            Thread.Sleep(1);
                            count += 1;
                            if (count >= 3000)//in case something weird happens
                            {
                                break;
                            }
                        }
                        str.Dispose();
                        ms.Dispose();
                    }
                    catch
                    {
                        //ignored
                    }
                }
                else
                {
                    PopupWindow.Error(game.Canvas, game, errormessage, "Error!");
                }
            }
            SafeFrameBuffer.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
            SafeFrameBuffer.DeleteFramebuffer(frontbuffer);
            SafeFrameBuffer.DeleteRenderbuffers(1, new[] { rbo2 });
            game.RenderSize = oldsize;
            Recording       = false;

            game.Canvas.SetSize(game.RenderSize.Width, game.RenderSize.Height);
            game.Canvas.FindChildByName("buttons").Position(Pos.CenterH);
        }