Example #1
0
        /// <summary>
        ///     Inserts an entire extracted directory of maps to the DB
        /// </summary>
        /// <param name="extractDirectory"></param>
        private static Map InsertAndUpdateSelectedMap(string extractDirectory)
        {
            // Go through each file in the directory and import it into the database.
            var quaFiles     = Directory.GetFiles(extractDirectory, "*.qua", SearchOption.AllDirectories).ToList();
            Map lastImported = null;

            try
            {
                foreach (var quaFile in quaFiles)
                {
                    var map = Map.FromQua(Qua.Parse(quaFile), quaFile);
                    map.DifficultyProcessorVersion = DifficultyProcessorKeys.Version;

                    var info = OnlineManager.Client?.RetrieveMapInfo(map.MapId);
                    if (info != null)
                    {
                        map.RankedStatus = info.Map.RankedStatus;
                    }

                    map.CalculateDifficulties();
                    MapDatabaseCache.InsertMap(map, quaFile);
                    lastImported = map;
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, LogType.Runtime);
            }

            return(lastImported);
        }
Example #2
0
        /// <summary>
        ///     Adds any new files that are currently not cached.
        ///     Used if the user adds a file to the folder.
        /// </summary>
        /// <param name="files"></param>
        private static void AddNonCachedFiles(List <string> files)
        {
            var maps = FetchAll();

            foreach (var file in files)
            {
                if (maps.Any(x => BackslashToForward(file) == BackslashToForward($"{ConfigManager.SongDirectory.Value}/{x.Directory}/{x.Path}")))
                {
                    continue;
                }

                // Found map that isn't cached in the database yet.
                try
                {
                    var map = Map.FromQua(Qua.Parse(file), file);
                    map.CalculateDifficulties();
                    map.DifficultyProcessorVersion = DifficultyProcessorKeys.Version;
                    InsertMap(map, file);
                }
                catch (Exception e)
                {
                    Logger.Error(e, LogType.Runtime);
                }
            }
        }
Example #3
0
        /// <summary>
        /// Converts the input of a specific row from the data grid into a Qua file.
        /// </summary>
        /// <param name="row"></param>
        /// <param name="parseMap"></param>
        /// <returns></returns>
        private MapData ParseMapsRowData(int row, bool parseMap = false)
        {
            var file       = parseMap ? AddRoot(GetMapFilePath(row)) : GetMapFilePath(row);
            var difficulty = float.Parse(DataGrid.Rows[row].Cells[2].Value.ToString());
            var weight     = float.Parse(DataGrid.Rows[row].Cells[3].Value.ToString());
            Qua map        = null;

            if (parseMap)
            {
                try
                {
                    if (file.EndsWith(".qua"))
                    {
                        map = Qua.Parse(file);
                    }
                    else if (file.EndsWith(".osu"))
                    {
                        map = new OsuBeatmap(file).ToQua();
                    }

                    PrintToOutput($"Map successfully parsed: {file}");
                }
                catch (Exception e)
                {
                    ErrorToOutput($"Error parsing map: {e.Message}");
                }
            }

            return(new MapData(file, difficulty, weight, map));
        }
Example #4
0
        /// <summary>
        /// </summary>
        /// <param name="screen"></param>
        /// <param name="file"></param>
        private static void OnConfirm(QuaverScreen screen, string file)
        {
            for (var i = DialogManager.Dialogs.Count - 1; i >= 0; i--)
            {
                DialogManager.Dialogs[i].Destroy();
                DialogManager.Dialogs.Remove(DialogManager.Dialogs[i]);
            }

            DialogManager.Update(new GameTime());

            if (!MapDatabaseCache.MapsToUpdate.Contains(MapManager.Selected.Value))
            {
                MapDatabaseCache.MapsToUpdate.Add(MapManager.Selected.Value);
            }

            screen.Exit(() =>
            {
                try
                {
                    return(new EditorScreen(Qua.Parse(file, false)));
                }
                catch (Exception exception)
                {
                    Logger.Error(exception, LogType.Runtime);
                    NotificationManager.Show(NotificationLevel.Error, "Failed to reload editor. Is your .qua file invalid?");
                    return(new SelectScreen());
                }
            });
        }
        /// <summary>
        /// </summary>
        /// <param name="args"></param>
        public VirtualReplayPlayerCommand(string[] args) : base(args)
        {
            var readHeaderLess = false;

            if (args.Length == 5)
            {
                if (args[4] == "-hl")
                {
                    readHeaderLess = true;
                }
            }

            Replay = new Replay(args[1], readHeaderLess)
            {
                Mods = (ModIdentifier)long.Parse(args[3])
            };

            if (args[2].EndsWith(".qua"))
            {
                Map = Qua.Parse(args[2]);
            }
            else if (args[2].EndsWith(".osu"))
            {
                Map = new OsuBeatmap(args[2]).ToQua();
            }

            MapMd5 = CryptoHelper.FileToMd5(args[2]);

            if (MapMd5 != Replay.MapMd5 && !readHeaderLess)
            {
                throw new ArgumentException("The specified replay doesn't match the map.");
            }
        }
        /// <summary>
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnConfirm(object sender, EventArgs e)
        {
            var game = GameBase.Game as QuaverGame;

            try
            {
                var path     = $"{ConfigManager.SongDirectory}/{MapManager.Selected.Value.Directory}/{MapManager.Selected.Value.Path}.autosave";
                var realPath = path.Replace(".autosave", "");

                File.Delete(realPath);
                File.Copy(path, realPath, true);
                File.Delete(path);

                if (!MapDatabaseCache.MapsToUpdate.Contains(MapManager.Selected.Value))
                {
                    MapDatabaseCache.MapsToUpdate.Add(MapManager.Selected.Value);
                }

                var qua = Qua.Parse(realPath, false);
                game?.CurrentScreen.Exit(() => new EditorScreen(qua));
            }
            catch (Exception exception)
            {
                Logger.Error(exception, LogType.Runtime);
                NotificationManager.Show(NotificationLevel.Error, "Could not load autosave map");
            }
        }
Example #7
0
        public void SoundEffects()
        {
            var qua = Qua.Parse("./Quaver/Resources/sound-effects.qua");

            Assert.True(qua.IsValid());
            Assert.Equal(new []
            {
                new CustomAudioSampleInfo()
                {
                    Path             = "hello.wav",
                    UnaffectedByRate = false
                },
                new CustomAudioSampleInfo()
                {
                    Path             = "world.mp3",
                    UnaffectedByRate = true
                }
            }, qua.CustomAudioSamples, CustomAudioSampleInfo.ByValueComparer);
            Assert.Equal(new []
            {
                new SoundEffectInfo()
                {
                    StartTime = 123,
                    Sample    = 2,
                    Volume    = 100
                },
                new SoundEffectInfo()
                {
                    StartTime = 200,
                    Sample    = 1,
                    Volume    = 53
                }
            }, qua.SoundEffects, SoundEffectInfo.ByValueComparer);
        }
Example #8
0
        public void KeySoundZeroVolume()
        {
            var converter      = new OsuBeatmap("./Osu/Resources/keysound-zero-volume.osu");
            var qua            = converter.ToQua();
            var groundTruthQua = Qua.Parse("./Osu/Resources/keysound-zero-volume.qua");

            Assert.Equal(groundTruthQua.HitObjects, qua.HitObjects, HitObjectInfo.ByValueComparer);
        }
        public ChangeQuaIdsCommand(string[] args) : base(args)
        {
            var qua = Qua.Parse(args[1], false);

            qua.MapId    = int.Parse(args[3]);
            qua.MapSetId = int.Parse(args[4]);
            qua.Save(args[2]);
        }
Example #10
0
        public void FullConversionWithKeysoundsCheck()
        {
            var converter = new OsuBeatmap("./Osu/Resources/megalovania.osu");
            var qua       = converter.ToQua();

            var groundTruthQua = Qua.Parse("./Osu/Resources/megalovania.qua");

            Assert.True(qua.EqualByValue(groundTruthQua));
        }
Example #11
0
        public void HitSoundTypeConversionCheck()
        {
            var converter = new OsuBeatmap("./Osu/Resources/hitsounds.osu");
            var qua       = converter.ToQua();

            var groundTruthQua = Qua.Parse("./Osu/Resources/hitsounds.qua");

            Assert.True(qua.EqualByValue(groundTruthQua));
        }
Example #12
0
        public void FullConversionCheck()
        {
            var converter = new OsuBeatmap(BeatmapFilename);
            var qua       = converter.ToQua();

            var groundTruthQua = Qua.Parse(Path.ChangeExtension(BeatmapFilename, "qua"));

            Assert.True(qua.EqualByValue(groundTruthQua));
        }
Example #13
0
        public void SoundEffectsFromO2JamConvert()
        {
            var converter      = new OsuBeatmap("./Osu/Resources/Glide.osu");
            var qua            = converter.ToQua();
            var groundTruthQua = Qua.Parse("./Osu/Resources/Glide-sound-effects.qua");

            Assert.Equal(groundTruthQua.CustomAudioSamples, qua.CustomAudioSamples, CustomAudioSampleInfo.ByValueComparer);
            Assert.Equal(groundTruthQua.SoundEffects, qua.SoundEffects, SoundEffectInfo.ByValueComparer);
        }
Example #14
0
        public void LoadFromStream()
        {
            var map = "./Quaver/Resources/fullln-output.qua";

            var buffer       = File.ReadAllBytes(map);
            var byteArrayQua = Qua.Parse(buffer);
            var normalQua    = Qua.Parse(map);

            var expectedObjects = normalQua.HitObjects.ToImmutableHashSet(HitObjectInfo.ByValueComparer);

            Assert.True(byteArrayQua.HitObjects.ToImmutableHashSet(HitObjectInfo.ByValueComparer).SetEquals(expectedObjects));
        }
Example #15
0
        public void IssueQuaver721()
        {
            var qua = Qua.Parse("./Quaver/Resources/issue-quaver-721.qua");

            qua.ApplyMods(ModIdentifier.FullLN);

            var originalQua = Qua.Parse("./Quaver/Resources/issue-quaver-721.qua");

            // Full LN should preserve the object if it's the only object in a lane.
            Assert.True(qua.EqualByValue(originalQua));
            Assert.True(qua.IsValid());
        }
Example #16
0
        public void FullLN()
        {
            var qua = Qua.Parse(LN_CONVERSION_INPUT);

            qua.ApplyMods(ModIdentifier.FullLN);
            var objects = qua.HitObjects.ToImmutableHashSet(HitObjectInfo.ByValueComparer);

            var expected        = Qua.Parse("./Quaver/Resources/fullln-output.qua");
            var expectedObjects = expected.HitObjects.ToImmutableHashSet(HitObjectInfo.ByValueComparer);

            Assert.True(objects.SetEquals(expectedObjects));
        }
Example #17
0
        /// <summary>
        /// </summary>
        private void CreateExportButton()
        {
            CalibrateOffsetButton = new BorderedTextButton("Calibrate", Colors.MainAccent)
            {
                Parent    = this,
                X         = -50,
                Alignment = Alignment.MidRight,
                Height    = 30,
                Width     = 225,
                Text      =
                {
                    Font     = Fonts.SourceSansProSemiBold,
                    FontSize = 12
                }
            };

            CalibrateOffsetButton.Clicked += (o, e) =>
            {
                var game = (QuaverGame)GameBase.Game;

                if (game.CurrentScreen.Type == QuaverScreenType.Editor)
                {
                    NotificationManager.Show(NotificationLevel.Warning, "Finish what you're doing before calibrating a new offset");
                    return;
                }

                var path = $"Quaver.Resources/Maps/Offset/offset.qua";

                var qua = Qua.Parse(GameBase.Game.Resources.Get(path));

                if (AudioEngine.Track != null && !AudioEngine.Track.IsDisposed && AudioEngine.Track.IsPlaying)
                {
                    AudioEngine.Track.Pause();
                }

                game.CurrentScreen?.Exit(() =>
                {
                    MapManager.Selected.Value     = Map.FromQua(qua, path, true);
                    MapManager.Selected.Value.Qua = qua;

                    // Make the user not allow to fail.
                    ModManager.RemoveAllMods();
                    ModManager.AddMod(ModIdentifier.NoFail);

                    // Load the background (usually the default one)
                    BackgroundHelper.Load(MapManager.Selected.Value);
                    DialogManager.Dismiss(Dialog);

                    return(new GameplayScreen(qua, "", new List <Score>(), null, false, 0, true));
                });
            };
        }
Example #18
0
        public void SVNormalization()
        {
            var tests = new[]
            {
                "regression-1",
                "regression-2",
                "regression-3",
                "regression-4",
                "regression-5",
                "regression-6",
                "regression-7",
                "regression-8",
                "regression-9",
                "sample",
                "sv-at-first-timing-point",
                "sv-before-first-timing-point",
                "symphony",
                "timing-points-override-svs",
                "cheat",
            };

            foreach (var test in tests)
            {
                // These files were generated with plitki-map-qua (taken as ground truth) from its test suite.
                var pathNormalized   = $"./Quaver/Resources/{test}.qua";
                var pathDenormalized = $"./Quaver/Resources/{test}-normalized.qua";

                var quaDenormalized = Qua.Parse(pathNormalized, false);
                var quaNormalized   = Qua.Parse(pathDenormalized, false);

                // Check that the normalization gives the correct result.
                var quaDenormalizedNormalized = quaDenormalized.WithNormalizedSVs();
                Assert.True(quaDenormalizedNormalized.EqualByValue(quaNormalized));

                // Denormalization can move the first SV (it doesn't matter where to put the InitialScrollVelocity SV).
                // So check back-and-forth instead of just denormalization.
                var quaNormalizedDenormalizedNormalized = quaNormalized.WithDenormalizedSVs().WithNormalizedSVs();
                Assert.True(quaNormalizedDenormalizedNormalized.EqualByValue(quaNormalized));

                // Check that serializing and parsing the result does not change it.
                var bufferDenormalized = Encoding.UTF8.GetBytes(quaDenormalized.Serialize());
                var quaDenormalized2   = Qua.Parse(bufferDenormalized, false);
                Assert.True(quaDenormalized.EqualByValue(quaDenormalized2));

                var bufferNormalized = Encoding.UTF8.GetBytes(quaNormalized.Serialize());
                var quaNormalized2   = Qua.Parse(bufferNormalized, false);
                Assert.True(quaNormalized.EqualByValue(quaNormalized2));
            }
        }
Example #19
0
        /// <summary>
        /// </summary>
        /// <param name="args"></param>
        public CalcDiffCommand(string[] args) : base(args)
        {
            var path = args[1];

            if (path.EndsWith(".qua"))
            {
                Map = Qua.Parse(path);
            }
            else if (path.EndsWith(".osu"))
            {
                Map = new OsuBeatmap(path).ToQua();
            }

            Mods = (ModIdentifier)Enum.Parse(typeof(ModIdentifier), args[2]);
        }
Example #20
0
        /// <summary>
        /// </summary>
        public override void Execute()
        {
            var files = Directory.GetFiles(BaseFolder, "*.qua", SearchOption.AllDirectories).ToList();

            files.AddRange(Directory.GetFiles(BaseFolder, "*.osu", SearchOption.AllDirectories));

            var calculatedMaps = new List <Tuple <int, string, string> >();

            for (var i = 0; i < files.Count; i++)
            {
                var file = files[i];

                try
                {
                    Qua map = null;

                    if (file.EndsWith(".qua"))
                    {
                        map = Qua.Parse(file);
                    }
                    else if (file.EndsWith(".osu"))
                    {
                        map = new OsuBeatmap(file).ToQua();
                    }

                    if (map == null)
                    {
                        continue;
                    }

                    var diffCalc = map.SolveDifficulty();

                    Console.WriteLine($"[{i}] | {map} | {diffCalc.OverallDifficulty}");
                    calculatedMaps.Add(Tuple.Create(i, map.ToString(), diffCalc.OverallDifficulty.ToString(CultureInfo.InvariantCulture)));
                }
                catch (Exception e)
                {
                    continue;
                }
            }

            var table = calculatedMaps.ToStringTable(new[] { "Id", "Map", "Difficulty" }, a => a.Item1, a => a.Item2, a => a.Item3);

            Console.WriteLine(table);

            File.WriteAllText("./diff-calc.txt", table);
        }
Example #21
0
        private static List <Qua> GetQuaFromDirectory(string dirname)
        {
            List <Qua> maps = new List <Qua>();

            foreach (string file in Directory.GetFiles(dirname, "*.qua"))
            {
                try
                {
                    maps.Add(Qua.Parse(File.ReadAllBytes(file), true));
                } catch (Exception e)
                {
                    Alert($"Invalid map '{ Path.GetFileNameWithoutExtension(file) }'. ({ e.ToString() })");
                }
            }

            return(maps);
        }
Example #22
0
        /// <summary>
        /// </summary>
        public static void ForceUpdateMaps()
        {
            for (var i = 0; i < MapsToUpdate.Count; i++)
            {
                try
                {
                    var path = $"{ConfigManager.SongDirectory}/{MapsToUpdate[i].Directory}/{MapsToUpdate[i].Path}";

                    if (!File.Exists(path))
                    {
                        continue;
                    }

                    var map = Map.FromQua(Qua.Parse(path, false), path);
                    map.CalculateDifficulties();
                    map.Id = MapsToUpdate[i].Id;

                    if (map.Id == 0)
                    {
                        map.Id = InsertMap(map, path);
                    }
                    else
                    {
                        UpdateMap(map);
                    }

                    MapsToUpdate[i]           = map;
                    MapManager.Selected.Value = map;
                }
                catch (Exception e)
                {
                    Logger.Error(e, LogType.Runtime);
                }
            }

            MapsToUpdate.Clear();
            OrderAndSetMapsets();

            var selectedMapset = MapManager.Mapsets.Find(x => x.Maps.Any(y => y.Id == MapManager.Selected.Value.Id));

            MapManager.Selected.Value = selectedMapset.Maps.Find(x => x.Id == MapManager.Selected.Value.Id);
        }
Example #23
0
        public void KeySounds()
        {
            var qua = Qua.Parse("./Quaver/Resources/keysounds.qua");

            Assert.True(qua.IsValid());
            Assert.Equal(new []
            {
                new CustomAudioSampleInfo()
                {
                    Path             = "hello.wav",
                    UnaffectedByRate = false
                },
                new CustomAudioSampleInfo()
                {
                    Path             = "world.mp3",
                    UnaffectedByRate = true
                }
            }, qua.CustomAudioSamples, CustomAudioSampleInfo.ByValueComparer);
            Assert.Equal(new List <KeySoundInfo>
            {
                new KeySoundInfo
                {
                    Sample = 1,
                    Volume = 100
                },
                new KeySoundInfo
                {
                    Sample = 2,
                    Volume = 50
                }
            }, qua.HitObjects[0].KeySounds, KeySoundInfo.ByValueComparer);
            Assert.Equal(new List <KeySoundInfo>
            {
                new KeySoundInfo
                {
                    Sample = 2,
                    Volume = 100
                }
            }, qua.HitObjects[1].KeySounds, KeySoundInfo.ByValueComparer);
            Assert.Equal(new List <KeySoundInfo>(), qua.HitObjects[2].KeySounds, KeySoundInfo.ByValueComparer);
        }
Example #24
0
        public static Qua Fetch(int id)
        {
            Directory.CreateDirectory(Dir);

            var filePath = $"{Dir}/{id}.qua";

            try
            {
                lock (IdLocks)
                {
                    if (!IdLocks.ContainsKey(id))
                    {
                        IdLocks[id] = new object();
                    }
                }

                lock (IdLocks[id])
                {
                    if (File.Exists(filePath))
                    {
                        return(Qua.Parse(filePath, false));
                    }

                    using (var client = new WebClient())
                        client.DownloadFile($"{Configuration.Instance.APIUrl}/d/web/map/{id}", filePath);
                }

                return(Qua.Parse(filePath, false));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                File.Delete(filePath);
                return(null);
            }
        }
Example #25
0
File: Map.cs Project: AiAe/Quaver-1
        /// <summary>
        ///     Loads the .qua, .osu or .sm file for a map.
        ///
        /// </summary>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public Qua LoadQua(bool checkValidity = true)
        {
            // Reference to the parsed .qua file
            Qua qua;

            // Handle osu! maps as well
            switch (Game)
            {
            case MapGame.Quaver:
                var quaPath = $"{ConfigManager.SongDirectory}/{Directory}/{Path}";
                qua = Qua.Parse(quaPath, checkValidity);
                break;

            case MapGame.Osu:
                var osu = new OsuBeatmap(MapManager.OsuSongsFolder + Directory + "/" + Path);
                qua = osu.ToQua();
                break;

            default:
                throw new InvalidEnumArgumentException();
            }

            return(qua);
        }
Example #26
0
        /// <summary>
        ///     Uploads the mapset to the server
        /// </summary>
        private void UploadMapset() => ThreadScheduler.Run(() =>
        {
            try
            {
                Logger.Important($"Starting to upload mapset...", LogType.Network);

                var path = MapManager.Selected.Value.Mapset.ExportToZip(false);
                Response = OnlineManager.Client.UploadMapset(path);
                Logger.Important($"Uploaded mapset with response: {Response}", LogType.Network);

                File.Delete(path);

                // ReSharper disable once SwitchStatementMissingSomeCases
                switch (Response.Code)
                {
                case MapsetSubmissionStatusCode.SuccessUpdated:
                case MapsetSubmissionStatusCode.SuccessUploaded:
                    // Get all files in the directory and delete them, so we can get the updated ones
                    foreach (var f in Directory.GetFiles($"{ConfigManager.SongDirectory.Value}/{MapManager.Selected.Value.Directory}", "*.qua"))
                    {
                        File.Delete(f);
                    }

                    using (var conn = new SQLiteConnection(MapDatabaseCache.DatabasePath))
                        MapManager.Selected.Value.Mapset.Maps.ForEach(x => conn.Delete(x));

                    foreach (var map in Response.Maps)
                    {
                        if (map == null)
                        {
                            continue;
                        }

                        var filePath = $"{ConfigManager.SongDirectory.Value}/{MapManager.Selected.Value.Directory}/{map.Id}.qua";

                        Logger.Important($"Commencing download for map: {map.Id}", LogType.Runtime);

                        try
                        {
                            OnlineManager.Client.DownloadMap(filePath, map.Id);
                            Logger.Important($"Successfully downloaded map: {map.Id}", LogType.Network);
                        }
                        catch (Exception)
                        {
                            continue;
                        }

                        MapDatabaseCache.MapsToUpdate.Add(Map.FromQua(Qua.Parse(filePath), filePath));

                        Thread.Sleep(1000);
                    }

                    DividerLine.Tint = Color.LimeGreen;
                    TopLine.Tint     = Color.LimeGreen;

                    MapDatabaseCache.ForceUpdateMaps();
                    break;

                default:
                    DividerLine.Tint = Color.Crimson;
                    TopLine.Tint     = Color.Crimson;
                    break;
                }

                Header.Text = StatusCodeMessages[Response.Code];
            }
            catch (Exception e)
            {
                Logger.Error(e, LogType.Network);
                DividerLine.Tint = Color.Crimson;
                TopLine.Tint     = Color.Crimson;

                Header.Text = "An unknown error has occurred while uploading. Please check your log files!";
            }
            finally
            {
                LoadingWheel.Visible = false;
                CreateCloseButton();

                if (Response != null && (Response.Code == MapsetSubmissionStatusCode.SuccessUpdated ||
                                         Response.Code == MapsetSubmissionStatusCode.SuccessUploaded))
                {
                    CloseButton.Border.Tint = Color.LimeGreen;
                    CloseButton.Text.Tint   = Color.LimeGreen;

                    CreateVisitMapsetPageButton();
                    VisitMapsetPageButton.X = -VisitMapsetPageButton.Width / 2f - 10;
                    CloseButton.X           = CloseButton.Width / 2f + 10;
                }
            }
        });
Example #27
0
        public void InvalidSampleIndex()
        {
            var qua = Qua.Parse("./Quaver/Resources/sound-effects-invalid-sample-index.qua", false);

            Assert.False(qua.IsValid());
        }
Example #28
0
        public static void ConvertMapset(string mapsetPath, Arguments args)
        {
            if (!File.Exists(mapsetPath) || Path.GetExtension(mapsetPath) != ".qp")
            {
                throw new ArgumentException("Invalid file");
            }

            var outputDir  = args.Output ?? Path.GetDirectoryName(mapsetPath);
            var folderName = Path.GetFileNameWithoutExtension(mapsetPath);
            var extractDir = Path.Join(outputDir, folderName);

            try
            {
                ZipFile.ExtractToDirectory(mapsetPath, extractDir, true);
                foreach (var file in Directory.EnumerateFiles(extractDir))
                {
                    switch (Path.GetExtension(file))
                    {
                    case ".qua":
                        var qua = Qua.Parse(file);
                        args.Print("Parsed qua", 3);

                        var map = new Osu.OsuBeatmap(qua, args);
                        args.Print("Converted qua to osu! map object", 3);

                        File.WriteAllText(file, map.ToString());
                        args.Print($"Written to file {file}", 3);

                        var osuPath = Path.Join(extractDir, Path.GetFileNameWithoutExtension(file) + ".osu");
                        File.Move(file, osuPath, true);
                        args.Print($"Renamed file to {osuPath}", 3);

                        break;

                    case ".png":
                    case ".jpg":
                    case ".mp3":
                        args.Print($"Kept file {file} in directory", 3);
                        break;

                    default:
                        args.Print($"Removed file {file}", 3);
                        File.Delete(file);
                        break;
                    }
                }

                var oszPath = extractDir + ".osz";
                if (File.Exists(oszPath))
                {
                    args.Print($"Removed existing .osz", 3);
                    File.Delete(oszPath);
                }

                ZipFile.CreateFromDirectory(extractDir, extractDir + ".osz");
                args.Print($"Created new .osz", 3);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e);
            }
            finally
            {
                foreach (var file in Directory.EnumerateFiles(extractDir))
                {
                    File.Delete(file);
                }
                Directory.Delete(extractDir);
                args.Print($"Removed temporary conversion folder", 3);
            }
        }
Example #29
0
        public SVPlot()
        {
            // Select .qua file
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.DefaultExt       = ".qua";
            dialog.Filter           = "Quaver map files (.qua)|*.qua";
            dialog.InitialDirectory = "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Quaver\\Songs";

            bool?result = dialog.ShowDialog();

            if (result == true)
            {
                Map = Qua.Parse(dialog.FileName, false);
            }

            Map.NormalizeSVs();
            Map.SliderVelocities.Insert(0, new SliderVelocityInfo {
                StartTime  = Math.Min(Map.SliderVelocities[0].StartTime, 0) - 3000,
                Multiplier = Map.InitialScrollVelocity
            });
            Map.SliderVelocities.Add(new SliderVelocityInfo {
                StartTime  = Math.Max(Map.SliderVelocities.Last().StartTime, Map.Length) + 3000,
                Multiplier = Map.SliderVelocities.Last().Multiplier
            });

            // Plot stuff
            Model = new PlotModel {
                Title = Map.ToString()
            };
            Model.Axes.Add(new LinearAxis {
                Position = AxisPosition.Bottom, Key = "Time", Title = "Time (ms)"
            });
            Model.Axes.Add(new LinearAxis {
                Position = AxisPosition.Left, Key = "Velocity", Title = "Velocity", Minimum = -10, Maximum = 10
            });
            Model.Axes.Add(new LinearAxis {
                Position = AxisPosition.Right, Key = "Position", Title = "Position", PositionTier = 1
            });

            // Scroll Velocities
            SVSeries       = new StairStepSeries();
            SVSeries.Title = "Scroll Velocities";
            SVSeries.VerticalStrokeThickness     = .25;
            SVSeries.CanTrackerInterpolatePoints = false;
            SVSeries.DataFieldX = "Time";
            SVSeries.DataFieldY = "Multiplier";
            SVSeries.YAxisKey   = "Velocity";

            foreach (SliderVelocityInfo sv in Map.SliderVelocities)
            {
                SVSeries.Points.Add(new DataPoint(sv.StartTime, sv.Multiplier));
            }

            // Position
            PositionSeries       = new LineSeries();
            PositionSeries.Title = "Position";
            PositionSeries.CanTrackerInterpolatePoints = true;
            PositionSeries.DataFieldX = "Time";
            PositionSeries.DataFieldY = "Position";
            PositionSeries.YAxisKey   = "Position";

            // Calculate position data points based off of Quaver's position calculations
            // This is pretty much just HitObjectManagerKeys.InitializePositionMarkers()
            long position = (long)(Map.SliderVelocities[0].StartTime * Map.InitialScrollVelocity * 100);

            PositionSeries.Points.Add(new DataPoint(Map.SliderVelocities[0].StartTime, position));

            for (int i = 1; i < Map.SliderVelocities.Count; i++)
            {
                position += (long)((Map.SliderVelocities[i].StartTime - Map.SliderVelocities[i - 1].StartTime)
                                   * Map.SliderVelocities[i - 1].Multiplier * 100);
                PositionSeries.Points.Add(new DataPoint(Map.SliderVelocities[i].StartTime, position));
            }

            Model.Series.Add(SVSeries);
            Model.Series.Add(PositionSeries);
        }
Example #30
0
        public void InvalidKeySoundIndex()
        {
            var qua = Qua.Parse("./Quaver/Resources/keysounds-invalid-sample-index.qua", false);

            Assert.False(qua.IsValid());
        }