Пример #1
0
 public void CreateButtonContent(BeatMap beatmaps)
 {
     for (int i = 0; i < beatmaps.map.Length; i++)
     {
         for (int j = 0; j < beatmap.map [i].notes.Length; j++)
         {
             Vector3    tempV     = new Vector3(beatmaps.map[i].notes[j].x, beatmaps.map[i].notes[j].y, beatmaps.map[i].notes[j].z);
             GameObject newButton = Instantiate(noteButton) as GameObject;
             newButton.transform.SetParent(gameObject.transform, false);
             newButton.GetComponent <RectTransform> ().position = Vector3.zero;
             newButton.GetComponentInChildren <Text>().text     = beatmaps.map[i].t.ToString() + "," + beatmaps.map[i].notes[j].type.ToString();
             newButton.GetComponent <Button> ().onClick.AddListener(delegate {
                 // menuCanvas.GetComponent<MenuManager> ().ToggleMenu(); move the GameController.StartGame()
                 AS.GetComponent <MusicControl>().JumpAndPause(
                     float.Parse(newButton.GetComponentInChildren <Text> ().text.Substring(0,
                                                                                           newButton.GetComponentInChildren <Text> ().text.IndexOf(','))),
                     newButton.transform.GetSiblingIndex(),
                     tempV
                     );
             });
         }
     }
     gameObject.GetComponent <RectTransform>().sizeDelta = new Vector2(
         gameObject.GetComponent <RectTransform>().sizeDelta.x,
         noteButton.GetComponent <LayoutElement>().minHeight *beatmap.map.Length);
 }
Пример #2
0
        private void ExecuteSelectedCommand(BeatMap map)
        {
            var navParams = new NavigationParameters
            {
                { "BeatMap", map }
            };

            regionManager.RequestNavigate(Regions.ContentRegion, nameof(MapDetailView), navParams);
        }
Пример #3
0
 private void Start()
 {
     instance = this;
     beats    = GetComponentsInChildren <Beat>();
     foreach (Beat b in beats)
     {
         setupBeat(b);
     }
 }
Пример #4
0
 void removeBeatMapListener()
 {
     if (selectedBeatMap != null && selectedBeatMapEntryController != null)
     {
         selectedBeatMap.delete_self(Application.persistentDataPath);
         selectedBeatMapEntryController.destroy();
     }
     selectedBeatMap = null;
     selectedBeatMapEntryController = null;
 }
Пример #5
0
    /// <summary>
    /// Spawns enemies at the right time. Used for a non-variable time
    /// </summary>
    private void FixedUpdate()
    {
        // Check to see if the game is over
        if (gameOver)
        {
            HandleGameOver();
        }

        currentGameTime += Time.deltaTime;


        #region User Inputted Map
        // Loop through every map we need to look at
        for (int i = 0; i < listOfMaps.Count; i++)
        {
            // Set our map for this loop
            BeatMap map = listOfMaps[i];

            if (map.mapPos == map.beatMap.Count)
            {
                continue;
            }
            map.sinceLastSpawn += Time.deltaTime;

            // in the map, get the next beat and compare it to our sinceLastSpawn
            // if the sinceLastSpawn is > the nextBeat time,
            if (map.sinceLastSpawn >= map.untilNextSpawn)
            {
                // update our timeSinceLastSpawn to be (it - nextBeatTime)
                map.sinceLastSpawn -= map.untilNextSpawn;

                // if this isn't our offset beat or the end of the map
                if (map.mapPos != 0 && map.mapPos != map.beatMap.Count)
                {
                    // spawn in the beat(timeSinceLastSpawn, left)
                    SpawnEnemy(map.sinceLastSpawn, map.left);
                }

                // Check to see if we just hit the last beat
                if (map.mapPos == map.beatMap.Count - 1)
                {
                    map.mapPos++;
                    continue;
                }
                // update our mapPos+1
                map.mapPos++;

                // update BeatMap's untilNextSpawn
                map.untilNextSpawn = map.beatMap[map.mapPos] - map.beatMap[map.mapPos - 1];
            }
            // otherwise, we don't care
        }
        #endregion
    }
Пример #6
0
    public static BeatMap loadBeatMap(string fn) //Todo rename this class to a static "BeatMapLoader" class
    {
        //see https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/walkthrough-persisting-an-object-in-visual-studio
        Stream          openFileStream = File.OpenRead(fn);
        BinaryFormatter deserializer   = new BinaryFormatter();
        BeatMap         beatMap        = (BeatMap)deserializer.Deserialize(openFileStream);

        Debug.Log("Beatmap loaded");
        Debug.Log(beatMap.song_meta.title);
        openFileStream.Close();
        return(beatMap);
    }
Пример #7
0
    // Start is called before the first frame update
    public void Start()
    {
        mapsContent         = mapsContent.GetComponent <Transform>();
        leaderBoard         = leaderBoard.GetComponent <Text>();
        selectedBeatMapText = selectedBeatMapText.GetComponent <Text>();
        removeBeatMapButton = removeBeatMapButton.GetComponent <Button>();
        removeBeatMapButton.onClick.AddListener(removeBeatMapListener);
        string beatMapDir = Application.persistentDataPath + "/BeatMaps/";

        Debug.Log(beatMapDir);
        Directory.CreateDirectory(beatMapDir); //create if it does not exist

        List <BeatMap> beatMaps = new List <BeatMap>();

        foreach (string fileName in Directory.EnumerateFiles(beatMapDir))
        {
            //see https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/serialization/walkthrough-persisting-an-object-in-visual-studio
            if (!fileName.EndsWith(".dat"))
            {
                continue;
            }
            BeatMap beatMap = BeatMap.loadBeatMap(fileName);
            beatMaps.Add(beatMap);
        }

        //sort beatmaps
        beatMaps.Sort((x, y) => DateTime.Compare(y.lastPlayed, x.lastPlayed));

        foreach (BeatMap beatMap in beatMaps)
        {
            GameObject             beatMapPanel = (GameObject)Instantiate(prefab, new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 0), mapsContent);
            BeatMapEntryController controller   = beatMapPanel.GetComponentInChildren <BeatMapEntryController>();
            controllers.Add(controller);
            panes.Add(beatMapPanel);
            controller.instantiateBeatMaps = this;
            controller.fileName            = beatMapDir + beatMap.fileName;
            controller.setCoverArt(beatMap.songFilePath + ".png");
            controller.beatMap = beatMap;
            foreach (Text text in beatMapPanel.GetComponentsInChildren <Text>())
            {
                if (text.name == "SongName")
                {
                    text.text = beatMap.song_meta.title + " by " + beatMap.song_meta.artist;
                }
                else if (text.name == "SongInfo")
                {
                    text.text = "Times Played: " + beatMap.timesPlayed + "  Last Played: " + (beatMap.timesPlayed == 0 ? "never" : beatMap.lastPlayed.ToShortDateString() + " " + beatMap.lastPlayed.ToShortTimeString())
                                + "\nRNG Seed: " + beatMap.get_settings().rng_seed.ToString() + " Duration: " + (Mathf.FloorToInt(beatMap.get_song_info().length) / 60f).ToString("0.0") + " minutes";
                }
            }
        }
    }
Пример #8
0
    public BeatMap GenerateBeatMap()
    {
        BeatMap beatMap = beatMapBase.ShallowClone();

        beatMap.beatObjectList.Clear();

        foreach (int timestampInt in timestampList)
        {
            BeatObject beatObject = new BeatObject();
            beatObject.beatTime = timestampInt / 1000f;
            beatMap.beatObjectList.Add(beatObject);
        }

        return(beatMap);
    }
Пример #9
0
 // CONSTRUCTOR //
 public BeatManager(float bpm, AudioClip song)
 {
     this.song             = song;
     currentBeat           = 0;
     lastBeat              = 0;
     lastBeatBarPlaced     = 0;
     rewinding             = false;
     this.bpm              = bpm;
     lengthOfSongInSeconds = song.length;
     beatsPerSecond        = (bpm / 60);
     bars         = new List <BeatBar>();
     destroyAtZ   = BeatMap.destroyNoteAtZ;
     spawnAtZ     = BeatMap.GetSpawnPosition(new Vector2(0, 0)).z;
     BarContainer = new GameObject("BarContainer");
 }
Пример #10
0
    //for now, more info == scoreboard
    public void moreInfo(BeatMap beatMap, BeatMapEntryController controller)
    {
        selectedBeatMap = beatMap;
        selectedBeatMapEntryController = controller;
        selectedBeatMapText.text       = "Selected: " + beatMap.song_meta.title + " by " + beatMap.song_meta.artist + " (" + beatMap.get_settings().rng_seed.ToString() + ")";
        leaderBoard.text = "";
        List <WinDataClass> wins = beatMap.getScoreBoard();

        if (wins.Count == 0)
        {
            leaderBoard.text = "No recorded scores.";
        }
        foreach (WinDataClass win in wins)
        {
            leaderBoard.text += " " + win.score.ToString() + " on: " + win.date.ToShortDateString() + "\n";
        }
    }
Пример #11
0
    public override void Start()
    {
        base.Start();

        gradeList = new List <BeatObjectGrade>();

        _audioManager = AudioManager.GetInstance();
        _beatMap      = beatMapData.GenerateBeatMap();
        _state        = State.Beginning;

        _audioSource      = GetComponent <AudioSource>();
        _audioSource.clip = beatMapData.GetAudioClip();

        _characterData = playerData.GetRandomCharacter();
        _currentDialog = beginningDialog;
        _currentDialog.ApplyCharacter(_characterData);
        _currentDialog.Display(playerData, _characterData);
    }
Пример #12
0
        public static BeatSaberJSONClass SaveToDisk(BeatMapData data)
        {
            Debug.LogWarning("Save to disk called with note count " + data.notes.Length);
            Debug.LogWarning("data song file name - " + data.songFileName);
            BeatSaberJSONClass beatSaberJSON = BeatSaberJSONClass.ConvertUnityDataToBSData(data);
            string             levelJSON     = JsonUtility.ToJson(beatSaberJSON.level, false);

            BeatSaberJSONClass.InfoJSON info = GenerateInfoFile(data);
            string infoJSON   = JsonUtility.ToJson(info, false);
            string songFolder = BeatMap.savePath + data.songName + "/";
            string levelFileName;

            if (data.difficulty == BeatSaveDifficulty.Easy)
            {
                levelFileName = "Easy.json";
            }
            else if (data.difficulty == BeatSaveDifficulty.Normal)
            {
                levelFileName = "Normal.json";
            }
            else if (data.difficulty == BeatSaveDifficulty.Hard)
            {
                levelFileName = "Hard.json";
            }
            else if (data.difficulty == BeatSaveDifficulty.Expert)
            {
                levelFileName = "Expert.json";
            }
            else
            {
                levelFileName = "ExpertPlus.json";
            }
            if (!Directory.Exists(songFolder))
            {
                Directory.CreateDirectory(songFolder);
            }
            string levelOutputPath = songFolder + levelFileName;
            string infoOutputPath  = songFolder + "info.json";

            WriteToDisk(infoOutputPath, infoJSON);
            WriteToDisk(levelOutputPath, levelJSON);
            BeatMap.Log("Save complete to file " + levelOutputPath);
            return(beatSaberJSON);
        }
Пример #13
0
    private void startBeat()
    {
        // write the beatmap
        string jsonString = LoadResourceTextfile(musicClip);

        currentBeatmap = JsonUtility.FromJson <BeatMap>(jsonString);

        // use the beatmap to generate the beat queue, apply offset if there is one
        beatQueue = new Priority_Queue.SimplePriorityQueue <int>(); // make an empty queue
        // enqueue all the beats
        for (int i = 0; i < currentBeatmap.beatmap.Length; i++)
        {
            beatQueue.Enqueue(currentBeatmap.beatmap[i] + currentBeatmap.offset, currentBeatmap.beatmap[i] + currentBeatmap.offset);
        }

        // reset beat delta time
        beatDeltatime = 0;
        nextBeat      = 0;

        musicPlaying = true; // this starts the update incrementing delta time
    }
Пример #14
0
        public async Task DownloadMap(CancellationToken cancellationToken, BeatMap map)
        {
            var folderName      = MapHelper.GetFormattedMapName(map.MapKey, map.Metadata.SongName, map.Metadata.SongAuthor);
            var levelsDirectory = beatSaberService.GetCustomLevelsDirectory();
            var savePath        = Path.Combine(levelsDirectory, folderName);

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/zip"));
            var response = await client.GetAsync(map.DownloadUrl, cancellationToken);

            var tempPath = Path.Combine(Path.GetTempPath(), "SaberStudio", folderName);
            var zipFile  = Path.Combine(tempPath, folderName + ".zip");

            FileHelper.CreateFolder(tempPath);

            await using var stream = await response.Content.ReadAsStreamAsync();

            await FileHelper.CreateFileFromStream(stream, zipFile, true);

            FileHelper.ExtractZip(zipFile, savePath);
            eventAggregator.GetEvent <MapLibraryChangedEvent>().Publish();
        }
Пример #15
0
    private void Update()
    {
        if (musicPlaying)
        {
            if (!MusicSource.isPlaying)
            {
                musicLooper();
            }

            // check if we've reached the next beat in the queue
            beatDeltatime += Time.deltaTime;

            if (getBeatDeltaTime() > nextBeat)
            {
                // hit beat, fire and setup next one
                beat();
                if (beatQueue.Count > 0)
                {
                    nextBeat = beatQueue.Dequeue();
                }
                else
                {
                    // if we reached the end, just reset the beat delta time and start over
                    beatDeltatime = 0;
                    nextBeat      = 0;
                    // don't forget to re-write the queue
                    string jsonString = LoadResourceTextfile("beatmap_stage_music_slow");
                    currentBeatmap = JsonUtility.FromJson <BeatMap>(jsonString);
                    for (int i = 0; i < currentBeatmap.beatmap.Length; i++)
                    {
                        beatQueue.Enqueue(currentBeatmap.beatmap[i], currentBeatmap.beatmap[i]);
                    }
                }
            }
        }
    }
Пример #16
0
 public void SetData(BeatObject beatObject, BeatMap beatMap)
 {
     _beatMap    = beatMap;
     _beatObject = beatObject;
 }
Пример #17
0
    // float[] getCombinedSamplesWeb (ref float[] samples) {
    // }

    //The B(eat) G(enerating) A(lgorithim)
    //Background thread to create the beatmap
    void algorithim()
    {
        Debug.Log("algo");
        //float[] samples = //getCombinedSamples(ref song_info.samples, song_info.sampleCount, song_info.channels);

        float[] samples = song_info.samples;

        Debug.Log("Song samples coverted to mono");

        int finalArraySize = song_info.sampleCount / settings.n_bins;

        Debug.Log(finalArraySize);
        output.fftData         = new float[finalArraySize][];
        output.flux            = new float[finalArraySize];
        output.flux2           = new float[finalArraySize];
        output.peaks           = new float[finalArraySize];
        output.peaks2          = new float[finalArraySize];
        output.threshold       = new float[finalArraySize];
        output.peakThreshold   = new float[finalArraySize];
        output.drifts          = new float[finalArraySize];
        output.flySectionIndex = 0;
        FFTProvider fftProvider = new DSPLibFFTProvider(settings.n_bins);
        WINDOW_TYPE fftWindow   = WINDOW_TYPE.Hamming;

        Debug.Log("done allocating large amount of ram");

        //perform fft using N_BINS at a time
        for (int i = 0; i < finalArraySize; i++)
        {
            float[] currSamples = new float[settings.n_bins];
            int     startIndex  = (i * settings.n_bins);
            //Grab the current sample (length N_BINS) from the samples data
            for (int j = startIndex; j < startIndex + settings.n_bins; j++)
            {
                currSamples[j - startIndex] = samples[j];
            }

            Debug.Log("doFFT");
            output.fftData[i] = fftProvider.doFFT(currSamples, fftWindow);

            if (i != 0)
            {
                //Compute the spectral flux for the current spectrum
                float flux = 0;
                for (int j = 0; j < output.fftData[i].Length; j++)
                {
                    float currFlux = (output.fftData[i][j] - output.fftData[i - 1][j]);
                    //we only want 'rising' spectral flux - since we are detecting beat onset therefore we only care about rise in power
                    if (currFlux > 0)
                    {
                        flux += currFlux;
                    }
                }
                output.flux[i] = flux;
            }
            else
            {
                output.flux[0] = 0;
            }
        }

        //define a window size for the threshold. THRESHOLD_TIME is the length in time that the window should be.
        int thresholdWindowSize = Mathf.FloorToInt((settings.threshold_time / song_info.sampleLength) / settings.n_bins);

        Debug.Log("threshold: ");
        Debug.Log(thresholdWindowSize);

        //Compute threshold for each flux value
        for (int i = 0; i < output.flux.Length; i++)
        {
            float avg   = 0;
            float count = 0;
            for (int j = (i - thresholdWindowSize); j < (i + thresholdWindowSize); j++)
            {
                if (j < 0 || j >= output.flux.Length)
                {
                    continue;                                   //todo should be optimized
                }
                avg   += output.flux[j];
                count += 1;
            }
            if (count > 0)
            {
                output.threshold[i] = (avg / count) * settings.threshold_multiplier;
            }
            else
            {
                output.threshold[i] = 0f;
            }
        }

        //using the computed threshold, discard any flux values that are below/at the threshold (most likely not a beat as it is below avg)
        for (int i = 0; i < output.flux.Length; i++)
        {
            if (output.flux[i] <= output.threshold[i])
            {
                output.flux2[i] = 0f;
            }
            else
            {
                output.flux2[i] = output.flux[i]; //subtract avg so we see only the peak
            }
        }

        //Check for peaks: If curr value > next value this is a peak

        for (int i = 0; i < output.flux2.Length - 1; i++)
        {
            if (output.flux2[i] > output.flux2[i + 1])
            {
                output.peaks[i]    = output.flux2[i]; //Beat Detected
                output.totalPeaks += 1;
            }
            else
            {
                output.peaks[i] = 0f;
            }
        }

        //avg # of beats per second... multiply by 60 to get bpm
        output.totalPeaksOverTime = output.totalPeaks / song_info.length;

        Debug.Log("BPM: ");
        Debug.Log(output.totalPeaksOverTime * 60);

        //fly detection

        //define a window size for the threshold. THRESHOLD_TIME is the length in time that the window should be. for now use drift threshold time
        int flyThresholdWindowSize = Mathf.FloorToInt((settings.fly_threshold_time / song_info.sampleLength) / settings.n_bins) / 2;

        Debug.Log("threshold3: ");
        Debug.Log(flyThresholdWindowSize);

        //only look at the song between 30% and 70% duration,
        //and only find largest value.

        float largestDelta = 0;
        int   indexLargest = 0;

        Debug.Log("Detect fly");
        Debug.Log(Mathf.FloorToInt(.30f * output.peaks.Length));
        Debug.Log(Mathf.FloorToInt(.70f * output.peaks.Length));

        for (int i = Mathf.FloorToInt(.30f * output.peaks.Length); i < Mathf.FloorToInt(.70f * output.peaks.Length); i++)
        {
            float avgL   = 0;
            float avgR   = 0;
            float countL = 0;
            float countR = 0;

            for (int j = (i - flyThresholdWindowSize); j < (i + flyThresholdWindowSize); j++)
            {
                if (j < 0 || j >= output.peaks.Length)
                {
                    continue;                                    //todo should be optimized
                }
                if (j < i)
                {
                    avgL   += output.peaks[j];
                    countL += 1;
                }
                else
                {
                    avgR   += output.peaks[j];
                    countR += 1;
                }
            }
            if (countL > 0 && countR > 0)
            {
                float avg = (avgL / countL) - (avgR / countR); //we are looking for the biggest difference from left to right
                if (avg > largestDelta)
                {
                    largestDelta = avg;
                    indexLargest = i;
                }
            }
        }

        output.flySectionIndex = indexLargest;

        Debug.Log("Fly section: ");
        Debug.Log(output.flySectionIndex);

        //end fly detection

        //drift detection

        //define a window size for the threshold. THRESHOLD_TIME is the length in time that the window should be.
        int driftThresholdWindowSize = Mathf.FloorToInt((settings.drift_threshold_time / song_info.sampleLength) / settings.n_bins) / 2;

        Debug.Log("threshold2: ");
        Debug.Log(driftThresholdWindowSize);

        //Compute a threshold on avg # of peaks at a given time
        for (int i = 0; i < output.peaks.Length; i++)
        {
            float avg   = 0;
            float count = 0;
            for (int j = (i - driftThresholdWindowSize); j < (i + driftThresholdWindowSize); j++)
            {
                if (j < 0 || j >= output.peaks.Length)
                {
                    continue;                                    //todo should be optimized
                }
                avg   += output.peaks[j];
                count += 1;
            }
            if (count > 0)
            {
                output.peakThreshold[i] = (avg / count);
            }
            else
            {
                output.peakThreshold[i] = 0f;
            }
        }

        //select amount_drift_sections from output.peakThreshold, ensuring that each drift section is min_time_between_drift apart
        //remove all duplicates / close values next to a value, then store remaning values as a GreatestValueElement in a arraylist, then sort the list.

        List <GreatestValueElement> greatestValues = new List <GreatestValueElement>();

        Debug.Log("Start greatestvalues");
        int offset = 1;

        for (int i = 0; i < output.peakThreshold.Length; i += offset)
        {
            offset = 1;
            if ((i - driftThresholdWindowSize) <= 0 || (i + driftThresholdWindowSize) >= output.peakThreshold.Length) //throw out values near beginning and near end
            {
                continue;
            }
            while (((i + offset) < output.peakThreshold.Length) && Math.Abs(output.peakThreshold[i] - output.peakThreshold[i + offset]) <= delta)
            {
                output.peakThreshold[i + offset] = 0;
                offset += 1;
            }
            GreatestValueElement elem = new GreatestValueElement(i, output.peakThreshold[i]);
            greatestValues.Add(elem);
        }

        Debug.Log("Sort greatestvalues");

        //todo debug this...
        try {
            greatestValues.Sort((x, y) => y.value.CompareTo(x.value));
        }
        catch (Exception e) {
            Debug.Log("Could not sort greatestValues!");
            Debug.Log(e.ToString());
        }

        Debug.Log("Song length:");
        Debug.Log(song_info.length);

        int minLengthBetweenDrift = Mathf.FloorToInt((settings.min_drift_seperation_time / song_info.sampleLength) / settings.n_bins);
        int totalAllowableDrifts  = Mathf.FloorToInt(settings.drifts_per_minute * Mathf.FloorToInt(song_info.length / 60f));
        int warmUpTimeLength      = Mathf.FloorToInt((settings.warm_up_time / song_info.sampleLength) / settings.n_bins);

        Debug.Log("drifts per minute:");
        Debug.Log(settings.drifts_per_minute);

        Debug.Log("Drift sections: ");
        Debug.Log(totalAllowableDrifts);

        Debug.Log("Min length between drifts: ");
        Debug.Log(minLengthBetweenDrift);

        //select elements and make sure they are min_time_between_drift apart
        int numSelected = 0;
        List <GreatestValueElement> addedValues = new List <GreatestValueElement>();
        bool first = true;

        foreach (GreatestValueElement elem in greatestValues)
        {
            if (numSelected >= totalAllowableDrifts)
            {
                break;
            }
            if (first)
            {
                int offSetIndex = Math.Max(elem.index - driftThresholdWindowSize, 0);
                if (offSetIndex == 0)
                {
                    continue;
                }
                if (offSetIndex - warmUpTimeLength <= 0)
                {
                    continue;
                }
                output.drifts[offSetIndex] = elem.value;
                numSelected = 1;
                first       = false;
                addedValues.Add(elem);
            }
            else
            {
                bool flag = false;
                //We need to check if this elem is properly spaced at least min_time_between_drift apart from other drifts
                //And that the elem is not in the middle of a <fly> section or <time_after_fly> section
                foreach (GreatestValueElement added in addedValues)
                {
                    if (Math.Abs(elem.index - added.index) <= minLengthBetweenDrift ||
                        Math.Abs(elem.index - output.flySectionIndex) <= (flyThresholdWindowSize * 2.2))
                    {
                        flag = true;
                        break;
                    }
                }
                if (!flag)
                {
                    int offSetIndex = Math.Max(elem.index - driftThresholdWindowSize, 0);
                    if (offSetIndex == 0)
                    {
                        continue;
                    }
                    if (offSetIndex - warmUpTimeLength <= 0)
                    {
                        continue;
                    }
                    output.drifts[offSetIndex] = elem.value;
                    numSelected += 1;
                    addedValues.Add(elem);
                }
            }
        }

        //end drift detection

        //Filter peaks to allowable min_time_between_peaks
        //Todo this is a bit naive should probably select highest peak or something (but will work for now)
        //int minLengthBetweenPeaks = Mathf.FloorToInt(Mathf.FloorToInt((settings.min_peak_seperation_time / sampleLength) / settings.n_bins) / 2);
        if (settings.min_peak_seperation_time > 0)
        {
            int minLengthBetweenPeaks = Mathf.FloorToInt((settings.min_peak_seperation_time / song_info.sampleLength) / settings.n_bins);
            for (int i = 0; i < output.peaks.Length; i++)
            {
                if (output.peaks[i] > 0)
                {
                    output.peaks2[i] = output.peaks[i];
                    i += minLengthBetweenPeaks - 1;
                }
            }
        }
        else
        {
            for (int i = 0; i < output.peaks.Length; i++)
            {
                output.peaks2[i] = output.peaks[i];
            }
        }

        BeatMap beatMap = makeBeatMap(driftThresholdWindowSize * 2, flyThresholdWindowSize * 2);

        beatMap.save(persistentDataPath);

        //todo deal with random stuff below
        //debug output

        Debug.Log("BGA Done");
        this.state = STATE.DONE;

        // using (StreamWriter file = new StreamWriter("output.txt"))
        // {
        //     for (int i=0; i < output.flux.Length; i++)
        //     {
        //         file.WriteLine(output.flux[i]);
        //     }
        // }
        // using (StreamWriter file = new StreamWriter("output2.txt"))
        // {
        //     for (int i = 0; i < output.threshold.Length; i++)
        //     {
        //         file.WriteLine(output.threshold[i]);
        //     }
        // }
        // using (StreamWriter file = new StreamWriter("output3.txt"))
        // {
        //     for (int i = 0; i < output.flux2.Length; i++)
        //     {
        //         file.WriteLine(output.flux2[i]);
        //     }
        // }
        // using (StreamWriter file = new StreamWriter("output4.txt"))
        // {
        //     for (int i = 0; i < output.peaks.Length; i++)
        //     {
        //         file.WriteLine(output.peaks[i]);
        //     }
        // }
        // using (StreamWriter file = new StreamWriter("output5.txt"))
        // {
        //     for (int i = 0; i < output.peaks2.Length; i++)
        //     {
        //         file.WriteLine(output.peaks2[i]);
        //     }
        // }
        // using (StreamWriter file = new StreamWriter("output6.txt"))
        // {
        //     for (int i = 0; i < output.peakThreshold.Length; i++)
        //     {
        //         file.WriteLine(output.peakThreshold[i]);
        //     }
        // }
        // using (StreamWriter file = new StreamWriter("output7.txt"))
        // {
        //     for (int i = 0; i < output.drifts.Length; i++)
        //     {
        //         file.WriteLine(output.drifts[i]);
        //     }
        // }
        // using (StreamWriter file = new StreamWriter("output8.txt"))
        // {
        //     Queue<LaneObject> laneObjects = beatMap.initLaneObjectQueue();
        //     foreach (LaneObject l in laneObjects) {
        //         file.WriteLine(l.sampleIndex + " " + l.lane + " " + l.time + " " + (l.type == LANE_OBJECT_TYPE.Beat ? "1" : "0"));
        //     }
        // }


        // Debug.Log("Output file saved");


        //frameScale = (int) (songLength / finalArraySize);
        //float sampleLength = song_info.length / (float)song_info.sampleCount;
        //Debug.Log(sampleLength);

        //Debug.Log(sampleLength * 1000);
        //Debug.Log(sampleLength * N_BINS); //length per reading

        //done = true;
    }
Пример #18
0
    public void OutputData()
    {
        BeatMap outputBM;
        //		float outputT=0;
        //		Note outputNode;
        TimeTick outputTimeTick;

        outputBM = new BeatMap();
        InputField[] inpF;
        inpF = mainCanvas.GetComponentsInChildren <InputField>();
        for (int i = 0; i < inpF.Length; i++)
        {
            if (inpF [i].name == "InputName")
            {
                if (inpF [i].text != "")
                {
                    outputBM.name = inpF [i].text;
                }
                else
                {
                    outputBM.name = inpF [i].placeholder.GetComponent <Text> ().text;
                }
                inpF [i].interactable = false;
            }

            else if (inpF [i].name == "InputAuthor")
            {
                if (inpF [i].text != "")
                {
                    outputBM.author = inpF [i].text;
                }
                else
                {
                    outputBM.author = inpF [i].placeholder.GetComponent <Text> ().text;
                }
                inpF [i].interactable = false;
            }

            else if (inpF [i].name == "InputMusic")
            {
                if (inpF [i].text != "")
                {
                    outputBM.music = inpF [i].text;
                }
                else
                {
                    outputBM.music = inpF [i].placeholder.GetComponent <Text> ().text;
                }
                inpF [i].interactable = false;
            }
        }


        List <TimeTick> outputMap;

        outputTimeTick = new TimeTick();
        outputMap      = new List <TimeTick> ();
        for (int i = 0; i < noteList.Count; i++)
        {
            if (i != noteList.Count - 1)
            {
                Debug.Log(i + " " + noteList.Count);
                if ((noteList [i].time - noteList [i + 1].time) < 0.001f && (noteList [i].time - noteList [i + 1].time) > -0.001f)
                {
                    outputTimeTick.notes = new Note[2];

                    for (int p = 0; p < 2; p++)
                    {
                        outputTimeTick.notes[p]       = new Note();
                        outputTimeTick.notes [p].type = noteList [i + p].type;
                        outputTimeTick.notes [p].x    = noteList [i + p].pos.x;
                        outputTimeTick.notes [p].y    = noteList [i + p].pos.y;
                        outputTimeTick.notes [p].z    = noteList [i + p].pos.z;
                        outputTimeTick.t = noteList [i + p].time;
                    }
                    i++;
                }
                else
                {
                    Debug.Log(i + " " + noteList.Count + " SecF");
                    outputTimeTick.notes    = new Note[1];
                    outputTimeTick.notes[0] = new Note();
//					Debug.Log(if(outputTimeTick.notes[0]));
                    Debug.Log(outputTimeTick.notes[0].type);
                    outputTimeTick.notes[0].type =
                        noteList[i].type;
                    outputTimeTick.notes[0].x = noteList[i].pos.x;
                    outputTimeTick.notes[0].y = noteList[i].pos.y;
                    outputTimeTick.notes[0].z = noteList[i].pos.z;
                    outputTimeTick.t          = noteList [i].time;
                }
            }
            else
            {
                Debug.Log(i + " " + noteList.Count + " " + noteList[i].time + " Sec");
                outputTimeTick.notes         = new Note[1];
                outputTimeTick.notes[0]      = new Note();
                outputTimeTick.notes[0].type = noteList[i].type;
                outputTimeTick.notes[0].x    = noteList[i].pos.x;
                outputTimeTick.notes[0].y    = noteList[i].pos.y;
                outputTimeTick.notes[0].z    = noteList[i].pos.z;
                outputTimeTick.t             = noteList [i].time;
            }
            outputMap.Add(outputTimeTick);
            outputTimeTick = new TimeTick();
        }
        outputBM.map = new TimeTick[outputMap.Count];
        for (int i = 0; i < outputMap.Count; i++)
        {
            outputBM.map[i] = outputMap[i];
        }

        Debug.Log(JsonUtility.ToJson(outputBM, true));
        //File.WriteAllText
        using (FileStream fs = new FileStream(dirPath + "/" + beatmapJson, FileMode.Create)){
            using (StreamWriter writer = new StreamWriter(fs)){
                writer.Write(JsonUtility.ToJson(outputBM, true));
            }
        }
    }
Пример #19
0
    public void Prepare(string _path)
    {
        //dirPath = new DirectoryInfo (ListControl.beatmapsDir + beatmapDir).FullName;
//		dirPath=_path;

        beatmapDir  = _path.Substring(0, _path.IndexOf('/')) + '/';
        beatmapJson = _path.Substring(_path.IndexOf('/') + 1);
        Debug.Log(beatmapDir);
        Debug.Log(beatmapJson);


        dirPath = new DirectoryInfo(ListControl.beatmapsDir + beatmapDir).FullName;
        Debug.Log(dirPath);
        beatmap = LoadBeatMap();


        InputField[] inpF;
        inpF = mainCanvas.GetComponentsInChildren <InputField>();
        for (int i = 0; i < inpF.Length; i++)
        {
            if (inpF [i].name == "InputName")
            {
                inpF [i].placeholder.GetComponent <Text>().text = beatmap.name;
            }

            else if (inpF [i].name == "InputAuthor")
            {
                inpF [i].placeholder.GetComponent <Text>().text = beatmap.author;
            }

            else if (inpF [i].name == "InputMusic")
            {
                inpF [i].placeholder.GetComponent <Text>().text = beatmap.music;
            }
        }



//		WWW www = new WWW("file://" + dirPath + beatmap.music);
        string ASname = "file://" + dirPath + beatmap.music;
//		audioClip = www.audioClip;
        MusicControl mc = AS.GetComponent <MusicControl>();

        _musicControl = AS.GetComponent <MusicControl> ();
        mc.PrepareMusic(ASname);

        if (mc.AS.clip == null)
        {
            Debug.Log("Load audioClip failed.");
        }
        else
        {
            Debug.Log("Load audioClip success");
        }

        mc.AutoPlay();
        CreateButtonContent(beatmap);

//		isPrepared = true;
//		Debug.Log (isPrepared);
    }
Пример #20
0
    //All peaks are detected - now its time to decide where these beats are going
    BeatMap makeBeatMap(int drift_length, int fly_length)
    {
        BeatMap beatMap = new BeatMap(settings, song_info, song_meta, songFilePath);

        int currLane      = 0;
        int currLaneCount = 0;

        int timeAfterFly = Mathf.FloorToInt(getIndexFromTime(BGACommon.TIME_AFTER_FLY_SECTION));

        int endFlyIndex = -1;

        for (int i = 0; i < output.peaks2.Length; i++)
        {
            float currTime = getTimeFromIndex(i);
            if (i == output.flySectionIndex)
            {
                LaneObject lObj1 = new LaneObject(i, currTime, -1, LANE_OBJECT_TYPE.START_FLY_TRIGGER);
                LaneObject lObj2 = new LaneObject(i + fly_length, getTimeFromIndex(i + fly_length), -1, LANE_OBJECT_TYPE.START_NORMAL_TRIGGER);
                endFlyIndex = i + drift_length;
                beatMap.addLaneObject(lObj1);
                beatMap.addLaneObject(lObj2);
                Debug.Log("Added the fly section triggers");
                continue;
            }
            else if (output.drifts[i] > 0)
            {
                LaneObject lObj1 = new LaneObject(i, currTime, -1, LANE_OBJECT_TYPE.START_DRIFT_TRIGGER);
                LaneObject lObj2 = new LaneObject(i + drift_length, getTimeFromIndex(i + drift_length), -1, LANE_OBJECT_TYPE.START_NORMAL_TRIGGER);
                beatMap.addLaneObject(lObj1);
                beatMap.addLaneObject(lObj2);
                continue;
            }
            else if (i == endFlyIndex)   //Don't spawn anything after a <fly> section so that the car can fall back to the track
            {
                endFlyIndex = -1;
                i          += timeAfterFly;
                continue;
            }
            else if (output.peaks2[i] <= 0)
            {
                continue;
            }
            else if (currTime < settings.warm_up_time)   //we do not spawn notes until warm up time is done. So we spawn obstacles on L and R to show the beats
            {
                int        lane = (bga_random.Next(0, 2) == 1) ? 0 : 2;
                LaneObject lObj = new LaneObject(i, currTime, lane, LANE_OBJECT_TYPE.Obstacle);
                beatMap.addLaneObject(lObj);
            }
            else
            {
                //we have not spawned a beat yet, choose a random lane
                if (currLaneCount == 0)
                {
                    currLane      = bga_random.Next(0, 3);
                    currLaneCount = 1;
                }
                else
                {
                    if (bga_random.NextDouble() < BGACommon.CHANCE_TO_SWITCH_LANES)   //5 % chance we stay in the same lane
                    {
                        currLaneCount = 1;
                        int direction = (bga_random.Next(0, 2) == 1) ? -1 : 1; //move left or right? if on ends wrap around
                        currLane = Math.Abs((currLane + direction) % BGACommon.NUMBER_LANES);
                    }
                    else
                    {
                        currLaneCount += 1;
                    }
                    int randomObstacle = bga_random.Next(0, 4);
                    switch (randomObstacle)
                    {
                    case 0: break;

                    case 1:
                        //add an obstacle on lane n + 1
                        beatMap.addLaneObject(new LaneObject(i, currTime, Math.Abs((currLane + 1) % BGACommon.NUMBER_LANES), LANE_OBJECT_TYPE.Obstacle));
                        break;

                    case 2:
                        //add an obstacle on lane n - 1
                        beatMap.addLaneObject(new LaneObject(i, currTime, Math.Abs((currLane - 1) % BGACommon.NUMBER_LANES), LANE_OBJECT_TYPE.Obstacle));
                        break;

                    case 3:
                        //add an obstacle on lanes n - 1 and n + 1
                        beatMap.addLaneObject(new LaneObject(i, currTime, Math.Abs((currLane + 1) % BGACommon.NUMBER_LANES), LANE_OBJECT_TYPE.Obstacle));
                        beatMap.addLaneObject(new LaneObject(i, currTime, Math.Abs((currLane - 1) % BGACommon.NUMBER_LANES), LANE_OBJECT_TYPE.Obstacle));
                        break;

                    default:
                        throw new Exception("randomObstacle is an unexpected value! Expected [0, 3]; actual: " + randomObstacle);
                    }

                    LaneObject lObj = new LaneObject(i, currTime, currLane, LANE_OBJECT_TYPE.Beat);
                    beatMap.addLaneObject(lObj);
                }
            }
        }

        return(beatMap);
    }
Пример #21
0
 private void ExecuteDownloadCommand(BeatMap map)
 {
     beatSaverClient.DownloadMap(CancellationToken.None, map);
 }
Пример #22
0
    public void Prepare()
    {
        dirPath = new DirectoryInfo(GameController.beatmapsDir + beatmapDir).FullName;
        beatmap = LoadBeatMap();

        WWW www = new WWW("file://" + dirPath + beatmap.music);

        audioClip = www.audioClip;

        if (audioClip == null)
        {
            Debug.Log("Load audioClip failed.");
        }
        else
        {
            Debug.Log("Load audioClip success");
        }
        audioSource      = GetComponent <AudioSource> ();
        audioSource.clip = audioClip;

        bool isRandom = false;

        // Random generator
        for (int cnt = 0; cnt < beatmap.map.Length; cnt++)
        {
            for (int j = 0; j < beatmap.map [cnt].notes.Length; j++)
            {
                switch (beatmap.map [cnt].notes [j].type)
                {
                case 1:
                {
                    Vector3 pos = randompos.Generate(beatmap.map [cnt].t);
                    pos += playerArmPosition;
                    beatmap.map [cnt].notes [j].x    = pos.x;
                    beatmap.map [cnt].notes [j].y    = pos.y;
                    beatmap.map [cnt].notes [j].z    = pos.z;
                    beatmap.map [cnt].notes [j].type = 2;
                    isRandom = true;
                }
                break;

                default:
                    break;
                }
            }
        }

        if (isRandom == true)
        {
            File.Copy((dirPath + beatmapJson), dirPath + beatmapJson + "backup.txt", false);
            using (FileStream fs = new FileStream(dirPath + beatmapJson, FileMode.Create)){
                using (StreamWriter writer = new StreamWriter(fs)){
                    writer.Write(JsonUtility.ToJson(beatmap, true));
                }
            }
        }

        isPrepared = true;
        Debug.Log(isPrepared);

        Debug.Log("Map Length: " + beatmap.map.Length);          // Debug
    }
Пример #23
0
 public float GetZDelta()
 {
     return(BeatMap.GetSpawnPositionZ() - BeatMap.destroyNoteAtZ);
 }
Пример #24
0
 /// <summary>
 /// Add a beatMap to this part's list of beatMaps
 /// </summary>
 public void AddBeatMap(BeatMap bm)
 {
     beats.Add(bm);
 }
Пример #25
0
 private void ExecuteDeleteMapCommand(BeatMap map)
 {
     beatSaberService.DeleteBeatMap(map);
     eventAggregator.GetEvent <MapLibraryChangedEvent>().Publish();
 }
Пример #26
0
        public void DeleteBeatMap(BeatMap beatMap)
        {
            var mapFolder = Path.Combine(GetCustomLevelsDirectory(), beatMap.FolderLocation);

            FileHelper.DeleteFolder(mapFolder, true);
        }
    void Start()
    {
        //Screen.SetResolution(1280, 720, true, 60);
        //mainCamera = GameObject.Find("Main Camera").GetComponent<Camera>();
        // first index is initial camera position/rotation
        //cameraPositions = new Vector3[] {mainCamera.transform.position, new Vector3(-313, -527, 1880)};
        //cameraRotations = new Quaternion[] {mainCamera.transform.rotation, Quaternion.Euler(-1.813f, -181.159f, 0)};
        warningText               = GameObject.Find("warningText");
        load_state                = LOAD_STATE.NOT_LOADED;
        _gameState                = GameState.playing;
        _playerScore              = 0;
        _playerCombo              = 1;
        _playerNotesHit           = 0;
        _playerMaxCombo           = 1;
        _pCombo                   = GameObject.Find("comboText").GetComponent <Text>();
        _pScore                   = GameObject.Find("scoreText").GetComponent <Text>();
        _playerHealth             = 100f;
        _playerHealthDecreaseRate = 1f;
        lastTime                  = Time.time;
        totalNotes                = 0;

        mainCamera = GameObject.Find("Main Camera");

        //gameOverPanel = GameObject.Find("GameOverPanel");
        gameOverPanel.SetActive(false);
        //gameOverRetryButton = GameObject.Find("GameOverRetryButton");
        //gameOverQuitButton = GameObject.Find("GameOverQuitButton");

        gameOverRetryButton.GetComponent <Button>().onClick.AddListener(handleGameOverRetry);
        gameOverQuitButton.GetComponent <Button>().onClick.AddListener(handleGameOverQuit);

        audioSrc = this.GetComponent <AudioSource>(); // there is an audiosource in beatmapplayer, but it is more convenient to create one here

        // do not render the pause canvas on launch
        //GameObject.Find("PauseCanvas").SetActive(false);

        LoadPlayerFromExternal(ref playerClass);

        // handle car visibility
        GameObject car_gt86  = GameObject.Find("car_gt86");
        GameObject car_merc  = GameObject.Find("car_merc");
        GameObject car_lambo = GameObject.Find("car_lambo");

        cars = new GameObject[] { car_gt86, car_merc, car_lambo }; // keep the order here the same as in MainMenuCanvasController

        btnSettings.onClick.AddListener(handleSettings);
        exitSettingsButton.onClick.AddListener(handleExitSettings);

        settingsPanel.SetActive(false);

        handleCarVisibility();

        beatMap = BeatMap.loadBeatMap();
        beatMap.loadSamples(this);

        objective    = GameObject.Find("Objective");
        badObjective = GameObject.Find("BadObjective");

        sounds = GetComponents <AudioSource>();

        // initial camera angle
        //mainCamera.transform.position = Vector3.MoveTowards(cameraPositions[1], cameraPositions[0], 20f);
        //mainCamera.transform.rotation = Quaternion.RotateTowards(cameraRotations[1], cameraRotations[0], 20f);


        // temp, generate gameobjects based on beatmap
        //Stream openFileStream = File.OpenRead(Application.persistentDataPath + "/BeatMaps/testBeatmap.dat");
        //BinaryFormatter deserializer = new BinaryFormatter();
        //BeatMap beatMap = (BeatMap)deserializer.Deserialize(openFileStream);
    }