Пример #1
0
    public void SetAnchor(bool anchored)
    {
        if (currentBPM != prevBPM)
        {
            return;
        }

        BPM newBpm = new BPM(currentBPM);

        if (anchored)
        {
            newBpm.anchor = currentBPM.song.LiveTickToTime(currentBPM.tick, currentBPM.song.resolution);
        }
        else
        {
            newBpm.anchor = null;
        }

        editor.commandStack.Push(new SongEditModify <BPM>(currentBPM, newBpm));
        editor.SelectSongObject(newBpm, editor.currentSong.syncTrack);

        Debug.Log("Anchor toggled to: " + newBpm.anchor);
    }
        public ActionResult EditBusiness(int?id, int?walkid)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            Walktrough     walktrough = db.Walktroughs.Find(walkid);
            BusinessProces business   = db.BusinessProcess.Find(id);
            BPM            bpm        = db.BPMs.Find(id);

            if (walktrough == null)
            {
                return(HttpNotFound());
            }
            List <string>         newFilesName = new List <string>();
            List <string>         paths        = new List <string>();
            UrlHelper             url          = Url;
            HttpServerUtilityBase server       = Server;

            var getFiles = filesTransact.getFiles(business.DocumentNo, out newFilesName, out paths, url, server);

            ViewBag.newFilesName = newFilesName;
            ViewBag.paths        = paths;

            ViewBag.WalktroughID     = business.WalktroughID;
            ViewBag.BPMID            = business.BPMID;
            ViewBag.BusinessProcesID = business.BusinessProcesID;
            ViewBag.DocumentNo       = business.DocumentNo;
            ViewBag.DocumentName     = business.DocumentName;
            ViewBag.FolderName       = business.FolderName;

            walktrough.BusinessProces = (from b in db.BusinessProcess
                                         where b.BPMID == id
                                         select b).ToList();

            return(View(walktrough));
        }
Пример #3
0
        public SimFileInfo ParseSmFile(String path)
        {
            SimFileInfo simFileInfo = new SimFileInfo();

            simFileInfo.path = Path.GetDirectoryName(path);
            StreamReader sr = new StreamReader(path);
            string       line;

            string[] words;

            while ((line = sr.ReadLine()) != null)
            {
                words = line.Split(':');

                if (words[0] == "#TITLE")
                {
                    simFileInfo.title = words[1].Trim(';');
                }

                if (words[0] == "#SUBTITLE")
                {
                    simFileInfo.subtitle = words[1].Trim(';');
                }

                if (words[0] == "#ARTIST")
                {
                    simFileInfo.artist = words[1].Trim(';');
                }

                if (words[0] == "#CREDIT")
                {
                    simFileInfo.credit = words[1].Trim(';');
                }

                if (words[0] == "#MUSIC")
                {
                    simFileInfo.music = words[1].Trim(';');
                }

                if (words[0] == "#BANNER")
                {
                    simFileInfo.banner = words[1].Trim(';');
                }

                if (words[0] == "#BACKGROUND")
                {
                    simFileInfo.bg = words[1].Trim(';');
                }

                if (words[0] == "#CDTITLE")
                {
                    simFileInfo.cdtitle = words[1].Trim(';');
                }

                if (words[0] == "#OFFSET")
                {
                    simFileInfo.offset = Convert.ToDouble(words[1].Trim(';').Replace('.', ','));
                }

                if (words[0] == "#BPMS")
                {
                    if (words[1].EndsWith(";"))
                    {
                        if (words[1].Split(',').Length > 1)
                        {
                            List <BPM> bpmList = new List <BPM>();
                            string[]   bpofarr = words[1].Trim(';').Split(',');
                            foreach (string element in bpofarr)
                            {
                                BPM      bpm  = new BPM();
                                string[] bpof = element.Split('=');
                                bpm.measure = Convert.ToDouble(bpof[0].Replace('.', ','));
                                bpm.bpm     = Convert.ToDouble(bpof[1].Replace('.', ','));
                                bpmList.Add(bpm);
                            }
                            simFileInfo.bpms = bpmList.ToArray();
                        }
                        else
                        {
                            BPM      bpm = new BPM();
                            string[] bpof;
                            bpof             = words[1].Split('=');
                            bpm.measure      = Convert.ToDouble(bpof[0].Replace('.', ','));
                            bpm.bpm          = Convert.ToDouble(bpof[1].Trim(';').Replace('.', ','));
                            simFileInfo.bpms = new BPM[] { bpm };
                        }
                    }
                    else
                    {
                        List <BPM> bpmList = new List <BPM>();
                        string[]   bpof    = words[1].Split('=');
                        BPM        bpm     = new BPM();
                        bpm.measure = Convert.ToDouble(bpof[0].Replace('.', ','));
                        bpm.bpm     = Convert.ToDouble(bpof[1].Replace('.', ','));
                        bpmList.Add(bpm);
                        while ((line = sr.ReadLine().Trim(',')) != ";")
                        {
                            bpof        = line.Split('=');
                            bpm         = new BPM();
                            bpm.measure = Convert.ToDouble(bpof[0].Replace('.', ',')) / 4;
                            bpm.bpm     = Convert.ToDouble(bpof[1].Replace('.', ','));
                            bpmList.Add(bpm);
                        }
                        simFileInfo.bpms = bpmList.ToArray();
                    }
                }

                if (words[0] == "#NOTES")
                {
                    List <Chart.Chart> chartList = new List <Chart.Chart>();
                    while ((line = sr.ReadLine()) != null)
                    {
                        Chart.Chart chart = new Chart.Chart();
                        line            = sr.ReadLine();
                        chart.stepAutor = line.Trim(' ', ':');
                        line            = sr.ReadLine();
                        chart.diff      = line.Trim(' ', ':');
                        line            = sr.ReadLine(); line = sr.ReadLine();
                        string notes = "";
                        while ((line = sr.ReadLine()) != ";")
                        {
                            if (line == ",")
                            {
                                notes += line;
                            }
                            else
                            {
                                notes += line + "\n";
                            }
                        }
                        chart.noteData = notes.Split(',');
                        chartList.Add(chart);
                        if ((line = sr.ReadLine()) == null)
                        {
                            break;
                        }
                        else
                        {
                            sr.ReadLine();
                            continue;
                        }
                    }
                    simFileInfo.charts = chartList.ToArray();
                }
            }
            sr.Close();
            return(simFileInfo);
        }
    string GetSaveString <T>(Song song, IList <T> list, ExportOptions exportOptions, ref string out_errorList, Song.Instrument instrument = Song.Instrument.Guitar) where T : SongObject
    {
        System.Text.StringBuilder saveString = new System.Text.StringBuilder();

        float resolutionScaleRatio = song.ResolutionScaleRatio(exportOptions.targetResolution);

        for (int i = 0; i < list.Count; ++i)
        {
            SongObject songObject = list[i];
            try
            {
                uint tick = (uint)Mathf.Round(songObject.tick * resolutionScaleRatio) + exportOptions.tickOffset;
                saveString.Append(Globals.TABSPACE + tick);

                switch ((SongObject.ID)songObject.classID)
                {
                case (SongObject.ID.BPM):
                    BPM bpm = songObject as BPM;
                    if (bpm.anchor != null)
                    {
                        uint anchorValue = (uint)((double)bpm.anchor * 1000000);
                        saveString.AppendFormat(s_anchorFormat, anchorValue, tick);
                    }

                    saveString.AppendFormat(s_bpmFormat, bpm.value);
                    break;

                case (SongObject.ID.TimeSignature):
                    TimeSignature ts = songObject as TimeSignature;

                    if (ts.denominator == 4)
                    {
                        saveString.AppendFormat(s_tsFormat, ts.numerator);
                    }
                    else
                    {
                        uint denominatorSaveVal = (uint)Mathf.Log(ts.denominator, 2);
                        saveString.AppendFormat(s_tsDenomFormat, ts.numerator, denominatorSaveVal);
                    }
                    break;

                case (SongObject.ID.Section):
                    Section section = songObject as Section;
                    saveString.AppendFormat(s_sectionFormat, section.title);
                    break;

                case (SongObject.ID.Event):
                    Event songEvent = songObject as Event;
                    saveString.AppendFormat(s_eventFormat, songEvent.title);
                    break;

                case (SongObject.ID.ChartEvent):
                    ChartEvent chartEvent = songObject as ChartEvent;
                    saveString.AppendFormat(s_chartEventFormat, chartEvent.eventName);
                    break;

                case (SongObject.ID.Starpower):
                    Starpower sp = songObject as Starpower;
                    saveString.AppendFormat(s_starpowerFormat, (uint)Mathf.Round(sp.length * resolutionScaleRatio));
                    break;

                case (SongObject.ID.Note):
                    Note note = songObject as Note;
                    int  fretNumber;

                    if (instrument != Song.Instrument.Unrecognised)
                    {
                        if (instrument == Song.Instrument.Drums)
                        {
                            fretNumber = GetDrumsSaveNoteNumber(note);
                        }

                        else if (instrument == Song.Instrument.GHLiveGuitar || instrument == Song.Instrument.GHLiveBass)
                        {
                            fretNumber = GetGHLSaveNoteNumber(note);
                        }

                        else
                        {
                            fretNumber = GetStandardSaveNoteNumber(note);
                        }
                    }
                    else
                    {
                        fretNumber = note.rawNote;
                    }

                    saveString.AppendFormat(s_noteFormat, fretNumber, (uint)Mathf.Round(note.length * resolutionScaleRatio));

                    // Only need to get the flags of one note of a chord
                    if (exportOptions.forced && (note.next == null || (note.next != null && note.next.tick != note.tick)))
                    {
                        if ((note.flags & Note.Flags.Forced) == Note.Flags.Forced)
                        {
                            saveString.AppendFormat(s_forcedNoteFormat, tick);
                        }

                        // Save taps line if not an open note, as open note taps cause weird artifacts under sp
                        if (!note.IsOpenNote() && (note.flags & Note.Flags.Tap) == Note.Flags.Tap)
                        {
                            saveString.AppendFormat(s_tapNoteFormat, tick);
                        }
                    }
                    continue;

                default:
                    continue;
                }
                saveString.Append(Globals.LINE_ENDING);

                //throw new System.Exception("Test error count: " + i);
            }
            catch (System.Exception e)
            {
                string error = Logger.LogException(e, "Error with saving object #" + i + " as " + songObject);
                out_errorList += error + Globals.LINE_ENDING;
            }
        }

        return(saveString.ToString());
    }
Пример #5
0
    Chart ParseChart(string text)
    {
        MatchCollection sectionNameMatches = Regex.Matches(text, @"\[(.*)\]");
        List <string>   sectionNames       = new List <string>();

        foreach (Match m in sectionNameMatches)
        {
            sectionNames.Add(m.Groups[1].Value);
        }

        string[]      sectionsArr = Regex.Split(text, @"(?:}\r\n)*\[.*\](?:\r\n{)");
        List <string> sections    = new List <string>();

        foreach (string s in sectionsArr)
        {
            if (s.Length > 0)
            {
                sections.Add(s);
            }
        }

        Chart c = new Chart();

        // Section 1 - Song Metadata
        string[] nameData = sections[0].Trim().Split('\n');
        c.Name    = nameData[0].Trim().Split('=')[1].Trim();
        c.Artist  = nameData[1].Trim().Split('=')[1].Trim();
        c.Charter = nameData[2].Trim().Split('=')[1].Trim();
        c.Offset  = float.Parse(nameData[3].Trim().Split('=')[1].Trim());
        // Offset might be used differently here than by GH
        // It is the amount of ticks to push up the tickStart of the notes
        c.Resolution     = int.Parse(nameData[4].Trim().Split('=')[1].Trim());
        c.Player2        = nameData[5].Trim().Split('=')[1].Trim();
        c.Difficulty     = int.Parse(nameData[6].Trim().Split('=')[1].Trim());
        c.PreviewStart   = float.Parse(nameData[7].Trim().Split('=')[1].Trim());
        c.PreviewEnd     = float.Parse(nameData[8].Trim().Split('=')[1].Trim());
        c.Genre          = nameData[9].Trim().Split('=')[1].Trim();
        c.MediaType      = nameData[10].Trim().Split('=')[1].Trim();
        c.MusicStream    = nameData[11].Trim().Split('=')[1].Trim();
        c.bpms           = new List <BPM>();
        c.timeSignatures = new List <TimeSignature>();

        // Section 2 - Synctrack data, like time signature and beats per second (x1000)
        string[] syncData = sections[1].Trim().Split('\n');

        for (int i = 0; i < syncData.Length; i++)
        {
            if (syncData[i].Trim().Split('=')[1].Trim().Split(' ')[0] == "B")
            {
                // BPM change
                int tick  = int.Parse(syncData[i].Trim().Split('=')[0].Trim());
                int value = int.Parse(syncData[i].Trim().Split('=')[1].Trim().Split(' ')[1]);
                BPM bpm   = new BPM(tick, value);

                c.bpms.Add(bpm);
            }
            else
            {
                // Time signature change
                int           tick  = int.Parse(syncData[i].Trim().Split('=')[0].Trim());
                int           value = int.Parse(syncData[i].Trim().Split('=')[1].Trim().Split(' ')[1]);
                TimeSignature ts    = new TimeSignature
                {
                    tick  = tick,
                    value = value
                };
                c.timeSignatures.Add(ts);
            }
        }

        for (int i = 0; i < c.bpms.Count; i++)
        {
            c.bpms[i].assignedTime = TickToTime(c, c.bpms[i].tick, c.Resolution);
        }

        // Section 3 (index2) is ignored

        // Section 4 (index3) is the first guitar track
        c.Notes = new Dictionary <Difficulty, List <Note> >();

        for (int i = 3; i < sectionNames.Count; i++)
        {
            c.Notes.Add(ParseDifficulty(sectionNames[i]), ParseNotes(c, sections[i]));
        }

        return(c);
    }
Пример #6
0
 public void CopyFrom(BPM bpm)
 {
     tick   = bpm.tick;
     value  = bpm.value;
     anchor = bpm.anchor;
 }
Пример #7
0
    protected override void Update()
    {
        base.Update();
        if (currentBPM != null)
        {
            // Update inspector information
            positionText.text = "Position: " + currentBPM.tick.ToString();
            if (!Services.IsTyping)
            {
                UpdateBPMInputFieldText();
            }

            anchorToggle.isOn = currentBPM.anchor != null;

            bool interactable = !IsNextBPMAnAnchor();
            foreach (Selectable ui in AnchorAheadDisable)
            {
                ui.interactable = interactable;
            }
        }

        editor.currentSong.UpdateCache();

        if (incrementalTimer > AUTO_INCREMENT_WAIT_TIME)
        {
            autoIncrementTimer += Time.deltaTime;
        }
        else
        {
            autoIncrementTimer = 0;
        }

        if (!(ShortcutInput.GetInput(Shortcut.BpmIncrease) && ShortcutInput.GetInput(Shortcut.BpmDecrease)))    // Can't hit both at the same time
        {
            if (!Services.IsTyping && !Globals.modifierInputActive)
            {
                if (ShortcutInput.GetInputDown(Shortcut.BpmDecrease) && decrement.interactable)
                {
                    lastAutoVal = currentBPM.value;
                    decrement.onClick.Invoke();
                }
                else if (ShortcutInput.GetInputDown(Shortcut.BpmIncrease) && increment.interactable)
                {
                    lastAutoVal = currentBPM.value;
                    increment.onClick.Invoke();
                }

                // Adjust to time rather than framerate
                if (incrementalTimer > AUTO_INCREMENT_WAIT_TIME && autoIncrementTimer > AUTO_INCREMENT_RATE)
                {
                    if (ShortcutInput.GetInput(Shortcut.BpmDecrease) && decrement.interactable)
                    {
                        decrement.onClick.Invoke();
                    }
                    else if (ShortcutInput.GetInput(Shortcut.BpmIncrease) && increment.interactable)
                    {
                        increment.onClick.Invoke();
                    }

                    autoIncrementTimer = 0;
                }

                //
                if (ShortcutInput.GetInput(Shortcut.BpmIncrease) || ShortcutInput.GetInput(Shortcut.BpmDecrease))
                {
                    incrementalTimer   += Time.deltaTime;
                    ChartEditor.isDirty = true;
                }
            }
            else
            {
                incrementalTimer = 0;
            }

            // Handle key release, add in action history
            if ((ShortcutInput.GetInputUp(Shortcut.BpmIncrease) || ShortcutInput.GetInputUp(Shortcut.BpmDecrease)) && lastAutoVal != null)
            {
                incrementalTimer = 0;
                editor.actionHistory.Insert(new ActionHistory.Modify(new BPM(currentSongObject.tick, (uint)lastAutoVal), currentSongObject));
                if (anchorAdjustment != null)
                {
                    editor.actionHistory.Insert(new ActionHistory.Modify(anchorAdjustmentOriginalValue, anchorAdjustment));
                    anchorAdjustment = null;
                    anchorAdjustmentOriginalValue = null;
                }

                ChartEditor.isDirty = true;
                lastAutoVal         = null;// currentBPM.value;
            }
        }

        Controls();

        prevBPM = currentBPM;
    }
Пример #8
0
 protected override void OnDisable()
 {
     base.OnDisable();
     currentBPM = null;
     editor.currentSong.UpdateCache();
 }
        public async Task <ActionResult> CreateBPM(IEnumerable <HttpPostedFileBase> files, [Bind(Include = "BPMID,WalktroughID,Name")] BPM bpm, string submit, int WalktroughID)
        {
            if (ModelState.IsValid)
            {
                string user = submit.Contains("By") ? submit.Split('y')[1] : String.Empty;
                if (submit == "Save" || submit == "Send Back")
                {
                    bpm.Status = "Draft";
                }
                else if (submit == "Approve")
                {
                    bpm.Status = "Approve";
                }
                else if (submit == "Submit For Review By" + user)
                {
                    bpm.Status = "Pending for Review by" + user;
                }
                else if (submit == "Submit For Approve By" + user)
                {
                    bpm.Status = "Pending for Approve by" + user;
                }

                db.BPMs.Add(bpm);
                await db.SaveChangesAsync();

                ReviewRelationMaster rrm = new ReviewRelationMaster();
                string page = "bpm";
                rrm.Description = page + bpm.BPMID;
                db.ReviewRelationMasters.Add(rrm);
                db.SaveChanges();
                string username = User.Identity.Name;
                int    wallid   = Convert.ToInt32(bpm.WalktroughID);
                BPM    bp       = new BPM();
                auditTransact.CreateAuditTrail("Create", wallid, "BPM", bp, bpm, username);
                TempData["message"] = "BPM successfully created!";
                return(RedirectToAction("CreateBusiness", new { id = bpm.BPMID, walkid = WalktroughID }));
                //return RedirectToAction("Create");
            }
            return(View(bpm));
        }
Пример #10
0
    public EvaluationReports(
        BPM classifier,
        ClassifierEvaluator <IList <Vector>, int, IList <string>, string> evaluator,
        Vector[] x,
        IList <string> y,
        IEnumerable <IDictionary <string, double> > yPredicDistrib,
        IEnumerable <string> yPredicLabel,
        string reportFileName,
        string positiveClassLabel,
        string groundTruthFileName          = "",
        string predictionsFileName          = "",
        string weightsFileName              = "",
        string calibrationCurveFileName     = "",
        string precisionRecallCurveFileName = "",
        string rocCurveFileName             = "")
    {
        Debug.Assert(classifier != null, "The classifier must not be null.");
        Debug.Assert(evaluator != null, "The evaluator must not be null.");
        Debug.Assert(x != null, "The feature vector must not be null.");
        Debug.Assert(y != null, "The targe variable must not be null.");
        Debug.Assert(yPredicDistrib != null, "The predictive distribution must not be null.");
        Debug.Assert(yPredicLabel != null, "The predicted labels must not be null.");
        Debug.Assert(!string.IsNullOrEmpty(reportFileName), "The report file name must not be null/empty.");
        Debug.Assert(!string.IsNullOrEmpty(positiveClassLabel), "The positive class label must not be null/empty.");

        // Write evaluation report header information
        if (!string.IsNullOrEmpty(reportFileName))
        {
            using (var writer = new StreamWriter(reportFileName))
            {
                this.WriteReportHeader(writer, groundTruthFileName, predictionsFileName);
                this.WriteReport(writer, evaluator, x, y, yPredicDistrib, yPredicLabel);
            }
        }

        // Write the prediction distribution for all labels
        if (!string.IsNullOrEmpty(predictionsFileName))
        {
            SaveLabelDistributions(predictionsFileName, yPredicDistrib);
        }

        // Compute and write the empirical probability calibration curve
        if (!string.IsNullOrEmpty(calibrationCurveFileName))
        {
            this.WriteCalibrationCurve(calibrationCurveFileName, evaluator, x, y, yPredicDistrib, positiveClassLabel);
        }

        // Compute and write the precision-recall curve
        if (!string.IsNullOrEmpty(precisionRecallCurveFileName))
        {
            this.WritePrecisionRecallCurve(precisionRecallCurveFileName, evaluator, x, y, yPredicDistrib, positiveClassLabel);
        }

        // Compute and write the receiver operating characteristic curve
        if (!string.IsNullOrEmpty(rocCurveFileName))
        {
            this.WriteRocCurve(rocCurveFileName, evaluator, x, y, yPredicDistrib, positiveClassLabel);
        }
        // Compute and write the weights
        if (!string.IsNullOrEmpty(weightsFileName))
        {
            // this.SampleWeights(weightsFileName, classifier);
        }
    }
Пример #11
0
 /// <summary>Initializes a new instance of the <seealso cref="TimingPoint"/> class.</summary>
 /// <param name="bpm">The BPM of the timing point.</param>
 /// <param name="timeSignature">The time signature of the timing point.</param>
 public TimingPoint(BPM bpm, TimeSignature timeSignature)
 {
     BPM           = bpm;
     TimeSignature = timeSignature;
 }
Пример #12
0
 private void updateLabel()
 {
     App.Current.Dispatcher.Invoke(() => Label.Text = "Period = " + Period + "\nBPM = " + BPM.ToString("000.00"));
 }
Пример #13
0
 public override int GetHashCode()
 {
     return(SessionID.GetHashCode() ^ BPM.GetHashCode() ^ TimeStamp.GetHashCode());
 }
Пример #14
0
        public ChartSlice Cut(double left, double right, Measure measure, SimFileInfo simFileInfo, int diffIndex, WaveFormat wf)
        {
            double begin = MeasureToMs((int)left, simFileInfo.offset, simFileInfo.bpms);
            double end   = MeasureToMs(Math.Ceiling(right), simFileInfo.offset, simFileInfo.bpms);

            TrimWavFile(Path.GetTempPath() + "/" + simFileInfo.music + ".wav", Path.GetTempPath() + "/temp.wav", begin, end);
            var w = File.Open(Path.GetTempPath() + "/temp.wav", FileMode.Open);

            byte[] bytes = new byte[w.Length];
            w.Read(bytes, 0, (int)w.Length);
            w.Close();

            File.Delete(Path.GetTempPath() + "/temp.wav");

            ///////////////////////

            int totalChunks = (int)(Math.Ceiling(right) - (int)left);

            string[] notes = new string[totalChunks];
            for (int i = 0; i < totalChunks; i++)
            {
                List <string> notesTemp = new List <string>();
                if (i == 0)
                {
                    double   skipPart = left - (int)left;
                    string[] arr      = simFileInfo.charts[diffIndex].noteData[(int)left + i].Split('\n');

                    for (int j = 0; j < arr.Length; j++)
                    {
                        if ((double)j / (double)(arr.Length - 1) >= skipPart)
                        {
                            notesTemp.Add(arr[j]);
                        }
                        else
                        {
                            notesTemp.Add("0000");
                        }
                    }
                }
                else if (i == totalChunks - 1)
                {
                    double   skipPart = Math.Ceiling(right) - right;
                    string[] arr      = simFileInfo.charts[diffIndex].noteData[(int)left + i].Split('\n');

                    for (int j = 0; j < arr.Length; j++)
                    {
                        if (1 - ((double)j / (double)(arr.Length - 1)) >= skipPart)
                        {
                            notesTemp.Add(arr[j]);
                        }
                        else
                        {
                            notesTemp.Add("0000");
                        }
                    }
                }
                else
                {
                    string[] arr = simFileInfo.charts[diffIndex].noteData[(int)left + i].Split('\n');
                    for (int j = 0; j < arr.Length; j++)
                    {
                        notesTemp.Add(arr[j]);
                    }
                }
                notes[i] = string.Join("\n", notesTemp.ToArray());
            }

            List <BPM> bpmList = new List <BPM>();
            BPM        leftBpm = new BPM();

            for (int i = 0; i < simFileInfo.bpms.Length; i++)
            {
                if (simFileInfo.bpms[i].measure < (int)left)
                {
                    leftBpm.bpm     = simFileInfo.bpms[i].bpm;
                    leftBpm.measure = 0;
                }
                else if (simFileInfo.bpms[i].measure > (int)left && simFileInfo.bpms[i].measure < Math.Ceiling(right))
                {
                    BPM bpm = new BPM();
                    bpm.measure = simFileInfo.bpms[i].measure - (int)left;
                    bpm.bpm     = simFileInfo.bpms[i].bpm;
                    bpmList.Add(bpm);
                }
            }
            bpmList.Insert(0, leftBpm);


            return(new ChartSlice(1.0, bytes, notes, bpmList.ToArray(), wf, (int)left, end - begin + clipCorrectionFunc(begin, end)));
        }
Пример #15
0
    public Song parse(string link)
    {
        Song result = new Song();

        StreamReader file = new StreamReader(link);
        string       line;

        while ((line = file.ReadLine()) != null)
        {
            string[] split = line.Split(':');
            string   flag  = split [0];

            if (flag == "#TITLE")
            {
                result.title = split [1].TrimEnd(';');
            }
            if (flag == "#ARTIST")
            {
                result.artist = split [1].TrimEnd(';');
            }
            if (flag == "#BPMS")
            {
                string   bpms  = split [1].TrimEnd(';');
                string[] pairs = bpms.Split(',');

                for (int i = 0; i < pairs.Length; i++)
                {
                    string[] sides = pairs [i].Split('=');
                    //Debug.Log ($"{sides[1]} at {sides[0]}");
                    float thisbpm  = float.Parse(sides [1], CultureInfo.InvariantCulture.NumberFormat);
                    float thisbeat = float.Parse(sides [0], CultureInfo.InvariantCulture.NumberFormat);
                    BPM   newbpm   = new BPM(thisbpm, thisbeat);
                    result.bpms.Add(newbpm);
                }
            }
            if (flag == "#OFFSET")
            {
                result.offset = float.Parse(split [1].TrimEnd(';'), CultureInfo.InvariantCulture.NumberFormat);
            }
            if (flag == "#MUSIC")
            {
                result.music = split [1].TrimEnd(';');
            }
            if (flag == "#STOPS")
            {
                Debug.Log("Got to stops");
                List <string> stopStrings = new List <string> ();

                stopStrings.Add(split [1]);

                string nextLn = file.ReadLine();
                while (!nextLn.Contains(";"))
                {
                    stopStrings.Add(nextLn);
                    nextLn = file.ReadLine();
                }

                for (int i = 0; i < stopStrings.Count; i++)
                {
                    float    beat, time;
                    string[] splitStop = stopStrings [i].Split('=');
                    beat = float.Parse(splitStop [0]);
                    time = float.Parse(splitStop [1]);
                    result.stops.Add(new Stop(beat, time));
                    Debug.Log($"Added {time} stop at {beat}");
                }
            }
            if (flag == "#NOTES")
            {
                Chart thisChart = new Chart();
                thisChart.topLeftNotes  = new List <noteSpawn> ();
                thisChart.bottomNotes   = new List <noteSpawn> ();
                thisChart.topRightNotes = new List <noteSpawn> ();
                int currentBpm = 0;                                             //This will be the index of the BPM currently being used to determine note times.

                file.ReadLine();                                                //dance-single
                file.ReadLine();                                                //chart artist
                thisChart.difficulty = file.ReadLine().TrimEnd(':');            //Hard
                thisChart.rating     = int.Parse(file.ReadLine().TrimEnd(':')); //18

                //Start to parse the lines of the chart

                string lineOfChart = file.ReadLine();
                //Get rid of any leading whitespace
                while (lineOfChart == null)
                {
                    lineOfChart = file.ReadLine();
                }

                int           measureCounter = 0;
                float         beatCounter    = 0;
                List <string> notesInMeasure = new List <string> ();
                while (lineOfChart[0] != ';')
                {
                    if (lineOfChart [0] == ',')
                    {
                        //End of Measure, calculate note times&types and add to chart
                        //Debug.Log ($"Measure has {notesInMeasure.Count} subdivisions.");
                        //Debug.Log (beatCounter);
                        //Before determining any note times, check if BPM has changed.
                        if (currentBpm + 1 < result.bpms.Count)
                        {
                            if (beatCounter >= result.bpms [currentBpm + 1].beat)
                            {
                                currentBpm++;
                            }
                        }

                        //Debug.Log ($"Step is {step}.");
                        for (int i = 0; i < notesInMeasure.Count; i++)
                        {
                            /*
                             * Todo: the code that creates noteSpawn structs and pushes them
                             * to the list of notes for the chart. Adding a note will involve
                             * calculating the amount of time past the current time (using BPM
                             * and amount of notes in measure). Make sure to advance currentTime
                             * while adding notes.
                             */
                            //advance beat
                            beatCounter += (float)(4 / (float)notesInMeasure.Count);
                            //Debug.Log ($"Current time is {currentTime}");

                            string lineNote = "";
                            if (notesInMeasure [i] [0] == '1')
                            {
                                //add a top left note at the current time
                                lineNote += "topleft ";
                                thisChart.topLeftNotes.Add(new noteSpawn(beatCounter, "tap"));
                            }
                            if (notesInMeasure [i] [1] == '1')
                            {
                                //add a bottom note at the current time
                                lineNote += "bottom ";
                                thisChart.bottomNotes.Add(new noteSpawn(beatCounter, "tap"));
                            }
                            if (notesInMeasure [i] [2] == '1')
                            {
                                //add a top right note at the current time
                                lineNote += "topright";
                                thisChart.topRightNotes.Add(new noteSpawn(beatCounter, "tap"));
                            }

                            //Debug.Log ("this note is : " + lineNote);
                        }

                        //Clean up measure variables
                        notesInMeasure.Clear();
                        measureCounter = 0;
                    }
                    else if (lineOfChart[0] != ' ')
                    {
                        //just read a note, save the note string and keep counting.
                        notesInMeasure.Add(lineOfChart);
                        measureCounter++;
                    }
                    lineOfChart = file.ReadLine();
                }

                //Debug.Log ($"{thisChart.difficulty}, level {thisChart.rating}");
                result.charts.Add(thisChart);
            }
        }

        return(result);
    }
    static void SubmitDataGlobals(Song song, List <string> stringData)
    {
        const int TEXT_POS_TICK       = 0;
        const int TEXT_POS_EVENT_TYPE = 2;
        const int TEXT_POS_DATA_1     = 3;

#if TIMING_DEBUG
        float time = Time.realtimeSinceStartup;
#endif

        List <Anchor> anchorData = new List <Anchor>();

        foreach (string line in stringData)
        {
            string[] stringSplit = line.Split(' ');
            uint     tick;
            string   eventType;
            if (stringSplit.Length > TEXT_POS_DATA_1 && uint.TryParse(stringSplit[TEXT_POS_TICK], out tick))
            {
                eventType = stringSplit[TEXT_POS_EVENT_TYPE];
                eventType = eventType.ToLower();
            }
            else
            {
                continue;
            }

            switch (eventType)
            {
            case ("ts"):
                uint numerator;
                uint denominator = 2;

                if (!uint.TryParse(stringSplit[TEXT_POS_DATA_1], out numerator))
                {
                    continue;
                }

                if (stringSplit.Length > TEXT_POS_DATA_1 + 1 && !uint.TryParse(stringSplit[TEXT_POS_DATA_1 + 1], out denominator))
                {
                    continue;
                }

                song.Add(new TimeSignature(tick, numerator, (uint)(Mathf.Pow(2, denominator))), false);
                break;

            case ("b"):
                uint value;
                if (!uint.TryParse(stringSplit[TEXT_POS_DATA_1], out value))
                {
                    continue;
                }

                song.Add(new BPM(tick, value), false);
                break;

            case ("e"):
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                int  startIndex = TEXT_POS_DATA_1;
                bool isSection  = false;

                if (stringSplit.Length > TEXT_POS_DATA_1 + 1 && stringSplit[TEXT_POS_DATA_1] == "\"section")
                {
                    startIndex = TEXT_POS_DATA_1 + 1;
                    isSection  = true;
                }

                for (int i = startIndex; i < stringSplit.Length; ++i)
                {
                    sb.Append(stringSplit[i].Trim('"'));
                    if (i < stringSplit.Length - 1)
                    {
                        sb.Append(" ");
                    }
                }

                if (isSection)
                {
                    song.Add(new Section(sb.ToString(), tick), false);
                }
                else
                {
                    song.Add(new Event(sb.ToString(), tick), false);
                }

                break;

            case ("a"):
                ulong anchorValue;
                if (ulong.TryParse(stringSplit[TEXT_POS_DATA_1], out anchorValue))
                {
                    Anchor a;
                    a.tick       = tick;
                    a.anchorTime = (float)(anchorValue / 1000000.0d);
                    anchorData.Add(a);
                }
                break;

            default:
                break;
            }
        }

        BPM[] bpms = song.syncTrack.OfType <BPM>().ToArray();        // BPMs are currently uncached
        foreach (Anchor anchor in anchorData)
        {
            int arrayPos = SongObjectHelper.FindClosestPosition(anchor.tick, bpms);
            if (bpms[arrayPos].tick == anchor.tick)
            {
                bpms[arrayPos].anchor = anchor.anchorTime;
            }
            else
            {
                // Create a new anchored bpm
                uint value;
                if (bpms[arrayPos].tick > anchor.tick)
                {
                    value = bpms[arrayPos - 1].value;
                }
                else
                {
                    value = bpms[arrayPos].value;
                }

                BPM anchoredBPM = new BPM(anchor.tick, value);
                anchoredBPM.anchor = anchor.anchorTime;
            }
        }
#if TIMING_DEBUG
        Debug.Log("Synctrack load time: " + (Time.realtimeSinceStartup - time));
#endif
    }
    static MoonscraperEngine.ICommand GenerateCommandsAdjustedForAnchors(BPM currentBPM, uint desiredBpmValue)
    {
        List <SongEditCommand> commands = new List <SongEditCommand>();

        int pos = SongObjectHelper.FindObjectPosition(currentBPM, currentBPM.song.bpms);

        if (pos != SongObjectHelper.NOTFOUND)
        {
            BPM anchor      = null;
            BPM bpmToAdjust = null;

            int anchorPos = 0;

            // Get the next anchor
            for (int i = pos + 1; i < currentBPM.song.bpms.Count; ++i)
            {
                if (currentBPM.song.bpms[i].anchor != null)
                {
                    anchor    = currentBPM.song.bpms[i];
                    anchorPos = i;
                    // Get the bpm before that anchor
                    bpmToAdjust = currentBPM.song.bpms[i - 1];

                    break;
                }
            }

            if (anchor == null || bpmToAdjust == currentBPM)
            {
                commands.Add(new SongEditModify <BPM>(currentBPM, new BPM(currentBPM.tick, desiredBpmValue, currentBPM.anchor)));
                return(new BatchedSongEditCommand(commands));
            }

            // Calculate the minimum the bpm can adjust to
            const float MIN_DT = 0.01f;

            float bpmTime    = (float)anchor.anchor - MIN_DT;
            float resolution = currentBPM.song.resolution;
            // Calculate the time of the 2nd bpm pretending that the adjustable one is super close to the anchor
            for (int i = anchorPos - 1; i > pos + 1; --i)
            {
                // Calculate up until 2 bpms before the anchor
                // Re-hash of the actual time calculation equation in Song.cs
                bpmTime -= (float)TickFunctions.DisToTime(currentBPM.song.bpms[i - 1].tick, currentBPM.song.bpms[i].tick, resolution, currentBPM.song.bpms[i - 1].value / 1000.0f);
            }

            float timeBetweenFirstAndSecond = bpmTime - currentBPM.time;
            // What bpm will result in this exact time difference?
            uint minVal = (uint)(Mathf.Ceil((float)TickFunctions.DisToBpm(currentBPM.song.bpms[pos].tick, currentBPM.song.bpms[pos + 1].tick, timeBetweenFirstAndSecond, currentBPM.song.resolution)) * 1000);

            if (desiredBpmValue < minVal)
            {
                desiredBpmValue = minVal;
            }

            BPM  anchorBPM = anchor;
            uint oldValue  = currentBPM.value;

            ChartEditor editor = ChartEditor.Instance;
            currentBPM.value = desiredBpmValue; // Very much cheating, better to not do this
            double deltaTime = (double)anchorBPM.anchor - editor.currentSong.LiveTickToTime(bpmToAdjust.tick, editor.currentSong.resolution);
            uint   newValue  = (uint)Mathf.Round((float)(TickFunctions.DisToBpm(bpmToAdjust.tick, anchorBPM.tick, deltaTime, editor.currentSong.resolution) * 1000.0d));
            currentBPM.value = oldValue;

            uint finalValue = oldValue;
            if (deltaTime > 0 && newValue > 0)
            {
                if (newValue != 0)
                {
                    commands.Add(new SongEditModify <BPM>(bpmToAdjust, new BPM(bpmToAdjust.tick, newValue, bpmToAdjust.anchor)));
                }

                finalValue = desiredBpmValue;
            }

            desiredBpmValue = finalValue;
        }

        if (desiredBpmValue == currentBPM.value)
        {
            return(null);
        }

        commands.Add(new SongEditModify <BPM>(currentBPM, new BPM(currentBPM.tick, desiredBpmValue, currentBPM.anchor)));
        return(new BatchedSongEditCommand(commands));
    }
        public async Task <ActionResult> UpdateBPM(string submit, int BPMID, int WalktroughID, int PrelimID)
        {
            string username = User.Identity.Name;

            db.Configuration.ProxyCreationEnabled = false;
            BPM         oldData  = db.BPMs.AsNoTracking().Where(p => p.BPMID.Equals(BPMID)).FirstOrDefault();
            BPM         bpm      = db.BPMs.Find(BPMID);
            int?        prelimId = PrelimID;
            Preliminary prelim   = db.Preliminaries.Find(prelimId);

            string user = submit.Contains("By") ? submit.Split('y')[1] : String.Empty;

            if (submit == "Save")
            {
                bpm.Status = "Draft";
            }
            else if (submit == "Send Back")
            {
                bpm.Status = HelperController.GetStatusSendback(db, "BPM", bpm.Status);
            }
            else if (submit == "Approve")
            {
                bpm.Status = "Approve";
            }
            else if (submit == "Submit For Review By" + user)
            {
                bpm.Status = "Pending for Review by" + user;
            }
            else if (submit == "Submit For Approve By" + user)
            {
                bpm.Status = "Pending for Approve by" + user;
                string userToSentEmail = String.Empty;
                if (user.Trim() == "CIA")
                {
                    userToSentEmail = prelim.PICID;
                    if (userToSentEmail != null)
                    {
                        sentSingleEmailBPM(userToSentEmail, bpm, WalktroughID);
                    }
                    else
                    {
                        sentEmailBPM(bpm, user.Trim(), WalktroughID);
                    }
                }
                else if (user.Trim() == "Pengawas")
                {
                    userToSentEmail = prelim.SupervisorID;
                    if (userToSentEmail != null)
                    {
                        sentSingleEmailBPM(userToSentEmail, bpm, WalktroughID);
                    }
                    else
                    {
                        sentEmailBPM(bpm, user.Trim(), WalktroughID);
                    }
                }
                else if (user.Trim() == "Ketua Tim")
                {
                    userToSentEmail = prelim.TeamLeaderID;
                    if (userToSentEmail != null)
                    {
                        sentSingleEmailBPM(userToSentEmail, bpm, WalktroughID);
                    }
                    else
                    {
                        sentEmailBPM(bpm, user.Trim(), WalktroughID);
                    }
                }
                else if (user.Trim() == "Member")
                {
                    userToSentEmail = prelim.MemberID;
                    if (userToSentEmail != null)
                    {
                        sentSingleEmailBPM(userToSentEmail, bpm, WalktroughID);
                    }
                    else
                    {
                        sentEmailBPM(bpm, user.Trim(), WalktroughID);
                    }
                }
            }

            auditTransact.CreateAuditTrail("Update", bpm.WalktroughID, "BusinessProces", oldData, bpm, username);
            db.Entry(bpm).State = EntityState.Modified;
            await db.SaveChangesAsync();

            TempData["message"] = "BPM successfully updated!";
            return(RedirectToAction("Create", new { id = bpm.WalktroughID }));
        }
Пример #19
0
 void Awake()
 {
     GC           = GameObject.FindGameObjectWithTag("GameController").GetComponent <GameController>();
     BPM          = GameObject.FindGameObjectWithTag("GameController").GetComponent <BPM>();
     timeForShoot = BPM.timeForBeat;
 }
Пример #20
0
    bool AdjustForAnchors(uint newBpmValue)
    {
        ChartEditor.GetInstance().songObjectPoolManager.SetAllPoolsDirty();

        int pos = SongObjectHelper.FindObjectPosition(currentBPM, currentBPM.song.bpms);

        if (pos != SongObjectHelper.NOTFOUND)
        {
            BPM anchor      = null;
            BPM bpmToAdjust = null;

            int anchorPos = 0;

            // Get the next anchor
            for (int i = pos + 1; i < currentBPM.song.bpms.Count; ++i)
            {
                if (currentBPM.song.bpms[i].anchor != null)
                {
                    anchor    = currentBPM.song.bpms[i];
                    anchorPos = i;
                    // Get the bpm before that anchor
                    bpmToAdjust = currentBPM.song.bpms[i - 1];

                    break;
                }
            }

            if (anchor == null || bpmToAdjust == currentBPM)
            {
                if (currentBPM.value != newBpmValue)
                {
                    ChartEditor.isDirty = true;
                }

                currentBPM.value = newBpmValue;
                return(true);
            }

            // Calculate the minimum the bpm can adjust to
            const float MIN_DT = 0.01f;

            float bpmTime    = (float)anchor.anchor - MIN_DT;
            float resolution = currentBPM.song.resolution;
            // Calculate the time of the 2nd bpm pretending that the adjustable one is super close to the anchor
            for (int i = anchorPos - 1; i > pos + 1; --i)
            {
                // Calculate up until 2 bpms before the anchor
                // Re-hash of the actual time calculation equation in Song.cs
                bpmTime -= (float)TickFunctions.DisToTime(currentBPM.song.bpms[i - 1].tick, currentBPM.song.bpms[i].tick, resolution, currentBPM.song.bpms[i - 1].value / 1000.0f);
            }

            float timeBetweenFirstAndSecond = bpmTime - currentBPM.time;
            // What bpm will result in this exact time difference?
            uint minVal = (uint)(Mathf.Ceil((float)TickFunctions.DisToBpm(currentBPM.song.bpms[pos].tick, currentBPM.song.bpms[pos + 1].tick, timeBetweenFirstAndSecond, currentBPM.song.resolution)) * 1000);

            if (newBpmValue < minVal)
            {
                newBpmValue = minVal;
            }

            if (anchorAdjustment == null)
            {
                anchorAdjustment = bpmToAdjust;
                anchorAdjustmentOriginalValue = new BPM(bpmToAdjust);
            }

            BPM  anchorBPM = anchor;
            uint oldValue  = currentBPM.value;
            currentBPM.value = newBpmValue;

            double deltaTime = (double)anchorBPM.anchor - editor.currentSong.LiveTickToTime(bpmToAdjust.tick, editor.currentSong.resolution);
            uint   newValue  = (uint)Mathf.Round((float)(TickFunctions.DisToBpm(bpmToAdjust.tick, anchorBPM.tick, deltaTime, editor.currentSong.resolution) * 1000.0d));
            currentBPM.value = oldValue;
            if (deltaTime > 0 && newValue > 0)
            {
                if (newValue != 0)
                {
                    bpmToAdjust.value = newValue;
                }
                currentBPM.value = newBpmValue;

                ChartEditor.isDirty = true;
            }
        }
        else
        {
            if (currentBPM.value != newBpmValue)
            {
                ChartEditor.isDirty = true;
            }

            currentBPM.value = newBpmValue;
        }

        return(true);
    }
Пример #21
0
        public static rtn_data GenerateProposalTask(string UserCode, string CustomerName, string IdCardNumber, string Mobile, string AppOrderId)
        {
            rtn_data rtn            = new rtn_data();
            var      para_get_bp_id = new Dictionary <string, object>();

            para_get_bp_id.Add("login_nme", UserCode);

            var bp_id_result = BizService.ExecuteBizNonQuery("DropdownListDataSource", "get_bp_id", para_get_bp_id);

            if (bp_id_result == null || bp_id_result.Count == 0)
            {
                AppUtility.Engine.LogWriter.Write("后台获取bp_id失败,login_nme-->" + UserCode);
                rtn.code    = -1;
                rtn.message = "获取bp_id失败,login_nme-->" + UserCode;
            }
            else
            {
                #region 自动发起流程的参数
                #region 人员关系表参数
                var app_type = new List <object>();
                app_type.Add(new
                {
                    IDENTIFICATION_CODE1 = 1,
                    APPLICANT_TYPE       = "I",
                    MAIN_APPLICANT       = "Y",
                    NAME1 = CustomerName
                });
                #endregion

                #region 申请人信息表参数
                var app_detail = new List <object>();
                app_detail.Add(new
                {
                    IDENTIFICATION_CODE2 = 1,
                    FIRST_THI_NME        = CustomerName,
                    ID_CARD_NBR          = IdCardNumber
                });
                #endregion

                #region 地址信息表参数
                var app_ads = new List <object>();
                app_ads.Add(new
                {
                    ADDRESS_CODE         = 1,
                    IDENTIFICATION_CODE4 = 1
                });
                #endregion

                #region 电话信息表参数
                var app_tel = new List <object>();
                app_tel.Add(new
                {
                    PHONE_SEQ_ID         = 1,
                    IDENTIFICATION_CODE5 = 1,
                    ADDRESS_CODE5        = 1,
                    PHONE_NUMBER         = Mobile
                });
                #endregion

                #region 工作信息表参数
                var app_work = new List <object>();
                app_work.Add(new
                {
                    EMPLOYEE_LINE_ID     = 1,
                    IDENTIFICATION_CODE6 = 1
                });
                #endregion

                var para = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    USER_NAME             = UserCode,     //FI账号
                    APPLICATION_NAME      = CustomerName, //主贷人的名称
                    APPLICANT_TYPE        = app_type,
                    APPLICATION_TYPE_NAME = "个人Individual",
                    BP_ID               = bp_id_result["BP_PRIMARY_ID"] + string.Empty,
                    AppUnionId          = AppOrderId,
                    APPLICANT_DETAIL    = app_detail,
                    ADDRESS             = app_ads,
                    APPLICANT_PHONE_FAX = app_tel,
                    EMPLOYER            = app_work
                });
                #endregion

                var r = new BPM().StartWorkflow_Base(UserCode, "APPLICATION", false, "", para);
                AppUtility.Engine.LogWriter.Write(Newtonsoft.Json.JsonConvert.SerializeObject(r));
                if (r.STATUS == "2")
                {
                    rtn.code    = 1;
                    rtn.message = r.MESSAGE;
                    rtn.data    = r.INSTANCE_ID;
                }
                else
                {
                    rtn.code    = -1;
                    rtn.message = r.MESSAGE;
                }
            }
            return(rtn);
        }
Пример #22
0
 public BPM(BPM _bpm) : base(_bpm.tick)
 {
     value  = _bpm.value;
     anchor = _bpm.anchor;
 }
Пример #23
0
 void Awake()
 {
     GC  = GameObject.FindGameObjectWithTag("GameController").GetComponent <GameController>();
     BPM = GameObject.FindGameObjectWithTag("GameController").GetComponent <BPM>();
 }
Пример #24
0
 private void Start()
 {
     GC    = GetComponent <GameController>();
     BPM   = GetComponent <BPM>();
     count = 0;
 }
Пример #25
0
        public override void Render(float delta, float mouseX, float mouseY)
        {
            // track transparency

            var editor = EditorWindow.Instance;

            int trackdim = EditorSettings.TrackOpacity;

            int[] Color1 = EditorWindow.Instance.Color1;
            int[] Color2 = EditorWindow.Instance.Color2;

            // waveform

            waveform = EditorSettings.Waveform;

            GL.Color4(Color.FromArgb(trackdim, 36, 35, 33));

            var rect = ClientRectangle;

            Glu.RenderQuad(rect);
            GL.Color3(0.2f, 0.2f, 0.2f);
            Glu.RenderQuad((int)rect.X, (int)rect.Y + rect.Height, (int)rect.Width, 1);

            var fr = editor.FontRenderer;

            float cellSize = rect.Height;
            float noteSize = cellSize * 0.65f;

            var gap = cellSize - noteSize;

            double audioTime = editor.MusicPlayer.CurrentTime.TotalMilliseconds;

            float cubeStep = editor.CubeStep;
            float posX     = (float)audioTime / 1000 * cubeStep;
            float maxX     = (float)editor.MusicPlayer.TotalTime.TotalMilliseconds / 1000f * cubeStep;

            var   zoomLvl   = editor.Zoom;
            float lineSpace = cubeStep * zoomLvl;

            float lineX = ScreenX - posX;

            if (lineX < 0)
            {
                lineX %= lineSpace;
            }

            if (waveform)
            {
                GL.Color3(0.35f, 0.35f, 0.35f);
                GL.PushMatrix();
                GL.BindVertexArray(editor.MusicPlayer.WaveModel.VaoID);
                GL.EnableVertexAttribArray(0);

                var p     = posX / maxX;
                var total = zoomLvl * maxX;

                var waveX = -posX + ScreenX + maxX / 2;
                var scale = maxX;                //;total;

                GL.Translate(waveX, rect.Height * 0.5, 0);
                GL.Scale(scale / 100000.0, -rect.Height, 1);
                GL.Translate(-50000, -0.5, 0);
                GL.LineWidth(2);
                editor.MusicPlayer.WaveModel.Render(PrimitiveType.LineStrip);
                GL.LineWidth(1);
                GL.Translate(50000 * scale, 0.5, 0);
                GL.Scale(1 / scale * 100000.0, -1.0 / rect.Height, 1);
                GL.Translate(-waveX, -rect.Height * 0.5, 0);

                GL.DisableVertexAttribArray(0);
                GL.BindVertexArray(0);
                GL.PopMatrix();
            }

            /*
             * GL.Begin(PrimitiveType.LineStrip);
             *
             * for (double x = 0; x < rect.Width + 4; x += 4)
             * {
             *      var peak = editor.MusicPlayer.GetPeak(audioTime + (x - ScreenX) / cubeStep * 1000) * rect.Height;
             *
             *      GL.Vertex2(x + 0.5f, rect.Height - peak);
             * }
             * GL.End();*/

            //render quarters of a second depending on zoom level

            /*
             * while (lineSpace > 0 && lineX < rect.Width)
             * {
             *      GL.Color3(0.85f, 0.85f, 0.85f);
             *      GL.Begin(PrimitiveType.Lines);
             *      GL.Vertex2((int)lineX + 0.5f, rect.Y);
             *      GL.Vertex2((int)lineX + 0.5f, rect.Y + 5);
             *      GL.End();
             *
             *      lineX += lineSpace;
             * }*/

            var mouseOver = false;

            //draw start line
            GL.LineWidth(2);
            GL.Color4(Color.FromArgb(Color2[0], Color2[1], Color2[2]));
            GL.Begin(PrimitiveType.Lines);
            GL.Vertex2((int)(ScreenX - posX), rect.Y);
            GL.Vertex2((int)(ScreenX - posX), rect.Y + rect.Height);
            GL.End();

            var endLineX = ScreenX - posX + maxX + 1;

            //draw end line
            GL.Color4(1f, 0f, 0f, 1);
            GL.Begin(PrimitiveType.Lines);
            GL.Vertex2((int)endLineX, rect.Y);
            GL.Vertex2((int)endLineX, rect.Y + rect.Height);
            GL.End();
            GL.LineWidth(1);

            MouseOverNote  = null;
            MouseOverPoint = null;
            Note closest = null;

            var y = rect.Y + gap / 2;

            _cs.Reset();
            for (int i = 0; i < editor.Notes.Count; i++)
            {
                Note note = EditorWindow.Instance.Notes[i];

                if (editor.GuiScreen is GuiScreenEditor gse)
                {
                    var offset = 0L;
                    long.TryParse(gse.SfxOffset.Text, out offset);

                    if (note.Ms <= (long)(EditorWindow.Instance.MusicPlayer.CurrentTime.TotalMilliseconds - offset))
                    {
                        closest = note;
                    }
                }

                note.Color = _cs.Next();

                var x = Math.Round(ScreenX - posX + note.Ms / 1000f * cubeStep);

                if (x > rect.Width)
                {
                    break;
                }

                if (x < rect.X - noteSize)
                {
                    continue;
                }

                var alphaMult = 1f;

                if (audioTime - 1 > note.Ms)                //(x <= ScreenX)
                {
                    alphaMult = 0.35f;
                }


                var noteRect = new RectangleF((int)x, (int)y, noteSize, noteSize);

                var b = MouseOverNote == null && !mouseOver && noteRect.Contains(mouseX, mouseY);

                if ((b || EditorWindow.Instance.SelectedNotes.Contains(note)) &&
                    !EditorWindow.Instance.IsDraggingNoteOnTimeLine)
                {
                    if (b)
                    {
                        MouseOverNote = note;
                        mouseOver     = true;
                        GL.Color3(0, 1, 0.25f);
                    }
                    else
                    {
                        GL.Color3(0, 0.5f, 1);
                    }

                    Glu.RenderOutline((int)(x - 4), (int)(y - 4), (int)(noteSize + 8), (int)(noteSize + 8));
                }

                var c = Color.FromArgb((int)(15 * alphaMult), (int)note.Color.R, (int)note.Color.G, (int)note.Color.B);

                GL.Color4(c);
                Glu.RenderQuad((int)x, (int)y, (int)noteSize, (int)noteSize);
                GL.Color4(note.Color.R, note.Color.G, note.Color.B, alphaMult);
                Glu.RenderOutline((int)x, (int)y, (int)noteSize, (int)noteSize);

                var gridGap = 2;
                for (int j = 0; j < 9; j++)
                {
                    var indexX = 2 - j % 3;
                    var indexY = 2 - j / 3;

                    var gridX = (int)x + indexX * (9 + gridGap) + 5;
                    var gridY = (int)y + indexY * (9 + gridGap) + 5;

                    if (Math.Round(note.X, 3) == indexX && Math.Round(note.Y, 3) == indexY)
                    {
                        GL.Color4(note.Color.R, note.Color.G, note.Color.B, alphaMult);
                        Glu.RenderQuad(gridX, gridY, 9, 9);
                    }
                    else
                    {
                        GL.Color4(note.Color.R, note.Color.G, note.Color.B, alphaMult * 0.45);
                        Glu.RenderOutline(gridX, gridY, 9, 9);
                    }
                }

                var numText = $"{(i + 1):##,###}";

                var msText = $"{note.Ms:##,###}";
                if (msText == "")
                {
                    msText = "0";
                }

                GL.Color3(Color.FromArgb(Color1[0], Color1[1], Color1[2]));
                fr.Render(numText, (int)x + 3, (int)(rect.Y + rect.Height) + 3, 16);

                GL.Color3(Color.FromArgb(Color2[0], Color2[1], Color2[2]));
                fr.Render($"{msText}ms", (int)x + 3,
                          (int)(rect.Y + rect.Height + fr.GetHeight(16)) + 3 + 2, 16);

                //draw line
                GL.Color4(1f, 1f, 1f, alphaMult);
                GL.Begin(PrimitiveType.Lines);
                GL.Vertex2((int)x + 0.5f, rect.Y + rect.Height + 3);
                GL.Vertex2((int)x + 0.5f, rect.Y + rect.Height + 28);
                GL.End();
            }

            if (_lastPlayedNote != closest)
            {
                _lastPlayedNote = closest;

                if (closest != null && editor.MusicPlayer.IsPlaying && editor.GuiScreen is GuiScreenEditor gse)
                {
                    editor.SoundPlayer.Play("hit", gse.SfxVolume.Value / (float)gse.SfxVolume.MaxValue, editor.MusicPlayer.Tempo);
                }
            }

            if (!Settings.Default.LegacyBPM)
            {
                for (var i = 0; i < BPMs.Count; i++)
                {
                    var    Bpm           = BPMs[i];
                    double nextoffset    = 0;
                    double nextLineX     = endLineX;
                    double currentoffset = Bpm.Ms;
                    double offsetint     = 60000 / Bpm.bpm / BeatDivisor;

                    if (i + 1 < BPMs.Count)
                    {
                        nextoffset = BPMs[i + 1].Ms;
                    }
                    else
                    {
                        nextoffset = editor.MusicPlayer.TotalTime.TotalMilliseconds * 2;
                    }

                    if (Bpm.bpm > 33)
                    {
                        lineSpace = 60 / Bpm.bpm * cubeStep;
                        var stepSmall = lineSpace / BeatDivisor;

                        lineX = ScreenX - posX + Bpm.Ms / 1000f * cubeStep;
                        if (lineX < 0)
                        {
                            lineX %= lineSpace;
                        }

                        if (i + 1 < BPMs.Count)
                        {
                            nextLineX = ScreenX - posX + nextoffset / 1000f * cubeStep;
                        }
                        if (nextLineX < 0)
                        {
                            nextLineX %= lineSpace;
                        }

                        if (lineSpace > 0 && lineX < rect.Width && lineX > 0)
                        {
                            //draw offset start line
                            GL.Color4(Color.FromArgb(255, 0, 0));
                            GL.Begin(PrimitiveType.Lines);
                            GL.Vertex2((int)lineX + 0.5f, 0);
                            GL.Vertex2((int)lineX + 0.5f, rect.Bottom + 56);
                            GL.End();
                        }

                        //draw timing point info
                        var x = Math.Round(ScreenX - posX + Bpm.Ms / 1000f * cubeStep);

                        var numText = $"{Bpm.bpm:##,###.###}";
                        if (numText == "")
                        {
                            numText = "0";
                        }

                        var msText = $"{Bpm.Ms:##,###}";
                        if (msText == "")
                        {
                            msText = "0";
                        }

                        GL.Color3(Color.FromArgb(Color1[0], Color1[1], Color1[2]));
                        fr.Render(numText, (int)x + 3, (int)(rect.Y + rect.Height) + 3 + 28, 16);

                        GL.Color3(Color.FromArgb(Color2[0], Color2[1], Color2[2]));
                        fr.Render($"{msText}ms", (int)x + 3,
                                  (int)(rect.Y + rect.Height + fr.GetHeight(16)) + 3 + 2 + 28, 16);

                        //render BPM lines
                        while (lineSpace > 0 && lineX < rect.Width && lineX < endLineX && lineX < nextLineX)
                        {
                            GL.Color3(Color.FromArgb(Color2[0], Color2[1], Color2[2]));
                            GL.Begin(PrimitiveType.Lines);
                            GL.Vertex2((int)lineX + 0.5f, rect.Bottom);
                            GL.Vertex2((int)lineX + 0.5f, rect.Bottom - 11);
                            GL.End();

                            for (int j = 1; j <= BeatDivisor; j++)
                            {
                                var xo = lineX + j * stepSmall;

                                if (j < BeatDivisor && xo < endLineX && xo < nextLineX)
                                {
                                    var half = j == BeatDivisor / 2 && BeatDivisor % 2 == 0;

                                    if (half)
                                    {
                                        GL.Color3(Color.FromArgb(Color2[0], Color2[1], Color2[2]));
                                    }
                                    else
                                    {
                                        GL.Color3(Color.FromArgb(Color1[0], Color1[1], Color1[2]));
                                    }

                                    GL.Begin(PrimitiveType.Lines);
                                    GL.Vertex2((int)xo + 0.5f, rect.Bottom - (half ? 7 : 4));
                                    GL.Vertex2((int)xo + 0.5f, rect.Bottom);
                                    GL.End();
                                }
                            }

                            lineX += lineSpace;
                        }

                        var w         = Math.Max(fr.GetWidth($"{Bpm.Ms:##,###}ms", 16), fr.GetWidth($"{Bpm.bpm:##,###}", 16));
                        var pointRect = new RectangleF((int)x, rect.Bottom, w + 3, 56);

                        var g = MouseOverPoint == null && pointRect.Contains(mouseX, mouseY);

                        if (g || EditorWindow.Instance._draggedPoint == Bpm &&
                            !EditorWindow.Instance.IsDraggingPointOnTimeline)
                        {
                            if (g)
                            {
                                MouseOverPoint = Bpm;
                                GL.Color3(0, 1, 0.25f);
                            }
                            else
                            {
                                GL.Color3(0, 0.5f, 1);
                            }

                            Glu.RenderOutline((int)(x - 4), rect.Bottom, w + 3 + 8, 56 + 4);
                        }
                    }
                }
            }
            else
            {
                double offsetint = 60000 / Bpm / BeatDivisor;

                if (Bpm > 33)
                {
                    lineSpace = 60 / Bpm * cubeStep;
                    var stepSmall = lineSpace / BeatDivisor;

                    lineX = ScreenX - posX + BpmOffset / 1000f * cubeStep;
                    if (lineX < 0)
                    {
                        lineX %= lineSpace;
                    }

                    if (lineSpace > 0 && lineX < rect.Width && lineX > 0)
                    {
                        //draw offset start line
                        GL.Color4(Color.FromArgb(255, 0, 0));
                        GL.Begin(PrimitiveType.Lines);
                        GL.Vertex2((int)lineX + 0.5f, 0);
                        GL.Vertex2((int)lineX + 0.5f, rect.Bottom + 56);
                        GL.End();
                    }

                    //draw timing point info
                    var x = Math.Round(ScreenX - posX + BpmOffset / 1000f * cubeStep);

                    var numText = $"{Bpm:##,###}";

                    GL.Color3(Color.FromArgb(Color1[0], Color1[1], Color1[2]));
                    fr.Render(numText, (int)x + 3, (int)(rect.Y + rect.Height) + 3 + 28, 16);

                    GL.Color3(Color.FromArgb(Color2[0], Color2[1], Color2[2]));
                    fr.Render($"{BpmOffset:##,###}ms", (int)x + 3,
                              (int)(rect.Y + rect.Height + fr.GetHeight(16)) + 3 + 2 + 28, 16);

                    //render BPM lines
                    while (lineSpace > 0 && lineX < rect.Width && lineX < endLineX)
                    {
                        GL.Color3(Color.FromArgb(Color2[0], Color2[1], Color2[2]));
                        GL.Begin(PrimitiveType.Lines);
                        GL.Vertex2((int)lineX + 0.5f, rect.Bottom);
                        GL.Vertex2((int)lineX + 0.5f, rect.Bottom - 11);
                        GL.End();

                        for (int j = 1; j <= BeatDivisor; j++)
                        {
                            var xo = lineX + j * stepSmall;

                            if (j < BeatDivisor && xo < endLineX)
                            {
                                var half = j == BeatDivisor / 2 && BeatDivisor % 2 == 0;

                                if (half)
                                {
                                    GL.Color3(Color.FromArgb(Color2[0], Color2[1], Color2[2]));
                                }
                                else
                                {
                                    GL.Color3(Color.FromArgb(Color1[0], Color1[1], Color1[2]));
                                }

                                GL.Begin(PrimitiveType.Lines);
                                GL.Vertex2((int)xo + 0.5f, rect.Bottom - (half ? 7 : 4));
                                GL.Vertex2((int)xo + 0.5f, rect.Bottom);
                                GL.End();
                            }
                        }

                        lineX += lineSpace;
                    }
                }
            }

            if (editor.GuiScreen is GuiScreenEditor gse1 && gse1.Metronome.Toggle)
            {
                //bool bdbool = true;
                double.TryParse(gse1.SfxOffset.Text, out var offset);

                var ms  = editor.MusicPlayer.CurrentTime.TotalMilliseconds - offset;
                var bpm = editor.GetCurrentBpm(editor.MusicPlayer.CurrentTime.TotalMilliseconds);
                int div = BeatDivisor;                //1;

                /*-
                 * if (bdbool)
                 * {
                 * div = BeatDivisor;
                 * }
                 */

                double interval  = 60000 / bpm.bpm / div;
                double remainder = (ms - bpm.Ms) % interval;
                double closestMS = ms - remainder;

                if (_lastPlayedMS != closestMS && remainder >= 0 && editor.MusicPlayer.IsPlaying)
                {
                    _lastPlayedMS = closestMS;

                    editor.SoundPlayer.Play("metronome", gse1.SfxVolume.Value / (float)gse1.SfxVolume.MaxValue, editor.MusicPlayer.Tempo);
                }
            }

            //draw screen line
            GL.Color4(1f, 1, 1, 0.75);
            GL.Begin(PrimitiveType.Lines);
            GL.Vertex2((int)(rect.X + ScreenX) + 0.5, rect.Y + 4);
            GL.Vertex2((int)(rect.X + ScreenX) + 0.5, rect.Y + rect.Height - 4);
            GL.End();

            //GL.Color3(1, 1, 1f);
            //FontRenderer.Print("HELLO", 0, rect.Y + rect.Height + 8);
        }
    public void Write(Song song, ExportOptions exportOptions, out string errorList)
    {
        song.UpdateCache();
        errorList = string.Empty;
        string saveString = string.Empty;

        try
        {
            string musicString  = string.Empty;
            string guitarString = string.Empty;
            string bassString   = string.Empty;
            string rhythmString = string.Empty;
            string drumString   = string.Empty;

            GetAudioStreamSaveString GetSaveAudioString = audio => {
                string audioString;
                string audioLocation = song.GetAudioLocation(audio);

                if (audioLocation != string.Empty && Path.GetDirectoryName(audioLocation).Replace("\\", "/") == Path.GetDirectoryName(path).Replace("\\", "/"))
                {
                    audioString = Path.GetFileName(audioLocation);
                }
                else
                {
                    audioString = audioLocation;
                }

                return(audioString);
            };

            musicString  = GetSaveAudioString(Song.AudioInstrument.Song);
            guitarString = GetSaveAudioString(Song.AudioInstrument.Guitar);
            bassString   = GetSaveAudioString(Song.AudioInstrument.Bass);
            rhythmString = GetSaveAudioString(Song.AudioInstrument.Rhythm);
            drumString   = GetSaveAudioString(Song.AudioInstrument.Drum);

            // Song properties
            Debug.Log("Writing song properties");
            saveString += s_chartHeaderSong;
            saveString += GetPropertiesStringWithoutAudio(song, exportOptions);

            // Song audio
            if (song.GetAudioIsLoaded(Song.AudioInstrument.Song) || (musicString != null && musicString != string.Empty))
            {
                saveString += string.Format(s_audioStreamFormat, "MusicStream", musicString);
            }

            if (song.GetAudioIsLoaded(Song.AudioInstrument.Guitar) || (guitarString != null && guitarString != string.Empty))
            {
                saveString += string.Format(s_audioStreamFormat, "GuitarStream", guitarString);
            }

            if (song.GetAudioIsLoaded(Song.AudioInstrument.Bass) || (bassString != null && bassString != string.Empty))
            {
                saveString += string.Format(s_audioStreamFormat, "BassStream", bassString);
            }

            if (song.GetAudioIsLoaded(Song.AudioInstrument.Rhythm) || (rhythmString != null && rhythmString != string.Empty))
            {
                saveString += string.Format(s_audioStreamFormat, "RhythmStream", rhythmString);
            }

            if (song.GetAudioIsLoaded(Song.AudioInstrument.Drum) || (drumString != null && drumString != string.Empty))
            {
                saveString += string.Format(s_audioStreamFormat, "DrumStream", drumString);
            }

            saveString += s_chartSectionFooter;
        }
        catch (System.Exception e)
        {
            string error = Logger.LogException(e, "Error with saving song properties");
            errorList += error + Globals.LINE_ENDING;

            saveString = string.Empty;  // Clear all the song properties because we don't want braces left open, which will screw up the loading of the chart

#if UNITY_EDITOR
            System.Diagnostics.Debugger.Break();
#endif
        }

        // SyncTrack
        Debug.Log("Writing synctrack");
        saveString += s_chartHeaderSyncTrack;
        if (exportOptions.tickOffset > 0)
        {
            saveString += new BPM().GetSaveString();
            saveString += new TimeSignature().GetSaveString();
        }

        saveString += GetSaveString(song, song.syncTrack, exportOptions, ref errorList);
        saveString += s_chartSectionFooter;

        // Events
        Debug.Log("Writing events");
        saveString += s_chartHeaderEvents;
        saveString += GetSaveString(song, song.eventsAndSections, exportOptions, ref errorList);
        saveString += s_chartSectionFooter;

        // Charts
        foreach (Song.Instrument instrument in EnumX <Song.Instrument> .Values)
        {
            string instrumentSaveString = string.Empty;
            switch (instrument)
            {
            case (Song.Instrument.Guitar):
                instrumentSaveString = "Single";
                break;

            case (Song.Instrument.GuitarCoop):
                instrumentSaveString = "DoubleGuitar";
                break;

            case (Song.Instrument.Bass):
                instrumentSaveString = "DoubleBass";
                break;

            case (Song.Instrument.Rhythm):
                instrumentSaveString = "DoubleRhythm";
                break;

            case (Song.Instrument.Drums):
                instrumentSaveString = "Drums";
                break;

            case (Song.Instrument.Keys):
                instrumentSaveString = "Keyboard";
                break;

            case (Song.Instrument.GHLiveGuitar):
                instrumentSaveString = "GHLGuitar";
                break;

            case (Song.Instrument.GHLiveBass):
                instrumentSaveString = "GHLBass";
                break;

            default:
                continue;
            }

            foreach (Song.Difficulty difficulty in EnumX <Song.Difficulty> .Values)
            {
                string difficultySaveString = difficulty.ToString();

                string chartString = GetSaveString(song, song.GetChart(instrument, difficulty).chartObjects, exportOptions, ref errorList, instrument);

                if (chartString == string.Empty)
                {
                    if (exportOptions.copyDownEmptyDifficulty)
                    {
                        Song.Difficulty chartDiff = difficulty;
                        bool            exit      = false;
                        while (chartString == string.Empty)
                        {
                            switch (chartDiff)
                            {
                            case (Song.Difficulty.Easy):
                                chartDiff = Song.Difficulty.Medium;
                                break;

                            case (Song.Difficulty.Medium):
                                chartDiff = Song.Difficulty.Hard;
                                break;

                            case (Song.Difficulty.Hard):
                                chartDiff = Song.Difficulty.Expert;
                                break;

                            case (Song.Difficulty.Expert):
                            default:
                                exit = true;
                                break;
                            }

                            chartString = GetSaveString(song, song.GetChart(instrument, chartDiff).chartObjects, exportOptions, ref errorList, instrument);

                            if (exit)
                            {
                                break;
                            }
                        }

                        if (exit)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }

                saveString += string.Format(s_chartHeaderTrackFormat, difficultySaveString, instrumentSaveString);
                saveString += chartString;
                saveString += s_chartSectionFooter;
            }
        }

        // Unrecognised charts
        foreach (Chart chart in song.unrecognisedCharts)
        {
            string chartString = GetSaveString(song, chart.chartObjects, exportOptions, ref errorList, Song.Instrument.Unrecognised);

            saveString += string.Format(s_chartSectionHeaderFormat, chart.name);
            saveString += chartString;
            saveString += s_chartSectionFooter;
        }

        try
        {
            // Save to file
            File.WriteAllText(path, saveString, System.Text.Encoding.UTF8);
        }
        catch (Exception e)
        {
            Logger.LogException(e, "Error when writing text to file");
        }
    }
Пример #27
0
 /// <summary>Initializes a new instance of the <seealso cref="RelativeTimingPoint"/> class.</summary>
 /// <param name="timePosition">The time position of the event.</param>
 /// <param name="bpm">The BPM of the timing point.</param>
 /// <param name="timeSignature">The time signature of the timing point.</param>
 public RelativeTimingPoint(MeasuredTimePosition timePosition, BPM bpm, TimeSignature timeSignature)
     : base(timePosition, bpm, timeSignature)
 {
 }
Пример #28
0
    public void AddSongObjects()
    {
        List <ActionHistory.Action> record       = new List <ActionHistory.Action>();
        List <ActionHistory.Action> deleteRecord = new List <ActionHistory.Action>();

        // Need to remember to undo/redo. This current will only work once object pools are implemented.
        // Check to see what the current offset is to decide how to record
        // Will also need to check for overwrites
        // All relative to the original notes

        bool moved = false;

        for (int i = 0; i < movingSongObjects.Count; ++i)
        {
            ActionHistory.Action overwriteRecord;

            if (movingSongObjects[i] != originalSongObjects[i])
            {
                moved = true;
                deleteRecord.Add(new ActionHistory.Delete(originalSongObjects[i]));
            }

            switch ((SongObject.ID)movingSongObjects[i].classID)
            {
            case (SongObject.ID.Note):
                record.AddRange(PlaceNote.AddObjectToCurrentChart((Note)movingSongObjects[i], editor, false, false));         // Capping
                break;

            case (SongObject.ID.Starpower):
                record.AddRange(PlaceStarpower.AddObjectToCurrentChart((Starpower)movingSongObjects[i], editor, false, false));           // Capping
                break;

            case (SongObject.ID.ChartEvent):
                overwriteRecord = PlaceSongObject.OverwriteActionHistory((ChartEvent)movingSongObjects[i], editor.currentChart.events);
                if (record != null)
                {
                    record.Add(overwriteRecord);
                }
                editor.currentChart.Add((ChartEvent)movingSongObjects[i], false);
                break;

            case (SongObject.ID.BPM):
                overwriteRecord = PlaceSongObject.OverwriteActionHistory((BPM)movingSongObjects[i], editor.currentSong.bpms);
                if (record != null)
                {
                    record.Add(overwriteRecord);
                }
                BPM bpm = (BPM)movingSongObjects[i];
                editor.currentSong.Add(bpm, false);
                if (bpm.anchor != null)
                {
                    bpm.anchor = bpm.song.LiveTickToTime(bpm.tick, bpm.song.resolution);
                }

                ChartEditor.GetInstance().songObjectPoolManager.SetAllPoolsDirty();
                break;

            case (SongObject.ID.TimeSignature):
                overwriteRecord = PlaceSongObject.OverwriteActionHistory((TimeSignature)movingSongObjects[i], editor.currentSong.timeSignatures);
                if (record != null)
                {
                    record.Add(overwriteRecord);
                }
                editor.currentSong.Add((TimeSignature)movingSongObjects[i], false);
                break;

            case (SongObject.ID.Section):
                overwriteRecord = PlaceSongObject.OverwriteActionHistory((Section)movingSongObjects[i], editor.currentSong.sections);
                if (record != null)
                {
                    record.Add(overwriteRecord);
                }
                editor.currentSong.Add((Section)movingSongObjects[i], false);
                break;

            case (SongObject.ID.Event):
                overwriteRecord = PlaceSongObject.OverwriteActionHistory((Event)movingSongObjects[i], editor.currentSong.events);
                if (record != null)
                {
                    record.Add(overwriteRecord);
                }
                editor.currentSong.Add((Event)movingSongObjects[i], false);
                break;

            default:
                break;
            }
        }

        editor.currentSelectedObjects = movingSongObjects.ToArray();

        if (moved)
        {
            editor.actionHistory.Insert(deleteRecord.ToArray());                // In case user removes a bpm from an anchor area
            editor.actionHistory.Insert(bpmAnchorRecord.ToArray());

            editor.currentSong.UpdateCache();
            editor.currentChart.UpdateCache();

            editor.actionHistory.Insert(record.ToArray());
            editor.actionHistory.Insert(editor.FixUpBPMAnchors().ToArray());    // In case user moves a bpm into an anchor area
        }

        editor.currentSong.UpdateCache();
        editor.currentChart.UpdateCache();

        Reset();
    }
Пример #29
0
        private void SetSubscribes()
        {
            FilePath.Subscribe(path => IsFileSpecified.Value = !string.IsNullOrEmpty(path));

            Interval.Subscribe(interval =>
            {
                if (ignoreChange)
                {
                    return;
                }

                Model.IntervalCalculator.Interval = interval;

                ignoreChange = true;
                BPM.Value    = Model.IntervalCalculator.BPM;
                ignoreChange = false;
            });
            BPM.Subscribe(bpm =>
            {
                if (ignoreChange)
                {
                    return;
                }

                Model.IntervalCalculator.BPM = bpm;

                ignoreChange   = true;
                Interval.Value = Model.IntervalCalculator.Interval;
                ignoreChange   = false;
            });

            Action <bool> UpdateLoopParam = isInterval =>
            {
                if (isInterval)
                {
                    BPM.Value = Model.IntervalCalculator.BPM;
                }
                else
                {
                    Interval.Value = Model.IntervalCalculator.Interval;
                }
            };

            Frequency.Subscribe(freq => Model.DuplicationCounter.Frequency      = freq);
            Beat.Subscribe(beat => Model.DuplicationCounter.Beat                = beat);
            LoopNum.Subscribe(lnum => Model.DuplicationCounter.LoopCount        = lnum);
            EnableDecrement.Subscribe(dec => Model.DuplicationCounter.Decrement = dec);

            Action <int> UpdateElemNum = _ =>
            {
                ElementNum.Value = Model.DuplicationCounter.ElementCount;
                IsDuplicationCountVaild.Value = ElementNum.Value > 0;
            };

            Frequency.Subscribe(UpdateElemNum);
            Beat.Subscribe(UpdateElemNum);
            LoopNum.Subscribe(UpdateElemNum);
            EnableDecrement.Subscribe(_ => UpdateElemNum(0));

            OpenFile.Subscribe(_ =>
            {
                var ofd = new OpenFileDialog()
                {
                    Filter          = "VMDファイル(*.vmd)|*.vmd",
                    AddExtension    = true,
                    CheckFileExists = true,
                    CheckPathExists = true,
                    Multiselect     = false,
                };

                if (ofd.ShowDialog() ?? false)
                {
                    string fileName = ofd.FileName;
                    ReadFile(fileName);
                }
            });

            ExecuteGeneration.Subscribe(_ =>
            {
                try
                {
                    var filePath   = FilePath.Value ?? "";
                    var sourceVMD  = Model.ReadFile(filePath);
                    var savePath   = Path.Combine(Path.GetDirectoryName(filePath) ?? "", Path.GetFileNameWithoutExtension(filePath) + "_loop.vmd");
                    var loopMotion = Model.CreateLoopMotion(sourceVMD);
                    loopMotion.Write(savePath);
                    AppendLog($"出力が完了しました。");
                    AppendLog($"フレーム数 : {sourceVMD.Frames.Count()} → {loopMotion.Frames.Count()}");
                    AppendLog($"保存先 : {savePath}");
                    AppendLog(Environment.NewLine);
                }
                catch (FileNotFoundException)
                {
                    AppendLog("ファイルが見つかりませんでした。");
                    FilePath.Value = null;
                }
                catch (InvalidDataException)
                {
                    AppendLog("非VMDファイルが指定されました。");
                    FilePath.Value = null;
                }
                catch (Exception ex)
                {
                    AppendLog($"エラーが発生しました。{ex.Message}");
                }
            });

            FilePath.Subscribe(path => Properties.Settings.Default.FilePath      = path);
            Interval.Subscribe(iv => Properties.Settings.Default.Interval        = iv ?? 1);
            BPM.Subscribe(bpm => Properties.Settings.Default.BPM                 = bpm ?? 1);
            Frequency.Subscribe(freq => Properties.Settings.Default.Frequency    = freq);
            Beat.Subscribe(beat => Properties.Settings.Default.Beat              = beat);
            LoopNum.Subscribe(l => Properties.Settings.Default.LoopNum           = l);
            EnableDecrement.Subscribe(d => Properties.Settings.Default.Decrement = d);
        }