SongBrowserModel.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. using SongBrowserPlugin.DataAccess;
  2. using SongBrowserPlugin.UI;
  3. using SongLoaderPlugin;
  4. using SongLoaderPlugin.OverrideClasses;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text.RegularExpressions;
  11. using UnityEngine;
  12. namespace SongBrowserPlugin
  13. {
  14. class FolderBeatMapData : BeatmapData
  15. {
  16. public FolderBeatMapData(BeatmapLineData[] beatmapLinesData, BeatmapEventData[] beatmapEventData) :
  17. base(beatmapLinesData, beatmapEventData)
  18. {
  19. }
  20. }
  21. class FolderBeatMapDataSO : BeatmapDataSO
  22. {
  23. public FolderBeatMapDataSO()
  24. {
  25. BeatmapLineData lineData = new BeatmapLineData();
  26. lineData.beatmapObjectsData = new BeatmapObjectData[0];
  27. this._beatmapData = new FolderBeatMapData(
  28. new BeatmapLineData[1]
  29. {
  30. lineData
  31. },
  32. new BeatmapEventData[1]
  33. {
  34. new BeatmapEventData(0, BeatmapEventType.Event0, 0)
  35. });
  36. }
  37. }
  38. class FolderLevel : StandardLevelSO
  39. {
  40. public void Init(String relativePath, String name, Sprite coverImage)
  41. {
  42. _songName = name;
  43. _songSubName = "";
  44. _songAuthorName = "Folder";
  45. _levelID = $"Folder_{relativePath}";
  46. var beatmapData = new FolderBeatMapDataSO();
  47. var difficultyBeatmaps = new List<CustomLevel.CustomDifficultyBeatmap>();
  48. var newDiffBeatmap = new CustomLevel.CustomDifficultyBeatmap(this, LevelDifficulty.Easy, 0, 0, beatmapData);
  49. difficultyBeatmaps.Add(newDiffBeatmap);
  50. var sceneInfo = Resources.Load<SceneInfo>("SceneInfo/" + "DefaultEnvironment" + "SceneInfo");
  51. this.InitFull(_levelID, _songName, _songSubName, _songAuthorName, SongLoaderPlugin.SongLoader.TemporaryAudioClip, 1, 1, 1, 1, 1, 1, 1, coverImage, difficultyBeatmaps.ToArray(), sceneInfo);
  52. this.InitData();
  53. }
  54. }
  55. class DirectoryNode
  56. {
  57. public string Key { get; private set; }
  58. public Dictionary<String, DirectoryNode> Nodes;
  59. public List<StandardLevelSO> Levels;
  60. public DirectoryNode(String key)
  61. {
  62. Key = key;
  63. Nodes = new Dictionary<string, DirectoryNode>();
  64. Levels = new List<StandardLevelSO>();
  65. }
  66. }
  67. public class SongBrowserModel
  68. {
  69. private const String CUSTOM_SONGS_DIR = "CustomSongs";
  70. private DateTime EPOCH = new DateTime(1970, 1, 1);
  71. private Logger _log = new Logger("SongBrowserModel");
  72. // song_browser_settings.xml
  73. private SongBrowserSettings _settings;
  74. // song list management
  75. private List<StandardLevelSO> _filteredSongs;
  76. private List<StandardLevelSO> _sortedSongs;
  77. private List<StandardLevelSO> _originalSongs;
  78. private Dictionary<String, SongLoaderPlugin.OverrideClasses.CustomLevel> _levelIdToCustomLevel;
  79. //private SongLoaderPlugin.OverrideClasses.CustomLevelCollectionSO _gameplayModeCollection;
  80. private Dictionary<String, double> _cachedLastWriteTimes;
  81. private Dictionary<string, int> _weights;
  82. private Dictionary<string, ScoreSaberData> _ppMapping = null;
  83. private Dictionary<String, DirectoryNode> _directoryTree;
  84. private Stack<DirectoryNode> _directoryStack = new Stack<DirectoryNode>();
  85. private GameplayMode _currentGamePlayMode;
  86. public static Action<List<CustomLevel>> didFinishProcessingSongs;
  87. /// <summary>
  88. /// Toggle whether inverting the results.
  89. /// </summary>
  90. public bool InvertingResults { get; private set; }
  91. /// <summary>
  92. /// Get the settings the model is using.
  93. /// </summary>
  94. public SongBrowserSettings Settings
  95. {
  96. get
  97. {
  98. return _settings;
  99. }
  100. }
  101. /// <summary>
  102. /// Get the sorted song list for the current working directory.
  103. /// </summary>
  104. public List<StandardLevelSO> SortedSongList
  105. {
  106. get
  107. {
  108. return _sortedSongs;
  109. }
  110. }
  111. /// <summary>
  112. /// Map LevelID to Custom Level info.
  113. /// </summary>
  114. public Dictionary<String, SongLoaderPlugin.OverrideClasses.CustomLevel> LevelIdToCustomSongInfos
  115. {
  116. get
  117. {
  118. return _levelIdToCustomLevel;
  119. }
  120. }
  121. public Dictionary<string, ScoreSaberData> PpMapping
  122. {
  123. get
  124. {
  125. return _ppMapping;
  126. }
  127. }
  128. /// <summary>
  129. /// How deep is the directory stack.
  130. /// </summary>
  131. public int DirStackSize
  132. {
  133. get
  134. {
  135. return _directoryStack.Count;
  136. }
  137. }
  138. /// <summary>
  139. /// Get the last selected (stored in settings) level id.
  140. /// </summary>
  141. public String LastSelectedLevelId
  142. {
  143. get
  144. {
  145. return _settings.currentLevelId;
  146. }
  147. set
  148. {
  149. _settings.currentLevelId = value;
  150. _settings.Save();
  151. }
  152. }
  153. /// <summary>
  154. /// Get the last known directory the user visited.
  155. /// </summary>
  156. public String CurrentDirectory
  157. {
  158. get
  159. {
  160. return _settings.currentDirectory;
  161. }
  162. set
  163. {
  164. _settings.currentDirectory = value;
  165. _settings.Save();
  166. }
  167. }
  168. private Playlist _currentPlaylist;
  169. /// <summary>
  170. /// Manage the current playlist if one exists.
  171. /// </summary>
  172. public Playlist CurrentPlaylist
  173. {
  174. get
  175. {
  176. if (_currentPlaylist == null)
  177. {
  178. _currentPlaylist = PlaylistsReader.ParsePlaylist(this._settings.currentPlaylistFile);
  179. }
  180. return _currentPlaylist;
  181. }
  182. set
  183. {
  184. _settings.currentPlaylistFile = value.playlistPath;
  185. _currentPlaylist = value;
  186. }
  187. }
  188. /// <summary>
  189. /// Constructor.
  190. /// </summary>
  191. public SongBrowserModel()
  192. {
  193. _cachedLastWriteTimes = new Dictionary<String, double>();
  194. // Weights used for keeping the original songs in order
  195. // Invert the weights from the game so we can order by descending and make LINQ work with us...
  196. /* Level4, Level2, Level9, Level5, Level10, Level6, Level7, Level1, Level3, Level8, Level11 */
  197. _weights = new Dictionary<string, int>
  198. {
  199. ["Level4"] = 11,
  200. ["Level2"] = 10,
  201. ["Level9"] = 9,
  202. ["Level5"] = 8,
  203. ["Level10"] = 7,
  204. ["Level6"] = 6,
  205. ["Level7"] = 5,
  206. ["Level1"] = 4,
  207. ["Level3"] = 3,
  208. ["Level8"] = 2,
  209. ["Level11"] = 1,
  210. ["Level4OneSaber"] = 12,
  211. ["Level1OneSaber"] = 11,
  212. ["Level2OneSaber"] = 10,
  213. ["Level9OneSaber"] = 9,
  214. ["Level7OneSaber"] = 8,
  215. };
  216. }
  217. /// <summary>
  218. /// Init this model.
  219. /// </summary>
  220. /// <param name="songSelectionMasterView"></param>
  221. /// <param name="songListViewController"></param>
  222. public void Init()
  223. {
  224. _settings = SongBrowserSettings.Load();
  225. _log.Info("Settings loaded, sorting mode is: {0}", _settings.sortMode);
  226. }
  227. /// <summary>
  228. /// Easy invert of toggling.
  229. /// </summary>
  230. public void ToggleInverting()
  231. {
  232. this.InvertingResults = !this.InvertingResults;
  233. }
  234. /// <summary>
  235. /// Get the song cache from the game.
  236. /// TODO: This might not even be necessary anymore. Need to test interactions with BeatSaverDownloader.
  237. /// </summary>
  238. public void UpdateSongLists(GameplayMode gameplayMode)
  239. {
  240. if (SongLoader.CustomLevels.Count > 0)
  241. {
  242. SongBrowserApplication.MainProgressBar.ShowMessage("Processing songs...");
  243. }
  244. _currentGamePlayMode = gameplayMode;
  245. String customSongsPath = Path.Combine(Environment.CurrentDirectory, CUSTOM_SONGS_DIR);
  246. String cachedSongsPath = Path.Combine(customSongsPath, ".cache");
  247. DateTime currentLastWriteTIme = File.GetLastWriteTimeUtc(customSongsPath);
  248. IEnumerable<string> directories = Directory.EnumerateDirectories(customSongsPath, "*.*", SearchOption.AllDirectories);
  249. // Get LastWriteTimes
  250. foreach (var level in SongLoader.CustomLevels)
  251. {
  252. //_log.Debug("Fetching LastWriteTime for {0}", slashed_dir);
  253. _cachedLastWriteTimes[level.levelID] = (File.GetLastWriteTimeUtc(level.customSongInfo.path) - EPOCH).TotalMilliseconds;
  254. }
  255. // Update song Infos, directory tree, and sort
  256. this.UpdateSongInfos(_currentGamePlayMode);
  257. this.UpdatePpMappings();
  258. this.UpdateDirectoryTree(customSongsPath);
  259. this.ProcessSongList();
  260. if (SongLoader.CustomLevels.Count > 0)
  261. {
  262. didFinishProcessingSongs?.Invoke(SongLoader.CustomLevels);
  263. }
  264. }
  265. /// <summary>
  266. /// Get the song infos from SongLoaderPluging
  267. /// </summary>
  268. private void UpdateSongInfos(GameplayMode gameplayMode)
  269. {
  270. _log.Trace("UpdateSongInfos for Gameplay Mode {0}", gameplayMode);
  271. // Get the level collection from song loader
  272. LevelCollectionsForGameplayModes levelCollections = Resources.FindObjectsOfTypeAll<LevelCollectionsForGameplayModes>().FirstOrDefault();
  273. List<LevelCollectionsForGameplayModes.LevelCollectionForGameplayMode> levelCollectionsForGameModes = ReflectionUtil.GetPrivateField<LevelCollectionsForGameplayModes.LevelCollectionForGameplayMode[]>(levelCollections, "_collections").ToList();
  274. _originalSongs = levelCollections.GetLevels(gameplayMode).ToList();
  275. _sortedSongs = _originalSongs;
  276. _levelIdToCustomLevel = new Dictionary<string, SongLoaderPlugin.OverrideClasses.CustomLevel>();
  277. foreach (var level in SongLoader.CustomLevels)
  278. {
  279. if (!_levelIdToCustomLevel.Keys.Contains(level.levelID))
  280. _levelIdToCustomLevel.Add(level.levelID, level);
  281. }
  282. _log.Debug("Song Browser knows about {0} songs from SongLoader...", _originalSongs.Count);
  283. }
  284. /// <summary>
  285. /// Parse the current pp data file.
  286. /// </summary>
  287. private void UpdatePpMappings()
  288. {
  289. _log.Trace("UpdatePpMappings()");
  290. ScoreSaberDataFile ppDataFile = ScoreSaberDatabaseDownloader.Instance.ScoreSaberDataFile;
  291. _ppMapping = new Dictionary<string, ScoreSaberData>();
  292. // bail
  293. if (ppDataFile == null)
  294. {
  295. _log.Warning("Cannot fetch song difficulty data tsv file from DuoVR");
  296. return;
  297. }
  298. foreach (var level in SongLoader.CustomLevels)
  299. {
  300. ScoreSaberData ppData = null;
  301. Regex versionRegex = new Regex(@".*/(?<version>[0-9]*-[0-9]*)/");
  302. Match m = versionRegex.Match(level.customSongInfo.path);
  303. if (m.Success)
  304. {
  305. String version = m.Groups["version"].Value;
  306. if (ppDataFile.SongVersionToPp.ContainsKey(version))
  307. {
  308. ppData = ppDataFile.SongVersionToPp[version];
  309. }
  310. }
  311. if (ppData == null)
  312. {
  313. if (ppDataFile.SongVersionToPp.ContainsKey(level.songName))
  314. {
  315. ppData = ppDataFile.SongVersionToPp[level.songName];
  316. }
  317. }
  318. if (ppData != null)
  319. {
  320. //_log.Debug("{0} = {1}pp", level.songName, pp);
  321. _ppMapping.Add(level.levelID, ppData);
  322. }
  323. }
  324. }
  325. /// <summary>
  326. /// Make the directory tree.
  327. /// </summary>
  328. /// <param name="customSongsPath"></param>
  329. private void UpdateDirectoryTree(String customSongsPath)
  330. {
  331. // Determine folder mapping
  332. Uri customSongDirUri = new Uri(customSongsPath);
  333. _directoryTree = new Dictionary<string, DirectoryNode>();
  334. _directoryTree[CUSTOM_SONGS_DIR] = new DirectoryNode(CUSTOM_SONGS_DIR);
  335. if (_settings.folderSupportEnabled)
  336. {
  337. foreach (StandardLevelSO level in _originalSongs)
  338. {
  339. AddItemToDirectoryTree(customSongDirUri, level);
  340. }
  341. }
  342. else
  343. {
  344. _directoryTree[CUSTOM_SONGS_DIR].Levels = _originalSongs;
  345. }
  346. // Determine starting location
  347. DirectoryNode currentNode = _directoryTree[CUSTOM_SONGS_DIR];
  348. _directoryStack.Push(currentNode);
  349. // Try to navigate directory path
  350. if (!String.IsNullOrEmpty(this.CurrentDirectory))
  351. {
  352. String[] paths = this.CurrentDirectory.Split('/');
  353. for (int i = 1; i < paths.Length; i++)
  354. {
  355. if (currentNode.Nodes.ContainsKey(paths[i]))
  356. {
  357. currentNode = currentNode.Nodes[paths[i]];
  358. _directoryStack.Push(currentNode);
  359. }
  360. }
  361. }
  362. //PrintDirectory(_directoryTree[CUSTOM_SONGS_DIR], 1);
  363. }
  364. /// <summary>
  365. /// Add a song to directory tree. Determine its place in the tree by walking the split directory path.
  366. /// </summary>
  367. /// <param name="customSongDirUri"></param>
  368. /// <param name="level"></param>
  369. private void AddItemToDirectoryTree(Uri customSongDirUri, StandardLevelSO level)
  370. {
  371. //_log.Debug("Processing item into directory tree: {0}", level.levelID);
  372. DirectoryNode currentNode = _directoryTree[CUSTOM_SONGS_DIR];
  373. // Just add original songs to root and bail
  374. if (level.levelID.Length < 32)
  375. {
  376. currentNode.Levels.Add(level);
  377. return;
  378. }
  379. CustomSongInfo songInfo = _levelIdToCustomLevel[level.levelID].customSongInfo;
  380. Uri customSongUri = new Uri(songInfo.path);
  381. Uri pathDiff = customSongDirUri.MakeRelativeUri(customSongUri);
  382. string relPath = Uri.UnescapeDataString(pathDiff.OriginalString);
  383. string[] paths = relPath.Split('/');
  384. Sprite folderIcon = Base64Sprites.Base64ToSprite(Base64Sprites.FolderIcon);
  385. // Prevent cache directory from building into the tree, will add all its leafs to root.
  386. bool forceIntoRoot = false;
  387. //_log.Debug("Processing path: {0}", songInfo.path);
  388. if (paths.Length > 2)
  389. {
  390. forceIntoRoot = paths[1].Contains(".cache");
  391. Regex r = new Regex(@"^\d{1,}-\d{1,}");
  392. if (r.Match(paths[1]).Success)
  393. {
  394. forceIntoRoot = true;
  395. }
  396. }
  397. for (int i = 1; i < paths.Length; i++)
  398. {
  399. string path = paths[i];
  400. if (path == Path.GetFileName(songInfo.path))
  401. {
  402. //_log.Debug("\tLevel Found Adding {0}->{1}", currentNode.Key, level.levelID);
  403. currentNode.Levels.Add(level);
  404. break;
  405. }
  406. else if (currentNode.Nodes.ContainsKey(path))
  407. {
  408. currentNode = currentNode.Nodes[path];
  409. }
  410. else if (!forceIntoRoot)
  411. {
  412. currentNode.Nodes[path] = new DirectoryNode(path);
  413. FolderLevel folderLevel = new FolderLevel();
  414. folderLevel.Init(relPath, path, folderIcon);
  415. //_log.Debug("\tAdding folder level {0}->{1}", currentNode.Key, path);
  416. currentNode.Levels.Add(folderLevel);
  417. _cachedLastWriteTimes[folderLevel.levelID] = (File.GetLastWriteTimeUtc(relPath) - EPOCH).TotalMilliseconds;
  418. currentNode = currentNode.Nodes[path];
  419. }
  420. }
  421. }
  422. /// <summary>
  423. /// Push a dir onto the stack.
  424. /// </summary>
  425. public void PushDirectory(IStandardLevel level)
  426. {
  427. DirectoryNode currentNode = _directoryStack.Peek();
  428. _log.Debug("Pushing directory {0}", level.songName);
  429. if (!currentNode.Nodes.ContainsKey(level.songName))
  430. {
  431. _log.Debug("Trying to push a directory that doesn't exist at this level.");
  432. return;
  433. }
  434. _directoryStack.Push(currentNode.Nodes[level.songName]);
  435. this.CurrentDirectory = level.levelID;
  436. ProcessSongList();
  437. }
  438. /// <summary>
  439. /// Pop a dir off the stack.
  440. /// </summary>
  441. public void PopDirectory()
  442. {
  443. if (_directoryStack.Count > 1)
  444. {
  445. _directoryStack.Pop();
  446. String currentDir = "";
  447. foreach (DirectoryNode node in _directoryStack)
  448. {
  449. currentDir = node.Key + "/" + currentDir;
  450. }
  451. this.CurrentDirectory = "Folder_" + currentDir;
  452. ProcessSongList();
  453. }
  454. }
  455. /// <summary>
  456. /// Print the directory structure parsed.
  457. /// </summary>
  458. /// <param name="node"></param>
  459. /// <param name="depth"></param>
  460. private void PrintDirectory(DirectoryNode node, int depth)
  461. {
  462. Console.WriteLine("Dir: {0}".PadLeft(depth*4, ' '), node.Key);
  463. node.Levels.ForEach(x => Console.WriteLine("{0}".PadLeft((depth + 1)*4, ' '), x.levelID));
  464. foreach (KeyValuePair<string, DirectoryNode> childNode in node.Nodes)
  465. {
  466. PrintDirectory(childNode.Value, depth + 1);
  467. }
  468. }
  469. /// <summary>
  470. /// Sort the song list based on the settings.
  471. /// </summary>
  472. public void ProcessSongList()
  473. {
  474. _log.Trace("ProcessSongList()");
  475. // This has come in handy many times for debugging issues with Newest.
  476. /*foreach (StandardLevelSO level in _originalSongs)
  477. {
  478. if (_levelIdToCustomLevel.ContainsKey(level.levelID))
  479. {
  480. _log.Debug("HAS KEY {0}: {1}", _levelIdToCustomLevel[level.levelID].customSongInfo.path, level.levelID);
  481. }
  482. else
  483. {
  484. _log.Debug("Missing KEY: {0}", level.levelID);
  485. }
  486. }*/
  487. // Playlist filter will load the original songs.
  488. if (this._settings.filterMode == SongFilterMode.Playlist && this.CurrentPlaylist != null)
  489. {
  490. _originalSongs = null;
  491. }
  492. else
  493. {
  494. _log.Debug("Showing songs for directory: {0}", _directoryStack.Peek().Key);
  495. _originalSongs = _directoryStack.Peek().Levels;
  496. }
  497. // filter
  498. _log.Debug("Starting filtering songs...");
  499. Stopwatch stopwatch = Stopwatch.StartNew();
  500. switch (_settings.filterMode)
  501. {
  502. case SongFilterMode.Favorites:
  503. FilterFavorites(_originalSongs);
  504. break;
  505. case SongFilterMode.Search:
  506. FilterSearch(_originalSongs);
  507. break;
  508. case SongFilterMode.Playlist:
  509. FilterPlaylist();
  510. break;
  511. case SongFilterMode.None:
  512. default:
  513. _log.Info("No song filter selected...");
  514. _filteredSongs = _originalSongs;
  515. break;
  516. }
  517. stopwatch.Stop();
  518. _log.Info("Filtering songs took {0}ms", stopwatch.ElapsedMilliseconds);
  519. // sort
  520. _log.Debug("Starting to sort songs...");
  521. stopwatch = Stopwatch.StartNew();
  522. switch (_settings.sortMode)
  523. {
  524. case SongSortMode.Original:
  525. SortOriginal(_filteredSongs);
  526. break;
  527. case SongSortMode.Newest:
  528. SortNewest(_filteredSongs);
  529. break;
  530. case SongSortMode.Author:
  531. SortAuthor(_filteredSongs);
  532. break;
  533. case SongSortMode.PlayCount:
  534. SortPlayCount(_filteredSongs, _currentGamePlayMode);
  535. break;
  536. case SongSortMode.PP:
  537. SortPerformancePoints(_filteredSongs);
  538. break;
  539. case SongSortMode.Difficulty:
  540. SortDifficulty(_filteredSongs);
  541. break;
  542. case SongSortMode.Random:
  543. SortRandom(_filteredSongs);
  544. break;
  545. case SongSortMode.Default:
  546. default:
  547. SortSongName(_filteredSongs);
  548. break;
  549. }
  550. if (this.InvertingResults && _settings.sortMode != SongSortMode.Random)
  551. {
  552. _sortedSongs.Reverse();
  553. }
  554. stopwatch.Stop();
  555. _log.Info("Sorting songs took {0}ms", stopwatch.ElapsedMilliseconds);
  556. //_sortedSongs.ForEach(x => _log.Debug(x.levelID));
  557. }
  558. private void FilterFavorites(List<StandardLevelSO> levels)
  559. {
  560. _log.Info("Filtering song list as favorites");
  561. _filteredSongs = levels
  562. .Where(x => _settings.Favorites.Contains(x.levelID))
  563. .ToList();
  564. }
  565. private void FilterSearch(List<StandardLevelSO> levels)
  566. {
  567. // Make sure we can actually search.
  568. if (this._settings.searchTerms.Count <= 0)
  569. {
  570. _log.Error("Tried to search for a song with no valid search terms...");
  571. SortSongName(levels);
  572. return;
  573. }
  574. string searchTerm = this._settings.searchTerms[0];
  575. if (String.IsNullOrEmpty(searchTerm))
  576. {
  577. _log.Error("Empty search term entered.");
  578. SortSongName(levels);
  579. return;
  580. }
  581. _log.Info("Filtering song list by search term: {0}", searchTerm);
  582. //_originalSongs.ForEach(x => _log.Debug($"{x.songName} {x.songSubName} {x.songAuthorName}".ToLower().Contains(searchTerm.ToLower()).ToString()));
  583. _filteredSongs = levels
  584. .Where(x => $"{x.songName} {x.songSubName} {x.songAuthorName}".ToLower().Contains(searchTerm.ToLower()))
  585. .ToList();
  586. }
  587. private void FilterPlaylist()
  588. {
  589. // bail if no playlist, usually means the settings stored one the user then moved.
  590. if (this.CurrentPlaylist == null)
  591. {
  592. _log.Error("Trying to load a null playlist...");
  593. _filteredSongs = _originalSongs;
  594. return;
  595. }
  596. _log.Debug("Filtering songs for playlist: {0}", this.CurrentPlaylist);
  597. List<String> playlistNameListOrdered = this.CurrentPlaylist.songs.Select(x => x.songName).Distinct().ToList();
  598. Dictionary<String, int> songNameToIndex = playlistNameListOrdered.Select((val, index) => new { Index = index, Value = val }).ToDictionary(i => i.Value, i => i.Index);
  599. HashSet<String> songNames = new HashSet<String>(playlistNameListOrdered);
  600. LevelCollectionsForGameplayModes levelCollections = Resources.FindObjectsOfTypeAll<LevelCollectionsForGameplayModes>().FirstOrDefault();
  601. List<StandardLevelSO> songList = levelCollections.GetLevels(_currentGamePlayMode).Where(x => songNames.Contains(x.songName)).ToList();
  602. _log.Debug("\tMatching songs found for playlist: {0}", songList.Count);
  603. _originalSongs = songList;
  604. _filteredSongs = songList
  605. .OrderBy(x => songNameToIndex[x.songName])
  606. .ToList();
  607. }
  608. private void SortOriginal(List<StandardLevelSO> levels)
  609. {
  610. _log.Info("Sorting song list as original");
  611. _sortedSongs = levels;
  612. }
  613. private void SortNewest(List<StandardLevelSO> levels)
  614. {
  615. _log.Info("Sorting song list as newest.");
  616. _sortedSongs = levels
  617. .OrderBy(x => _weights.ContainsKey(x.levelID) ? _weights[x.levelID] : 0)
  618. .ThenByDescending(x => x.levelID.StartsWith("Level") ? _weights[x.levelID] : _cachedLastWriteTimes[x.levelID])
  619. .ToList();
  620. }
  621. private void SortAuthor(List<StandardLevelSO> levels)
  622. {
  623. _log.Info("Sorting song list by author");
  624. _sortedSongs = levels
  625. .OrderBy(x => x.songAuthorName)
  626. .ThenBy(x => x.songName)
  627. .ToList();
  628. }
  629. private void SortPlayCount(List<StandardLevelSO> levels, GameplayMode gameplayMode)
  630. {
  631. _log.Info("Sorting song list by playcount");
  632. // Build a map of levelId to sum of all playcounts and sort.
  633. PlayerDynamicData playerData = GameDataModel.instance.gameDynamicData.GetCurrentPlayerDynamicData();
  634. IEnumerable<LevelDifficulty> difficultyIterator = Enum.GetValues(typeof(LevelDifficulty)).Cast<LevelDifficulty>();
  635. Dictionary<string, int> levelIdToPlayCount = new Dictionary<string, int>();
  636. foreach (var level in levels)
  637. {
  638. if (!levelIdToPlayCount.ContainsKey(level.levelID))
  639. {
  640. // Skip folders
  641. if (level.levelID.StartsWith("Folder_"))
  642. {
  643. levelIdToPlayCount.Add(level.levelID, 0);
  644. }
  645. else
  646. {
  647. int playCountSum = 0;
  648. foreach (LevelDifficulty difficulty in difficultyIterator)
  649. {
  650. PlayerLevelStatsData stats = playerData.GetPlayerLevelStatsData(level.levelID, difficulty, gameplayMode);
  651. playCountSum += stats.playCount;
  652. }
  653. levelIdToPlayCount.Add(level.levelID, playCountSum);
  654. }
  655. }
  656. }
  657. _sortedSongs = levels
  658. .OrderByDescending(x => levelIdToPlayCount[x.levelID])
  659. .ThenBy(x => x.songName)
  660. .ToList();
  661. }
  662. private void SortPerformancePoints(List<StandardLevelSO> levels)
  663. {
  664. _log.Info("Sorting song list by performance points...");
  665. _sortedSongs = levels
  666. .OrderByDescending(x => _ppMapping.ContainsKey(x.levelID) ? _ppMapping[x.levelID].maxPp : 0)
  667. .ToList();
  668. }
  669. private void SortDifficulty(List<StandardLevelSO> levels)
  670. {
  671. _log.Info("Sorting song list by random");
  672. System.Random rnd = new System.Random(Guid.NewGuid().GetHashCode());
  673. Dictionary<LevelDifficulty, int> difficultyWeights = new Dictionary<LevelDifficulty, int>
  674. {
  675. [LevelDifficulty.Easy] = int.MaxValue - 4,
  676. [LevelDifficulty.Normal] = int.MaxValue - 3,
  677. [LevelDifficulty.Hard] = int.MaxValue - 2,
  678. [LevelDifficulty.Expert] = int.MaxValue - 1,
  679. [LevelDifficulty.ExpertPlus] = int.MaxValue,
  680. };
  681. IEnumerable<LevelDifficulty> difficultyIterator = Enum.GetValues(typeof(LevelDifficulty)).Cast<LevelDifficulty>();
  682. Dictionary<string, int> levelIdToDifficultyValue = new Dictionary<string, int>();
  683. foreach (var level in levels)
  684. {
  685. if (!levelIdToDifficultyValue.ContainsKey(level.levelID))
  686. {
  687. // Skip folders
  688. if (level.levelID.StartsWith("Folder_"))
  689. {
  690. levelIdToDifficultyValue.Add(level.levelID, 0);
  691. }
  692. else
  693. {
  694. int difficultyValue = 0;
  695. foreach (LevelDifficulty difficulty in difficultyIterator)
  696. {
  697. IStandardLevelDifficultyBeatmap beatmap = level.GetDifficultyLevel(difficulty);
  698. if (beatmap != null)
  699. {
  700. difficultyValue += difficultyWeights[difficulty];
  701. break;
  702. }
  703. }
  704. levelIdToDifficultyValue.Add(level.levelID, difficultyValue);
  705. }
  706. }
  707. }
  708. _sortedSongs = levels
  709. .OrderBy(x => levelIdToDifficultyValue[x.levelID])
  710. .ThenBy(x => x.songName)
  711. .ToList();
  712. }
  713. private void SortRandom(List<StandardLevelSO> levels)
  714. {
  715. _log.Info("Sorting song list by random");
  716. System.Random rnd = new System.Random(Guid.NewGuid().GetHashCode());
  717. _sortedSongs = levels
  718. .OrderBy(x => rnd.Next())
  719. .ToList();
  720. }
  721. private void SortSongName(List<StandardLevelSO> levels)
  722. {
  723. _log.Info("Sorting song list as default (songName)");
  724. _sortedSongs = levels
  725. .OrderBy(x => x.songName)
  726. .ThenBy(x => x.songAuthorName)
  727. .ToList();
  728. }
  729. }
  730. }