Exemple #1
0
 void Start()
 {
     track = GameObject.FindGameObjectsWithTag("track")[0].transform.root.gameObject;
     trackInformation = track.GetComponent<TrackInformation>();
     camera = transform.Find("Main Camera").gameObject;
     KB = gameObject.GetComponent<KartBehaviour>();
 }
Exemple #2
0
 void Start()
 {
     track            = GameObject.FindGameObjectsWithTag("track")[0].transform.root.gameObject;
     trackInformation = track.GetComponent <TrackInformation>();
     camera           = transform.Find("Main Camera").gameObject;
     KB = gameObject.GetComponent <KartBehaviour>();
 }
        private static void GetArtistAndTrack(string name, TrackInformation information)
        {
            var client  = new RestClient("https://ws.audioscrobbler.com");
            var request = new RestRequest("/2.0", Method.GET);

            request.AddParameter("method", "track.search");
            request.AddParameter("track", name);
            request.AddParameter("api_key", Properties.Settings.LastFmApiKey);
            request.AddParameter("format", "json");
            request.AddParameter("limit", 1);

            var result = client.Execute(request);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                throw new WebException();
            }

            var json = JObject.Parse(result.Content);

            var results = json["results"]["trackmatches"]["track"].Children().ToList();

            if (results.Count == 0)
            {
                return;
            }

            information.Artist = results[0]["artist"].ToString();
            information.Name   = results[0]["name"].ToString();
        }
        private static void GetThumbnail(TrackInformation information)
        {
            // Request search for the track
            var client  = new RestClient("https://api.discogs.com");
            var request = new RestRequest("/database/search", Method.GET);

            request.AddParameter("q", $"{information.Artist} {information.Name}");
            request.AddParameter("type", "release");
            request.AddParameter("per_page", 1);
            request.AddParameter("key", Properties.Settings.DiscogsApiKey);
            request.AddParameter("secret", Properties.Settings.DiscogsApiSecret);
            request.AddHeader("Accept", "application/vnd.discogs.v2.html+json");

            var response = client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new WebException();
            }

            var searchResponse = JObject.Parse(response.Content);
            var searchResults  = searchResponse["results"].Children().ToList();

            if (searchResults.Count == 0)
            {
                return;
            }

            information.CoverUrl = searchResults[0]["thumb"].ToString();
            information.Album    = searchResults[0]["title"].ToString();
        }
Exemple #5
0
        public static TrackInformation Decode(byte[] response)
        {
            if (response.Length < 32)
            {
                return(null);
            }

            var decoded = new TrackInformation
            {
                DataLength               = (ushort)((response[0] << 8) + response[1]),
                LogicalTrackNumber       = response[2],
                SessionNumber            = response[3],
                LayerJumpRecordingStatus = (LayerJumpRecordingStatus)(response[5] >> 6),
                Damage    = (response[5] & 0x20) == 0x20,
                Copy      = (response[5] & 0x10) == 0x10,
                TrackMode = (byte)(response[5] & 0xF),
                RT        = (response[6] & 0x80) == 0x80,
                Blank     = (response[6] & 0x40) == 0x40,
                Packet    = (response[6] & 0x20) == 0x20,
                FP        = (response[6] & 0x10) == 0x10,
                DataMode  = (byte)(response[6] & 0xF),
                LraV      = (response[7] & 0x02) == 0x02,
                NwaV      = (response[7] & 0x01) == 0x01,
                LogicalTrackStartAddress =
                    (uint)((response[8] << 24) + (response[9] << 16) + (response[10] << 8) + response[11]),
                NextWritableAddress =
                    (uint)((response[12] << 24) + (response[13] << 16) + (response[14] << 8) + response[15]),
                FreeBlocks      = (uint)((response[16] << 24) + (response[17] << 16) + (response[18] << 8) + response[19]),
                FixedPacketSize =
                    (uint)((response[20] << 24) + (response[21] << 16) + (response[22] << 8) + response[23]),
                LogicalTrackSize =
                    (uint)((response[24] << 24) + (response[25] << 16) + (response[26] << 8) + response[27]),
                LastRecordedAddress =
                    (uint)((response[28] << 24) + (response[29] << 16) + (response[30] << 8) + response[31])
            };

            if (response.Length < 48)
            {
                return(decoded);
            }

            decoded.LogicalTrackNumber += (ushort)(response[32] << 8);

            decoded.SessionNumber += (ushort)(response[33] << 8);

            decoded.ReadCompatibilityLba =
                (uint)((response[36] << 24) + (response[37] << 16) + (response[38] << 8) + response[39]);

            decoded.NextLayerJumpAddress =
                (uint)((response[40] << 24) + (response[41] << 16) + (response[42] << 8) + response[43]);

            decoded.LastLayerJumpAddress =
                (uint)((response[44] << 24) + (response[45] << 16) + (response[46] << 8) + response[47]);

            return(decoded);
        }
Exemple #6
0
 private void AddTrackInformation()
 {
     _trackInformation["SomeTrack"] = new TrackInformation
     {
         Name              = "SomeTrack",
         Location          = "SomeWhere",
         DegradationPoints = new List <int> {
             10, 20
         }
     };
 }
Exemple #7
0
 void Start()
 {
     TI            = GameObject.Find("track").GetComponent <TrackInformation>();                 // Get TrackInformation
     miniMapSprite = TI.miniMapTexture;                                                          // Get the sprite of the minimap from TrackInformation
     gameObject.GetComponent <Image>().sprite = miniMapSprite;                                   // Set it to be the current minimap sprite
     mapWidth    = gameObject.GetComponent <RectTransform>().rect.width;                         // Width of the minimap
     mapHeight   = gameObject.GetComponent <RectTransform>().rect.height;                        // Height of the minimap
     sceneWidth  = TI.trackWidth;                                                                // Width of the track
     sceneHeight = TI.trackHeight;                                                               // Height of the track
     offSetX     = TI.miniMapOffSetX;                                                            // Offset if the minimap marker is on the wrong place
     offSetZ     = TI.miniMapOffSetZ;
 }
        private TrackInformation CreateTrackInformation(string singleTackData)
        {
            var separatedInfo = singleTackData.Split("|");
            var points        = separatedInfo[2].Split(',').Select(int.Parse).ToList();
            var trackInfo     = new TrackInformation
            {
                Name              = separatedInfo[0],
                Location          = separatedInfo[1],
                DegradationPoints = points
            };

            return(trackInfo);
        }
Exemple #9
0
    void Start()
    {
        TI = GameObject.Find("track").GetComponent<TrackInformation>();                             // Get TrackInformation
        miniMapSprite = TI.miniMapTexture;                                                          // Get the sprite of the minimap from TrackInformation
        gameObject.GetComponent<Image>().sprite = miniMapSprite;                                    // Set it to be the current minimap sprite
        mapWidth = gameObject.GetComponent<RectTransform>().rect.width;                             // Width of the minimap
        mapHeight = gameObject.GetComponent<RectTransform>().rect.height;                           // Height of the minimap
        sceneWidth = TI.trackWidth;                                                                 // Width of the track
        sceneHeight = TI.trackHeight;                                                               // Height of the track
        offSetX = TI.miniMapOffSetX;                                                                // Offset if the minimap marker is on the wrong place
        offSetZ = TI.miniMapOffSetZ;


    }
        /// <summary>
        /// Gets the track information.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static TrackInformation GetTrackInformation(string name)
        {
            var information = new TrackInformation();

            // Normalize track title
            name = Regex.Replace(name, @"[\[【].+?[\]】]", "");
            name = Regex.Replace(name, @"[^\w\s\d-]", "");

            GetArtistAndTrack(name, information);
            if (string.IsNullOrEmpty(information.Name) || string.IsNullOrEmpty(information.Artist))
            {
                return(information);
            }

            GetThumbnail(information);

            return(information);
        }
Exemple #11
0
        FindEventResult GenerateTrackEvent(RecordingInformation recording, TrackInformation track)
        {
            FindEventResult eventResult = new FindEventResult();

            eventResult.RecordingToken = recording.RecordingToken;
            if (track != null)
            {
                eventResult.TrackToken = track.TrackToken;
            }
            else
            {
                eventResult.TrackToken = "";
            }
            eventResult.Event = new NotificationMessageHolderType();
            //eventResult.Event.ProducerReference = new EndpointReferenceType();
            //eventResult.Event.ProducerReference.Address = new AttributedURIType(){Value= "http://localhost/dut.asmx"};
            eventResult.Event.Topic         = new TopicExpressionType();
            eventResult.Event.Topic.Dialect = "http://www.onvif.org/ver10/tev/topicExpression/ConcreteSet";
            return(eventResult);
        }
        public static TrackInformation GetTrackInformation(PlaylistItem item)
        {
            var information = new TrackInformation();

            var searchTerm = NormalizeSongTitle(item.Title);

            information.Name = searchTerm;

            try
            {
                var client  = new RestClient("https://itunes.apple.com");
                var request = new RestRequest("/search");

                request.AddParameter("term", searchTerm);
                request.AddParameter("country", "US");
                request.AddParameter("media", "music");
                request.AddParameter("limit", 1);

                var result = client.Execute(request);
                var parsed = JObject.Parse(result.Content);
                var tracks = parsed["results"].Children().ToList();
                if (tracks.Count == 0)
                {
                    return(information);
                }

                var artwork = tracks[0]["artworkUrl100"].ToString();
                information.CoverUrl = artwork.Replace("100x100", "600x600");
                information.Name     = tracks[0]["trackName"].ToString();
                information.Album    = tracks[0]["collectionName"].ToString();
                information.Artist   = tracks[0]["artistName"].ToString();
            }
            catch (Exception ex)
            {
                Logger.Warn(ex, "Error retrieving artwork for track {0}", information);
            }

            return(information);
        }
Exemple #13
0
        void CompareLists(IEnumerable <RecordingInformation> recordings1, IEnumerable <RecordingInformation> recordings2)
        {
            bool          ok     = true;
            StringBuilder logger = new StringBuilder();

            List <string> common = new List <string>();

            // check that all tokens from full list are present in list of found recordings
            foreach (RecordingInformation item in recordings1)
            {
                string token = item.RecordingToken;

                if (!recordings2.Any(RI => RI.RecordingToken == token))
                {
                    logger.AppendFormat("Recording with token {0} not found in second list{1}", item.RecordingToken, Environment.NewLine);
                    ok = false;
                }
                else
                {
                    common.Add(token);
                }
            }

            foreach (RecordingInformation item in recordings2)
            {
                string token = item.RecordingToken;

                if (!recordings1.Any(RI => RI.RecordingToken == token))
                {
                    logger.AppendFormat("Recording with token {0} not found in first list{1}", item.RecordingToken, Environment.NewLine);
                    ok = false;
                }
            }

            // for common only

            foreach (RecordingInformation info1 in recordings1)
            {
                string token = info1.RecordingToken;
                if (!common.Contains(token))
                {
                    continue;
                }

                RecordingInformation info2 = recordings2.FirstOrDefault(RI => RI.RecordingToken == token);

                StringBuilder dump = new StringBuilder(string.Format("Information for recording with token '{0}' is different:{1}", token, Environment.NewLine));

                bool localOk = true;

                if (info1.Content != info2.Content)
                {
                    localOk = false;
                    dump.AppendLine("   Content is different");
                }
                if (info1.RecordingStatus != info2.RecordingStatus)
                {
                    localOk = false;
                    dump.AppendLine("   RecordingStatus is different");
                }

                Action <Func <RecordingInformation, bool>, Func <RecordingInformation, System.DateTime>, string> check =
                    new Action <Func <RecordingInformation, bool>, Func <RecordingInformation, System.DateTime>, string>(
                        (specifiedSelector, valueSelector, fieldName) =>
                {
                    bool specified1 = specifiedSelector(info1);
                    bool specified2 = specifiedSelector(info2);

                    if (specified1 || specified2)
                    {
                        if (specified1 && specified2)
                        {
                            System.DateTime value1 = valueSelector(info1);
                            System.DateTime value2 = valueSelector(info2);

                            if (value1 != value2)
                            {
                                localOk = false;
                                dump.AppendFormat("   {0} is different{1}", fieldName, Environment.NewLine);
                            }
                        }
                        else
                        {
                            if (!specified1)
                            {
                                localOk = false;
                                dump.AppendFormat("   {0} not specified for the first list{1}", fieldName,
                                                  Environment.NewLine);
                            }
                            if (!specified2)
                            {
                                localOk = false;
                                dump.AppendFormat("   {0} not specified for the second list{1}", fieldName,
                                                  Environment.NewLine);
                            }
                        }
                    }
                });

                check(RI => RI.EarliestRecordingSpecified, RI => RI.EarliestRecording, "EarliestRecording");
                check(RI => RI.LatestRecordingSpecified, RI => RI.LatestRecording, "LatestRecording");

                RecordingSourceInformation source1 = info1.Source;
                RecordingSourceInformation source2 = info2.Source;

                if (source1 != null || source2 != null)
                {
                    if (source1 != null && source2 != null)
                    {
                        Action <string, Func <RecordingSourceInformation, string> > checkStringAction =
                            new Action <string, Func <RecordingSourceInformation, string> >(
                                (name, fieldSelector) =>
                        {
                            string value1 = fieldSelector(source1);
                            string value2 = fieldSelector(source2);
                            if (value1 != value2)
                            {
                                localOk = false;
                                dump.AppendFormat("   Source.{0} field is different {1}", name, Environment.NewLine);
                            }
                        });

                        checkStringAction("Address", S => S.Address);
                        checkStringAction("Description", S => S.Description);
                        checkStringAction("Location", S => S.Location);
                        checkStringAction("Name", S => S.Name);
                        checkStringAction("SourceId", S => S.SourceId);
                    }
                    else
                    {
                        if (source1 == null)
                        {
                            dump.AppendLine("   RecordingSourceInformation is missing for the item from the first list{0}");
                            localOk = false;
                        }
                        if (source2 == null)
                        {
                            dump.AppendLine("   RecordingSourceInformation is missing for the item from the second list{0}");
                            localOk = false;
                        }
                    }
                }

                bool trackList1Ok = info1.Track != null && info1.Track.Length > 0;
                bool trackList2Ok = info2.Track != null && info2.Track.Length > 0;

                if (trackList1Ok || trackList2Ok)
                {
                    if (trackList1Ok && trackList2Ok)
                    {
                        // compare track by track

                        bool tracksOk = true;

                        TrackInformation[] tracks1 = info1.Track;
                        TrackInformation[] tracks2 = info2.Track;

                        StringBuilder sb       = new StringBuilder();
                        bool          tokensOk = ArrayUtils.ValidateTokens(tracks1, TR => TR.TrackToken, sb);
                        if (!tokensOk)
                        {
                            dump.AppendFormat("   List of tracks is not valid for item from the first list - not all checks will be performed{0}", Environment.NewLine);
                            tracksOk = false;
                        }

                        sb       = new StringBuilder();
                        tokensOk = ArrayUtils.ValidateTokens(tracks2, TR => TR.TrackToken, sb);
                        if (!tokensOk)
                        {
                            dump.AppendFormat("   List of tracks is not valid for item from the second list - not all checks will be performed{0}", Environment.NewLine);
                            tracksOk = false;
                        }

                        {
                            List <string> commonTracks = new List <string>();

                            // compare tokens
                            foreach (TrackInformation info in tracks1)
                            {
                                TrackInformation inf = tracks2.FirstOrDefault(T => T.TrackToken == info.TrackToken);
                                if (inf == null)
                                {
                                    tracksOk = false;
                                    // not found
                                    dump.AppendFormat("   Track with token {0} not found for recording from second list{1}", info.TrackToken, Environment.NewLine);
                                }
                                else
                                {
                                    int cnt = tracks1.Count(T => T.TrackToken == info.TrackToken);
                                    if (cnt == 1)
                                    {
                                        commonTracks.Add(info.TrackToken);
                                    }
                                }
                            }
                            foreach (TrackInformation info in tracks2)
                            {
                                TrackInformation inf = tracks1.FirstOrDefault(T => T.TrackToken == info.TrackToken);
                                if (inf == null)
                                {
                                    tracksOk = false;
                                    // not found
                                    dump.AppendFormat("   Track with token {0} not found for recording from  first list{1}", info.TrackToken, Environment.NewLine);
                                }
                            }

                            {
                                // compare common

                                foreach (TrackInformation trackInfo1 in tracks1)
                                {
                                    string trackToken = trackInfo1.TrackToken;

                                    if (!commonTracks.Contains(trackToken))
                                    {
                                        continue;
                                    }

                                    TrackInformation[] infos = tracks2.Where(T => T.TrackToken == trackToken).ToArray();
                                    if (infos.Length != 1)
                                    {
                                        // error is added to log already
                                        continue;
                                    }
                                    TrackInformation trackInfo2 = infos[0];

                                    // DataFrom, DataTo, Description, TrackType

                                    if (trackInfo1.Description != trackInfo2.Description)
                                    {
                                        tracksOk = false;
                                        dump.AppendFormat("   Description is different for tracks with token '{0}'{1}", trackToken, Environment.NewLine);
                                    }

                                    if (trackInfo1.TrackType != trackInfo2.TrackType)
                                    {
                                        tracksOk = false;
                                        dump.AppendFormat("   TrackType is different for tracks with token '{0}' {1}", trackToken, Environment.NewLine);
                                    }

                                    if (trackInfo1.DataFrom != trackInfo2.DataFrom)
                                    {
                                        tracksOk = false;
                                        dump.AppendFormat("   DataFrom is different for tracks with token '{0}' {1}", trackToken, Environment.NewLine);
                                    }
                                    if (trackInfo1.DataTo != trackInfo2.DataTo)
                                    {
                                        tracksOk = false;
                                        dump.AppendFormat("   DataTo is different for tracks with token '{0}' {1}", trackToken, Environment.NewLine);
                                    }
                                }
                            }
                        }

                        localOk = localOk && tracksOk;
                    }
                    else
                    {
                        if (!trackList1Ok)
                        {
                            dump.AppendFormat("   Track list is missing for the item from the first list{0}",
                                              Environment.NewLine);
                            localOk = false;
                        }
                        if (!trackList2Ok)
                        {
                            dump.AppendFormat("   Track list is missing for the item from the first list{0}",
                                              Environment.NewLine);
                            localOk = false;
                        }
                    }
                }

                if (!localOk)
                {
                    logger.Append(dump.ToString());
                    ok = false;
                }
            }

            Assert(ok, logger.ToStringTrimNewLine(), "Check that all recordings are returned");
        }
Exemple #14
0
        protected bool CompareTracks(
            GetTracksResponseList list,
            TrackInformation[] tracks,
            string itemToken,
            StringBuilder logger)
        {
            bool ok = true;

            //Validate:  list not null, list.Tracks not empty, tracks not empty
            if (list == null || list.Track == null || list.Track.Length == 0)
            {
                if (tracks == null || tracks.Length == 0)
                {
                    // skip validation for this lists
                    return(true);
                }
                else
                {
                    logger.AppendFormat(
                        "List of tracks is empty when information is got via GetRecordings for recording with token '{0}'{1}",
                        itemToken, Environment.NewLine);
                    return(false);
                }
            }

            if (tracks == null || tracks.Length == 0)
            {
                logger.AppendFormat(
                    "List of tracks is empty when information is got via GetRecordingSearchResults for recording with token '{0}'{1}",
                    itemToken, Environment.NewLine);
                return(false);
            }

            if (tracks.Length != list.Track.Length)
            {
                logger.AppendFormat(
                    "Number of tracks is different for recording with token '{0}'{1}",
                    itemToken, Environment.NewLine);
                return(false);
            }

            //
            // validate tokens
            //

            GetTracksResponseItem[] tracksList = list.Track;

            // check that tokens are unique
            StringBuilder sb       = new StringBuilder();
            bool          tokensOk = ArrayUtils.ValidateTokens(tracksList, TR => TR.TrackToken, sb);

            if (!tokensOk)
            {
                logger.AppendFormat("List of tracks is not valid when received from GetRecordings. {0}{1}", sb.ToStringTrimNewLine(), Environment.NewLine);
                ok = false;
            }

            sb       = new StringBuilder();
            tokensOk = ArrayUtils.ValidateTokens(tracks, TR => TR.TrackToken, sb);
            if (!tokensOk)
            {
                logger.AppendFormat("List of tracks is not valid when received from GetRecordingSearchResults. {0}{1}", sb.ToStringTrimNewLine(), Environment.NewLine);
                ok = false;
            }

            if (!ok)
            {
                return(false);
            }

            //
            // May be skip this comparison (and token validation)
            // When for each track in tracks find track with the same token
            //  if 0 - NOK
            //  if 2 and more - don't validate, NOK
            // Then for each track in second list find track in first list
            //  if 1 - already checked
            //  if 0 - NOK
            //  if 2 and more - NOK
            //

            ok = ArrayUtils.CompareTokensLists(tracks,
                                               T => T.TrackToken,
                                               string.Format("list got via GetRecordingSearchResults for recording with token '{0}' ", itemToken),
                                               tracksList, T => T.TrackToken,
                                               string.Format("list got via GetRecording for recording with token '{0}' ", itemToken),
                                               "Track",
                                               logger);

            if (!ok)
            {
                return(false);
            }

            //
            // fields to compare: Description, TrackType (find via TrackToken)
            //
            foreach (GetTracksResponseItem item in tracksList)
            {
                string trackToken = item.TrackToken;

                // if track token is not unique, don't perform check
                if (tracksList.Count(T => T.TrackToken == trackToken) > 1)
                {
                    // error is added to log already
                    continue;
                }

                if (item.Configuration == null)
                {
                    ok = false;
                    logger.AppendFormat("Configuration is missing for tracks with token '{0}' (recording {1}). Skip validation for this item.{2}",
                                        trackToken, itemToken, Environment.NewLine);

                    continue;
                }

                TrackInformation[] infos = tracks.Where(T => T.TrackToken == trackToken).ToArray();
                if (infos.Length != 1)
                {
                    // error is added to log already
                    continue;
                }
                TrackInformation info = infos[0];

                if (item.Configuration.Description != info.Description)
                {
                    ok = false;
                    logger.AppendFormat("Description is different for tracks with token '{0}' (recording '{1}'){2}",
                                        trackToken, itemToken, Environment.NewLine);
                }

                if (item.Configuration.TrackType != info.TrackType)
                {
                    ok = false;
                    logger.AppendFormat("TrackType is different for tracks with token '{0}' (recording '{1}'){2}",
                                        trackToken, itemToken, Environment.NewLine);
                }
            }

            return(ok);
        }
        void ValidateTrackEvents(RecordingInformation recording,
                                 TrackInformation track,
                                 IEnumerable <FindEventResult> results,
                                 Dictionary <FindEventResult, XmlElement> elements,
                                 bool checkEdges)
        {
            {
                Func <FindEventResult, bool> eventCheck =
                    (E =>
                {
                    bool topicMatches = CheckEventTopic(E, elements[E], "tns1:RecordingHistory/Track/State",
                                                        TNS1NAMESPACE);

                    return(topicMatches);
                });

                List <FindEventResult> filtered = results.Where(E => eventCheck(E) && E.TrackToken == track.TrackToken).OrderBy(E => E.Time).ToList();

                bool dataPresentOk   = true;
                bool?lastDataPresent = null;
                if (checkEdges)
                {
                    lastDataPresent = false;

                    // checkEdges = false means that interval is narrowed and virtual events are sent
                    // in this case 1 event is OK
                    Assert(filtered.Count >= 2,
                           string.Format(
                               "Not enough events with topic=tns1:RecordingHistory/Track/State, RecordingToken='{0}' for track '{1}' found in the response",
                               recording.RecordingToken, track.TrackToken),
                           string.Format("Check that at least two events with topic tns1:RecordingHistory/Track/State are present for track '{0}'", track.TrackToken));
                }

                StringBuilder dump = new StringBuilder();
                for (int i = 0; i < filtered.Count; i++)
                {
                    FindEventResult ev = filtered[i];

                    XmlElement message = ev.Event.Message;

                    string value = GetSimpleItem(message, "IsDataPresent");

                    if (value == null)
                    {
                        dataPresentOk = false;
                        dump.AppendFormat(
                            string.Format(
                                "IsDataPresent value not found for event with RecordingToken='{0}', Time='{1}'{2}",
                                ev.RecordingToken, ev.Time.StdDateTimeToString(), Environment.NewLine));
                    }
                    else
                    {
                        bool dataPresent;
                        bool attrOk = bool.TryParse(value, out dataPresent);
                        if (!attrOk)
                        {
                            dataPresentOk = false;
                            dump.AppendFormat(
                                string.Format(
                                    "IsDataPresent value for event with RecordingToken='{0}', Time='{1}' is incorrect ({2}){3}",
                                    ev.RecordingToken, ev.Time.StdDateTimeToString(), value, Environment.NewLine));
                        }
                        else
                        {
                            if (ev.StartStateEvent)
                            {
                                continue;
                            }

                            if (lastDataPresent.HasValue)
                            {
                                if (dataPresent == lastDataPresent)
                                {
                                    dataPresentOk = false;
                                    if (i == 0)
                                    {
                                        dump.AppendFormat(
                                            string.Format(
                                                "IsDataPresent value for first event with RecordingToken='{0}', Time='{1}' is false {2}",
                                                ev.RecordingToken, ev.Time.StdDateTimeToString(), Environment.NewLine));
                                    }
                                    else
                                    {
                                        dump.AppendFormat(
                                            string.Format(
                                                "IsDataPresent value for event with RecordingToken='{0}', Time='{1}' is {2} while previous is also {2}{3}",
                                                ev.RecordingToken, ev.Time.StdDateTimeToString(), dataPresent,
                                                Environment.NewLine));
                                    }
                                }
                            }
                            lastDataPresent = dataPresent;
                        }
                    }
                }

                Assert(dataPresentOk, dump.ToStringTrimNewLine(), "Check that IsDataPresent values in events are correct");
            }
        }
        void ValidateTrackEvents(RecordingInformation recording,
                                 TrackInformation track,
                                 IEnumerable <FindEventResult> results,
                                 Dictionary <FindEventResult, XmlElement> elements,
                                 bool checkEdges, bool forward)
        {
            Func <FindEventResult, bool> eventCheck = E => CheckEventTopic(E, elements[E], "tns1:RecordingHistory/Track/State", TNS1NAMESPACE);

            IEnumerable <FindEventResult> filtered = results.Where(E => eventCheck(E) && E.TrackToken == track.TrackToken).OrderBy(E => E.Time);

            bool dataPresentOk   = true;
            bool?lastDataPresent = null;

            if (checkEdges)
            {
                //If checkEdges == true => It is expected that searchInterval includes the entire recording
                //In this case IsRecording == true for event with min Time(first) and false for event with max Time(last)
                //By spec, check only event with min Time
                lastDataPresent = false;

                // checkEdges = false means that interval is narrowed and virtual events are sent
                // in this case 1 event is OK
                Assert(filtered.Count() >= 2,
                       string.Format("Not enough events with topic=tns1:RecordingHistory/Track/State, RecordingToken='{0}' for track '{1}' found in the response",
                                     recording.RecordingToken, track.TrackToken),
                       string.Format("Check that at least two events with topic tns1:RecordingHistory/Track/State are present for track '{0}'", track.TrackToken));
            }

            StringBuilder dump  = new StringBuilder();
            bool          first = true;

            foreach (FindEventResult ev in filtered)
            {
                bool topicMatches = CheckEventTopic(ev, elements[ev], "tns1:RecordingHistory/Track/State", TNS1NAMESPACE);
                if (!topicMatches)
                {
                    continue;
                }

                bool f = first;
                first = false;

                XmlElement message = ev.Event.Message;

                string value = GetSimpleItem(message, "IsDataPresent");

                if (value == null)
                {
                    dataPresentOk = false;
                    dump.AppendFormat("IsDataPresent value not found for event with RecordingToken='{0}', Time='{1}'{2}",
                                      ev.RecordingToken, ev.Time.StdDateTimeToString(), Environment.NewLine);
                }
                else
                {
                    bool dataPresent = false;
                    bool attrOk      = true;

                    try
                    {
                        dataPresent = XmlConvert.ToBoolean(value);
                    }
                    catch (Exception)
                    {
                        attrOk = false;
                    }

                    if (!attrOk)
                    {
                        dataPresentOk = false;
                        dump.AppendFormat("IsDataPresent value for event with RecordingToken='{0}', Time='{1}' is incorrect ({2}){3}",
                                          ev.RecordingToken, ev.Time.StdDateTimeToString(), value, Environment.NewLine);
                    }
                    else
                    {
                        if (ev.StartStateEvent)
                        {
                            continue;
                        }

                        if (lastDataPresent.HasValue)
                        {
                            if (dataPresent == lastDataPresent)
                            {
                                dataPresentOk = false;
                                if (f)
                                {
                                    dump.AppendFormat("IsDataPresent value for first event with RecordingToken='{0}', Time='{1}' is false {2}",
                                                      ev.RecordingToken, ev.Time.StdDateTimeToString(), Environment.NewLine);
                                }
                                else
                                {
                                    dump.AppendFormat("IsDataPresent value for event with RecordingToken='{0}', Time='{1}' is {2} while previous is also {2}{3}",
                                                      ev.RecordingToken, ev.Time.StdDateTimeToString(), dataPresent, Environment.NewLine);
                                }
                            }
                        }
                        lastDataPresent = dataPresent;
                    }
                }
            }

            Assert(dataPresentOk, dump.ToStringTrimNewLine(), "Check that IsDataPresent values in events are correct");
        }
Exemple #17
0
	// Update is called once per frame


	void Update () {
	    switch(currentState)
        {
            case State.STARTING:
                {
                    startTimer += Time.deltaTime;
                    if (startTimer >= startDelay)
                        setState(State.RACING);
                    if (startDelay - startTimer <= 1.0f && !playersInitialized && isServer)
                    {
                        GameObject.Find("PlayerList").GetComponent<PlayerList>().SendPlayerInfo();
                        playersInitialized = true;
                    }
                    startTimerText.GetComponent<Text>().text = ((int)(startDelay - startTimer)).ToString(); 
                    break;
                }
            case State.RACING:
                {
                    List<DebugPlayer> tempPlayerList = new List<DebugPlayer>();
                    for (int i = 0; i < players.Count; i++ )
                    {
                        DebugPlayer dp = new DebugPlayer();
                        Player p = players[i];
                        Placement placement = p.gameObject.GetComponent<Placement>();
                        TrackInformation track = GameObject.FindGameObjectsWithTag("track")[0].transform.root.gameObject.GetComponent<TrackInformation>();

                        dp.gameObject = p.gameObject;
                        dp.currentLap = placement.currentLap;
                        dp.currentCheckpointIndex = placement.currentCheckPointIndex;
                        dp.distanceToNextCheckpoint = Vector3.Distance( track.checkPoints[dp.currentCheckpointIndex + 1].transform.position,dp.gameObject.transform.position);
                        tempPlayerList.Add(dp);
                    }
                    players.Clear();
                   for(int j = 0; j < tempPlayerList.Count; j++)
                   {
                        DebugPlayer currentBest = new DebugPlayer();
                        currentBest.gameObject = null;
                        for (int i = 0; i < tempPlayerList.Count; i++)
                        {
                            DebugPlayer tempPlayer = tempPlayerList[i];
                            if (containsPlayer(tempPlayer.gameObject))
                                continue;
                            if(currentBest.gameObject != null)
                            {
                                if(currentBest.currentLap == tempPlayer.currentLap)
                                {
                                    
                                        
                                    if(currentBest.currentCheckpointIndex == tempPlayer.currentCheckpointIndex)
                                    {
                                         if(currentBest.distanceToNextCheckpoint > tempPlayer.distanceToNextCheckpoint)
                                        {
                                            currentBest = tempPlayer;
                                        }
                                    }
                                    else if (currentBest.currentCheckpointIndex < tempPlayer.currentCheckpointIndex)
                                        currentBest = tempPlayer;
                                }
                                else if (currentBest.currentLap < tempPlayer.currentLap)
                                    currentBest = tempPlayer;
                            }
                            else
                            {
                                currentBest = tempPlayer;
                            }
                        }

                        Player p = new Player(players.Count + 1, currentBest.gameObject);
                       players.Add(p);

                    }
                        break;
                }
            case State.DONE_RACING:
                {
                    break;
                }
        }
	}
 public void SetSelectedTrack(TrackInformation trackInformation)
 {
     _selectedTrack = trackInformation;
     RecalculateForEachTyre();
 }
        void ValidateTrackEvents(RecordingInformation recording,
                                 TrackInformation track,
                                 IEnumerable <FindEventResult> results,
                                 Dictionary <FindEventResult, XmlElement> elements,
                                 bool checkEdges, bool outsideRange)
        {
            Func <FindEventResult, bool> eventCheck = E => CheckEventTopic(E, elements[E], "tns1:RecordingHistory/Track/State", TNS1NAMESPACE);

            var propertuOperationPriority = new Dictionary <string, int>()
            {
                { OnvifMessage.INITIALIZED, 0 },
                { OnvifMessage.CHANGED, 1 },
                { OnvifMessage.DELETED, 2 }
            };
            //If two events has the same time then event with "Initialized" flag should be first.
            var filtered = results.Where(E => eventCheck(E) && E.TrackToken == track.TrackToken).OrderBy(E => propertuOperationPriority[E.Event.Message.GetAttribute(OnvifMessage.PROPERTYOPERATIONTYPE)])
                           .OrderBy(E => E.Time);

            // checkEdges = false means that interval is narrowed and virtual events are sent
            // in this case 1 event is OK
            Assert(filtered.Count() >= (checkEdges ? 2 : 1),
                   string.Format("Not enough events with topic=tns1:RecordingHistory/Track/State, RecordingToken='{0}' for track '{1}' found in the response",
                                 recording.RecordingToken, track.TrackToken),
                   string.Format("Check that at least {0} with topic tns1:RecordingHistory/Track/State are present for track '{1}'",
                                 checkEdges ? "two events" : "one event", track.TrackToken));

            bool dataPresentOk   = true;
            bool?lastDataPresent = null;

            if (checkEdges)
            {
                //If checkEdges == true => It is expected that searchInterval includes the entire recording
                //In this case IsRecording == true for event with min Time(first) and false for event with max Time(last)
                //By spec, check only event with min Time

                if (outsideRange)
                {
                    //FindEvents was called with range wider than recording's range.
                    //Events with PropertyOperation = 'Initialized' and IsDataPresent = 'false' are possible.

                    var firstEvent = filtered.First();

                    bool isDataPresent = false;
                    try
                    {
                        var isDataPresentValue = GetSimpleItem(firstEvent.Event.Message, "IsDataPresent");
                        isDataPresent = XmlConvert.ToBoolean(isDataPresentValue);
                    }
                    catch (Exception e)
                    {
                        Assert(false,
                               string.Format("Failed to retrieve value of isDataPresent flag: {0}", e.Message),
                               "Retrieve value of isDataPresent flag in event with earliest time");
                    }

                    string operationType = "";
                    try
                    { operationType = firstEvent.Event.Message.GetAttribute(OnvifMessage.PROPERTYOPERATIONTYPE); }
                    catch (Exception e)
                    {
                        if (!isDataPresent)
                        {
                            Assert(false,
                                   string.Format("Failed to retrieve value of PropertyOperation flag: {0}", e.Message),
                                   "Retrieve value of PropertyOperation flag in event with earliest time");
                        }
                    }

                    Assert(isDataPresent || (!isDataPresent && OnvifMessage.INITIALIZED == operationType),
                           "Expected that earliest event has IsDataPresent = 'true' or OperationType = 'Initialized' and IsDataPresent = 'false'"
                           + Environment.NewLine
                           + string.Format("Actually: OperationType = '{0}' and IsDataPresent = '{1}'", operationType, isDataPresent),
                           "Check value of IsDataPresent flag in event with earliest time");

                    lastDataPresent = !isDataPresent;
                }
                else
                {
                    lastDataPresent = false;
                }
            }

            StringBuilder dump  = new StringBuilder();
            bool          first = true;

            foreach (FindEventResult ev in filtered)
            {
                bool f = first;
                first = false;

                XmlElement message = ev.Event.Message;

                string value = GetSimpleItem(message, "IsDataPresent");

                if (value == null)
                {
                    dataPresentOk = false;
                    dump.AppendFormat("IsDataPresent value not found for event with RecordingToken='{0}', Time='{1}'{2}",
                                      ev.RecordingToken, ev.Time.StdDateTimeToString(), Environment.NewLine);
                }
                else
                {
                    bool dataPresent = false;
                    bool attrOk      = true;

                    try
                    { dataPresent = XmlConvert.ToBoolean(value); }
                    catch (Exception)
                    { attrOk = false; }

                    if (!attrOk)
                    {
                        dataPresentOk = false;
                        dump.AppendFormat("IsDataPresent value for event with RecordingToken='{0}', Time='{1}' is incorrect ({2}){3}",
                                          ev.RecordingToken, ev.Time.StdDateTimeToString(), value, Environment.NewLine);
                    }
                    else
                    {
                        if (ev.StartStateEvent)
                        {
                            continue;
                        }

                        if (lastDataPresent.HasValue)
                        {
                            if (dataPresent == lastDataPresent)
                            {
                                dataPresentOk = false;
                                if (f)
                                {
                                    dump.AppendFormat("IsDataPresent value for first event with RecordingToken='{0}', Time='{1}' is false {2}",
                                                      ev.RecordingToken, ev.Time.StdDateTimeToString(), Environment.NewLine);
                                }
                                else
                                {
                                    dump.AppendFormat("IsDataPresent value for event with RecordingToken='{0}', Time='{1}' is {2} while previous is also {2}{3}",
                                                      ev.RecordingToken, ev.Time.StdDateTimeToString(), dataPresent, Environment.NewLine);
                                }
                            }
                        }
                        lastDataPresent = dataPresent;
                    }
                }
            }

            Assert(dataPresentOk, dump.ToStringTrimNewLine(), "Check that IsDataPresent values in events are correct");
        }