コード例 #1
0
        public virtual Task <RoleLeaveZoneResponse> DoPlayerLeaveAsync(AreaZonePlayer player, RoleLeaveZoneRequest leave)
        {
            var tcs = new System.Threading.Tasks.TaskCompletionSource <RoleLeaveZoneResponse>();

            this.node.PlayerLeave(player,
                                  (c) =>
            {
                tcs.TrySetResult(new RoleLeaveZoneResponse()
                {
                    lastScenePos = new Data.ZonePosition()
                    {
                        x = c.Actor.X,
                        y = c.Actor.Y,
                        z = c.Actor.Z,
                    },
                    curHP             = c.Actor.CurrentHP,
                    curMP             = c.Actor.CurrentMP,
                    LeaveZoneSaveData = c.LastZoneSaveData,
                });
            },
                                  (e) =>
            {
                tcs.TrySetResult(new RoleLeaveZoneResponse()
                {
                    s2c_code = RoleLeaveZoneResponse.CODE_ERROR,
                    s2c_msg  = e.Message,
                });
            });
            return(tcs.Task);
        }
コード例 #2
0
ファイル: AppDelegate.cs プロジェクト: xcodeuuuuu66699/gMusic
        public void SetUpApp(UIApplication app)
        {
            try
            {
                Strings.Culture = new System.Globalization.CultureInfo(NSLocale.CurrentLocale.LanguageCode);
            }
            catch (Exception ex)
            {
                LogManager.Shared.Log($"Error setting Culture {System.Threading.Thread.CurrentThread.CurrentCulture}");
            }
            SimpleAuth.OnePassword.Activate();
            ApiManager.Shared.Load();
            App.AlertFunction = (t, m) => { new UIAlertView(t, m, null, "Ok").Show(); };
            App.Invoker       = app.BeginInvokeOnMainThread;
            App.OnPlaying     = () =>
            {
                if (playingBackground != 0)
                {
                    return;
                }
                playingBackground = app.BeginBackgroundTask(() =>
                {
                    app.EndBackgroundTask(playingBackground);
                    playingBackground = 0;
                });
            };
            App.OnStopped = () =>
            {
                if (playingBackground == 0)
                {
                    return;
                }
                app.EndBackgroundTask(playingBackground);
                playingBackground = 0;
            };

            App.OnShowSpinner = (title) => { BTProgressHUD.ShowContinuousProgress(title, ProgressHUD.MaskType.Clear); };

            App.OnDismissSpinner  = BTProgressHUD.Dismiss;
            App.OnCheckForOffline = (message) =>
            {
                var tcs = new System.Threading.Tasks.TaskCompletionSource <bool>();
                new AlertView(Strings.DoYouWantToContinue, message)
                {
                    { Strings.Continue, () => tcs.TrySetResult(true) },
                    { Strings.Nevermind, () => tcs.TrySetResult(false), true },
                }.Show(window.RootViewController);
                return(tcs.Task);
            };
            NotificationManager.Shared.LanguageChanged += (s, e) =>
            {
                window.RootViewController = new RootViewController();
            };
#pragma warning disable 4014
            App.Start();
#pragma warning restore 4014
            AutolockPowerWatcher.Shared.CheckStatus();
        }
コード例 #3
0
 public virtual async Task <RoleEnterZoneResponse> DoPlayerEnterAsync(AreaZonePlayer player, RoleEnterZoneRequest enter)
 {
     if (await player.OnEnterAsync() == false)
     {
         log.Error("Can Not Find Session Or Logic : " + enter.roleSessionName + " : " + enter.roleUUID);
     }
     try
     {
         player.SessionReconnect();
         var tcs = new System.Threading.Tasks.TaskCompletionSource <RoleEnterZoneResponse>();
         this.node.PlayerEnter(player, ToAddUnit(enter), client =>
         {
             if (HasAddPlayer == false)
             {
                 HasAddPlayer = true;
             }
             client.Actor.SetAttribute(nameof(AreaZonePlayer.RoleSessionName), player.RoleSessionName);
             tcs.TrySetResult(new RoleEnterZoneResponse()
             {
                 s2c_code           = RoleEnterZoneResponse.CODE_OK,
                 mapTemplateID      = this.MapTemplateID,
                 zoneUUID           = this.ZoneUUID,
                 zoneTemplateID     = this.ZoneTemplateID,
                 roleBattleData     = enter.roleData,
                 roleDisplayName    = enter.roleDisplayName,
                 roleUnitTemplateID = enter.roleUnitTemplateID,
                 roleScenePos       = new ZonePosition()
                 {
                     x = client.Actor.X,
                     y = client.Actor.Y,
                     z = client.Actor.Z
                 },
                 areaName  = service.SelfAddress.ServiceName,
                 areaNode  = service.SelfAddress.ServiceNode,
                 guildUUID = enter.guildUUID,
             });
         }, err =>
         {
             tcs.TrySetResult(new RoleEnterZoneResponse()
             {
                 s2c_code = RoleEnterZoneResponse.CODE_ERROR,
                 s2c_msg  = err.Message,
             });
         });
         return(await tcs.Task);
     }
     catch (Exception err)
     {
         log.Error(err);
         return(new RoleEnterZoneResponse()
         {
             s2c_code = RoleEnterZoneResponse.CODE_ERROR,
             s2c_msg = err.Message,
         });
     }
 }
コード例 #4
0
        private async Task SendGetPeers(Node target)
        {
            NodeId distance = target.Id.Xor(infoHash);

            ClosestActiveNodes.Add(distance, target);

            GetPeers m = new GetPeers(engine.LocalId, infoHash);

            activeQueries++;
            var args = await engine.SendQueryAsync(m, target);

            activeQueries--;

            // We want to keep a list of the top (K) closest nodes which have responded
            int index = ClosestActiveNodes.Values.IndexOf(target);

            if (index >= Bucket.MaxCapacity || args.TimedOut)
            {
                ClosestActiveNodes.RemoveAt(index);
            }

            if (args.TimedOut)
            {
                if (activeQueries == 0)
                {
                    tcs.TrySetResult(new Node[0]);
                }
                return;
            }

            GetPeersResponse response = (GetPeersResponse)args.Response;

            // Ensure that the local Node object has the token. There may/may not be
            // an additional copy in the routing table depending on whether or not
            // it was able to fit into the table.
            target.Token = response.Token;
            if (response.Values != null)
            {
                // We have actual peers!
                engine.RaisePeersFound(infoHash, Peer.Decode(response.Values));
            }
            else if (response.Nodes != null)
            {
                // We got a list of nodes which are closer
                IEnumerable <Node> newNodes = Node.FromCompactNode(response.Nodes);
                foreach (Node closer in Node.CloserNodes(infoHash, ClosestNodes, newNodes, Bucket.MaxCapacity))
                {
                    await SendGetPeers(closer);
                }
            }

            if (activeQueries == 0)
            {
                tcs.TrySetResult(ClosestActiveNodes.Values.ToArray());
            }
        }
コード例 #5
0
        /// <summary>
        /// Ожидает пока окно не будет готово к взаимодействию
        /// </summary>
        /// <returns>Задача представляющая операцию и ее статус</returns>
        public System.Threading.Tasks.Task WaitForLoadAsync()
        {
            Dispatcher.VerifyAccess();

            if (this.IsLoaded)
            {
                return(new System.Threading.Tasks.Task(() => { }));
            }

            System.Threading.Tasks.TaskCompletionSource <object> tcs = new System.Threading.Tasks.TaskCompletionSource <object>();

            RoutedEventHandler handler = null;

            handler = (sender, args) =>
            {
                this.Loaded -= handler;

                this.Focus();

                tcs.TrySetResult(null);
            };

            this.Loaded += handler;

            return(tcs.Task);
        }
コード例 #6
0
 public async virtual Task StartAsync(CancellationToken cancellationToken)
 {
     plaintextResult         = new StringBytes(_helloWorldPayload);
     mApiServer              = new HttpApiServer();
     mApiServer.Options.Port = 8080;
     mApiServer.Options.BufferPoolMaxMemory = 500;
     mApiServer.Options.MaxConnections      = 100000;
     mApiServer.Options.Statistical         = false;
     mApiServer.Options.LogLevel            = BeetleX.EventArgs.LogType.Error;
     mApiServer.Options.LogToConsole        = true;
     mApiServer.Register(typeof(Program).Assembly);
     HeaderTypeFactory.SERVAR_HEADER_BYTES = Encoding.ASCII.GetBytes("Server: TFB\r\n");
     mApiServer.HttpConnected += (o, e) =>
     {
         e.Session["DB"] = new RawDb(new ConcurrentRandom(), Npgsql.NpgsqlFactory.Instance);
     };
     mApiServer.Started += (o, e) =>
     {
         mComplete.TrySetResult(new object());
     };
     mApiServer.Open();
     RawDb._connectionString = "Server=tfb-database;Database=hello_world;User Id=benchmarkdbuser;Password=benchmarkdbpass;Maximum Pool Size=256;NoResetOnClose=true;Enlist=false;Max Auto Prepare=4;Multiplexing=true;Write Coalescing Delay Us=500;Write Coalescing Buffer Threshold Bytes=1000";
     //RawDb._connectionString = "Server=192.168.2.19;Database=hello_world;User Id=benchmarkdbuser;Password=benchmarkdbpass;Maximum Pool Size=256;NoResetOnClose=true;Enlist=false;Max Auto Prepare=3";
     await mComplete.Task;
 }
コード例 #7
0
        private static void TransferCompletionToTask <T>(System.Threading.Tasks.TaskCompletionSource <T> tcs, System.ComponentModel.AsyncCompletedEventArgs e, Func <T> getResult, Action unregisterHandler)
        {
            if (e.UserState != tcs)
            {
                return;
            }

            try
            {
                unregisterHandler();
            }
            finally
            {
                if (e.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (e.Error != null)
                {
                    tcs.TrySetException(e.Error);
                }
                else
                {
                    tcs.TrySetResult(getResult());
                }
            }
        }
コード例 #8
0
ファイル: AppDelegate.cs プロジェクト: jasonhan803/gMusic
        public void SetUpApp(UIApplication app)
        {
            SimpleAuth.OnePassword.Activate();
            ApiManager.Shared.Load();
            App.AlertFunction = (t, m) => { new UIAlertView(t, m, null, "Ok").Show(); };
            App.Invoker       = app.BeginInvokeOnMainThread;
            App.OnPlaying     = () =>
            {
                if (playingBackground != 0)
                {
                    return;
                }
                playingBackground = app.BeginBackgroundTask(() =>
                {
                    app.EndBackgroundTask(playingBackground);
                    playingBackground = 0;
                });
            };
            App.OnStopped = () =>
            {
                if (playingBackground == 0)
                {
                    return;
                }
                app.EndBackgroundTask(playingBackground);
                playingBackground = 0;
            };

            App.OnShowSpinner = (title) => { BTProgressHUD.ShowContinuousProgress(title, ProgressHUD.MaskType.Clear); };

            App.OnDismissSpinner  = BTProgressHUD.Dismiss;
            App.OnCheckForOffline = (message) =>
            {
                var tcs = new System.Threading.Tasks.TaskCompletionSource <bool>();
                new AlertView(Strings.DoYouWantToContinue, message)
                {
                    { Strings.Continue, () => tcs.TrySetResult(true) },
                    { Strings.Nevermind, () => tcs.TrySetResult(false), true },
                }.Show(window.RootViewController);
                return(tcs.Task);
            };
#pragma warning disable 4014
            App.Start();
#pragma warning restore 4014
        }
コード例 #9
0
 public void OnComplete(Android.Gms.Tasks.Task task)
 {
     if (task.IsSuccessful)
     {
         var docsObj = task.Result;
         if (docsObj is QuerySnapshot docs)
         {
             _tcs.TrySetResult(docs.Convert <T>());
         }
     }
 }
コード例 #10
0
        /// <summary>
        /// Begins to show the MetroWindow's overlay effect.
        /// </summary>
        /// <returns>A task representing the process.</returns>
        public System.Threading.Tasks.Task ShowOverlayAsync()
        {
            if (_OverlayBox == null)
            {
                throw new InvalidOperationException("OverlayBox can not be founded in this MetroWindow's template. Are you calling this before the window has loaded?");
            }

            var tcs = new System.Threading.Tasks.TaskCompletionSource <object>();

            if (IsOverlayVisible() && _OverlayStoryboard == null)
            {
                //No Task.FromResult in .NET 4.
                tcs.SetResult(null);
                return(tcs.Task);
            }

            Dispatcher.VerifyAccess();

            _OverlayBox.Visibility = Visibility.Visible;

            var sb = (Storyboard)this.Template.Resources["OverlayFastSemiFadeIn"];

            sb = sb.Clone();

            EventHandler completionHandler = null;

            completionHandler = (sender, args) =>
            {
                sb.Completed -= completionHandler;

                if (_OverlayStoryboard == sb)
                {
                    _OverlayStoryboard = null;

                    if (IsContentDialogVisible == false)
                    {
                        IsContentDialogVisible = true;
                    }
                }

                tcs.TrySetResult(null);
            };

            sb.Completed += completionHandler;

            _OverlayBox.BeginStoryboard(sb);

            _OverlayStoryboard = sb;

            return(tcs.Task);
        }
コード例 #11
0
 /// <summary>
 /// Finds the receipt associated with the specified CustomTransactionID for the currently logged in user.
 /// </summary>
 /// <param name="customTransactionID">The CustomTransactionID of the transaction. For Facebook payments this is the OrderID of the transaction.</param>
 /// <returns>A Task&lt;IEnumerable&lt;Receipt&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IEnumerable<Receipt>> GetReceiptForUserAndTransactionIDAsync(this Buddy.Commerce commerce, string customTransactionID)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<Receipt>>();
     commerce.GetReceiptForUserAndTransactionIDInternal(customTransactionID, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #12
0
ファイル: Sound.cs プロジェクト: rajeshwarn/Buddy-DotNet-SDK
 /// <summary>
 /// Retrieves a sound from the Buddy sound library, and returns a Stream.  Your application should perisist this stream locally in a location such as IsolatedStorage.
 /// </summary>
 /// <param name="soundName">The name of the sound file.  See the Buddy Developer Portal "Sounds" page to find sounds and get their names.</param>
 /// <param name="quality">The quality level of the file to retrieve.</param>  
 public Task<Stream> GetSoundAsync(string soundName, Buddy.Sounds.SoundQuality quality)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Stream>();
     this.GetSoundInternal(soundName, quality, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #13
0
 /// <summary>
 /// Finds the receipt list based on the FromDateTime parameter for the currently logged in user.
 /// </summary>
 /// <param name="fromDateTime">The starting date and time to get receipts from, leave this blank to get all the receipts.</param>
 /// <returns>A Task&lt;IEnumerable&lt;Receipt&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IEnumerable<Receipt>> GetReceiptsForUserAsync(this Buddy.Commerce commerce, System.Nullable<System.DateTime> fromDateTime = null)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<Receipt>>();
     commerce.GetReceiptsForUserInternal(fromDateTime, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #14
0
        /// <summary>
        /// Retrieves a sound from the Buddy sound library, and returns a Stream.  Your application should perisist this stream locally in a location such as IsolatedStorage.
        /// </summary>
        /// <param name="soundName">The name of the sound file.  See the Buddy Developer Portal "Sounds" page to find sounds and get their names.</param>
        /// <param name="quality">The quality level of the file to retrieve.</param>
        public Task <Stream> GetSoundAsync(string soundName, Buddy.Sounds.SoundQuality quality)
        {
            var tcs = new System.Threading.Tasks.TaskCompletionSource <Stream>();

            this.GetSoundInternal(soundName, quality, (bcr) =>
            {
                if (bcr.Error != BuddyServiceClient.BuddyError.None)
                {
                    tcs.TrySetException(new BuddyServiceException(bcr.Error));
                }
                else
                {
                    tcs.TrySetResult(bcr.Result);
                }
            });
            return(tcs.Task);
        }
コード例 #15
0
        /// <summary>
        /// Begins to hide the TMPWindow's overlay effect.
        /// </summary>
        /// <returns>A task representing the process.</returns>
        public System.Threading.Tasks.Task HideOverlayAsync()
        {
            if (overlayBox == null)
            {
                throw new InvalidOperationException("OverlayBox can not be founded in this TMPWindow's template. Are you calling this before the window has loaded?");
            }

            if (overlayBox.Visibility == Visibility.Visible && overlayBox.Opacity == 0.0)
            {
                return(new System.Threading.Tasks.Task(() => { })); //No Task.FromResult in .NET 4.
            }
            Dispatcher.VerifyAccess();

            var tcs = new System.Threading.Tasks.TaskCompletionSource <object>();

            var sb = (Storyboard)this.Template.Resources["OverlayFastSemiFadeOut"];

            sb = sb.Clone();

            EventHandler completionHandler = null;

            completionHandler = (sender, args) =>
            {
                sb.Completed -= completionHandler;

                if (overlayStoryboard == sb)
                {
                    overlayBox.Visibility = Visibility.Hidden;
                    overlayStoryboard     = null;
                }

                tcs.TrySetResult(null);
            };

            sb.Completed += completionHandler;

            overlayBox.BeginStoryboard(sb);

            overlayStoryboard = sb;

            return(tcs.Task);
        }
コード例 #16
0
        private Task <bool> InitializeLanguageChange()
        {
            TaskCompletionSource <bool> source = new System.Threading.Tasks.TaskCompletionSource <bool>();

            GlobalStatusStore.Current.WhenAnyValue(x => x.Setting.Language)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(lan =>
            {
                source?.TrySetResult(true);
                if (lan == "en-us")
                {
                    ((App)App.Current).SetLanguage("en-us");
                }
                else
                {
                    ((App)App.Current).SetLanguage("zh-cn");
                }
            });
            return(source.Task);
        }
コード例 #17
0
 /// <summary>
 /// Get all GameState keys and values.
 /// </summary>
 /// <returns>A Task&lt;IDictionary&lt;String,GameState&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IDictionary<String, GameState>> GetAllAsync(this Buddy.GameStates gameStates)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IDictionary<String, GameState>>();
     gameStates.GetAllInternal((bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #18
0
 /// <summary>
 /// Get a Place by it's globally unique identifier. This method can also be used to calculate a distance from a lat/long to a place.
 /// </summary>
 /// <param name="placeId">The ID of the place to retreive.</param>
 /// <param name="latitude">The optional latitude to calcualte a distance to.</param>
 /// <param name="longitude">The optioanl longitude to calculate a distance to.</param>
 /// <returns>A Task&lt;Place&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Place> GetAsync(this Buddy.Places places, int placeId, double latitude = 0, double longitude = 0)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Place>();
     places.GetInternal(placeId, latitude, longitude, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #19
0
 /// <summary>
 /// Send a message to a user from the current authenticated user.
 /// </summary>
 /// <param name="toUser">The user to send a message to.</param>
 /// <param name="message">The message to send, must be less then 200 characters.</param>
 /// <param name="appTag">An optional application tag to set for the message.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> SendAsync(this Buddy.Messages messages, Buddy.User toUser, string message, string appTag = "")
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     messages.SendInternal(toUser, message, appTag, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #20
0
 /// <summary>
 /// Check if a group with this name already exists.
 /// </summary>
 /// <param name="name">The name of the group to check for.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> CheckIfExistsAsync(this Buddy.MessageGroups messageGroups, string name)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     messageGroups.CheckIfExistsInternal(name, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #21
0
 /// <summary>
 /// Create a new message group.
 /// </summary>
 /// <param name="name">The name of the new group, must be unique for the app.</param>
 /// <param name="openGroup">Optionally whether to make to group open for all user (anyone can join), or closed (only the owner can add users to it).</param>
 /// <param name="appTag">An optional application tag for this message group.</param>
 /// <returns>A Task&lt;MessageGroup&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<MessageGroup> CreateAsync(this Buddy.MessageGroups messageGroups, string name, bool openGroup, string appTag = "")
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<MessageGroup>();
     messageGroups.CreateInternal(name, openGroup, appTag, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #22
0
 /// <summary>
 /// Send a message to the entire message group.
 /// </summary>
 /// <param name="message">The message to send to this group. Must be less then 1000 characters.</param>
 /// <param name="latitude">The optional latitude from where this message was sent.</param>
 /// <param name="longitude">The optional longitude from where this message was sent.</param>
 /// <param name="appTag">An optional application tag for this message.</param>
 /// <returns>A Task&lt;IDictionary&lt;Int32,Boolean&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IDictionary<Int32, Boolean>> SendMessageAsync(this Buddy.MessageGroup messageGroup, string message, double latitude = 0, double longitude = 0, string appTag = "")
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IDictionary<Int32, Boolean>>();
     messageGroup.SendMessageInternal(message, latitude, longitude, appTag, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #23
0
 /// <summary>
 /// Remove an identity value for this user.
 /// </summary>
 /// <param name="value">The value to remove.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> RemoveAsync(this Buddy.Identity identity, string value)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     identity.RemoveInternal(value, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #24
0
 /// <summary>
 /// Get a virtual album by its globally unique identifier. All the album photos will be retreived as well. Note that this method internally does two web-service calls, and the IAsyncResult object
 /// returned is only valid for the first one.
 /// </summary>
 /// <param name="albumId">The ID of the virtual album to retrieve.</param>
 /// <returns>A Task&lt;VirtualAlbum&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<VirtualAlbum> GetAsync(this Buddy.VirtualAlbums virtualAlbums, int albumId)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<VirtualAlbum>();
     virtualAlbums.GetInternal(albumId, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #25
0
 /// <summary>
 /// Create a new virtual album. Note that this method internally does two web-service calls, and the IAsyncResult object
 /// returned is only valid for the first one.
 /// </summary>
 /// <param name="name">The name of the new virtual album.</param>
 /// <param name="appTag">An optional application tag for the album.</param>
 /// <returns>A Task&lt;VirtualAlbum&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<VirtualAlbum> CreateAsync(this Buddy.VirtualAlbums virtualAlbums, string name, string appTag = "")
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<VirtualAlbum>();
     virtualAlbums.CreateInternal(name, appTag, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #26
0
 /// <summary>
 /// Update virtual album picture comment or app.tag.
 /// </summary>
 /// <param name="picture">The picture to be updated, either PicturePublic or Picture works.</param>
 /// <param name="newComment">The new comment to set for the picture.</param>
 /// <param name="newAppTag">An optional new application tag for the picture.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> UpdatePictureAsync(this Buddy.VirtualAlbum virtualAlbum, Buddy.PicturePublic picture, string newComment, string newAppTag = "")
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     virtualAlbum.UpdatePictureInternal(picture, newComment, newAppTag, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #27
0
 /// <summary>
 /// Add a list of pictures to this virtual album.
 /// </summary>
 /// <param name="pictures">The list of pictures to add to this photo album. Either PicturePublic or Picture works.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> AddPictureBatchAsync(this Buddy.VirtualAlbum virtualAlbum, System.Collections.Generic.List<Buddy.PicturePublic> pictures)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     virtualAlbum.AddPictureBatchInternal(pictures, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #28
0
 /// <summary>
 /// Get a list of startups in the specified metro area.
 /// </summary>
 /// <param name="metroName">The name of the metro area within which to search for startups.</param>
 /// <param name="recordLimit">The number of search results to return.</param>
 /// <returns>A Task&lt;IEnumerable&lt;Startup&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IEnumerable<Startup>> GetFromMetroAreaAsync(this Buddy.Startups startups, string metroName, int recordLimit)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<Startup>>();
     startups.GetFromMetroAreaInternal(metroName, recordLimit, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #29
0
 /// <summary>
 /// Searches for statups by name within the distance of the specified location. Note: To search for all startups within the distance from the specified location, leave the SearchName parameter empty.
 /// </summary>
 /// <param name="searchDistanceInMeters">The radius of the startup search.</param>
 /// <param name="latitude">The latitude where the search should start.</param>
 /// <param name="longitude">The longitude where the search should start.</param>
 /// <param name="numberOfResults">The number of search results to return.</param>
 /// <param name="searchForName">Optional search string, for example: "Star*" to search for all startups that begin with the string "Star".</param>
 /// <returns>A Task&lt;IEnumerable&lt;Startup&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IEnumerable<Startup>> FindAsync(this Buddy.Startups startups, int searchDistanceInMeters, double latitude, double longitude, int numberOfResults=20, string searchForName = "")
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<Startup>>();
     startups.FindInternal(searchDistanceInMeters, latitude, longitude, numberOfResults, searchForName, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #30
0
        public async override System.Threading.Tasks.Task OnEntry()
        {
            // log
            UnityEngine.Debug.Log(
                "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : begin with pattern ["
                + UXF.Session.instance.CurrentTrial.settings.GetString("current_pattern")
                + "] & phase_C_linear_acceleration_target ["
                + System.String.Join(",", this.FSM.CurrentSettings.phase_C_linear_acceleration_target)
                + "]"
                );

            // get bridges
            var control_bridge
                = gameplay.ApollonGameplayManager.Instance.getBridge(
                      gameplay.ApollonGameplayManager.GameplayIDType.AgencyAndThresholdPerceptionControl
                      ) as gameplay.control.ApollonAgencyAndThresholdPerceptionControlBridge;

            var motion_system_bridge
                = gameplay.ApollonGameplayManager.Instance.getBridge(
                      gameplay.ApollonGameplayManager.GameplayIDType.MotionSystemCommand
                      ) as gameplay.device.command.ApollonMotionSystemCommandBridge;

            var virtual_motion_system_bridge
                = gameplay.ApollonGameplayManager.Instance.getBridge(
                      gameplay.ApollonGameplayManager.GameplayIDType.VirtualMotionSystemCommand
                      ) as gameplay.device.command.ApollonVirtualMotionSystemCommandBridge;

            // current scenario
            bool bHasRealMotion = false;

            switch (this.FSM.CurrentSettings.scenario_type)
            {
            default:
            case profile.ApollonAgencyAndThresholdPerceptionProfile.Settings.ScenarioIDType.VisualOnly:
            {
                bHasRealMotion = false;
                break;
            }

            case profile.ApollonAgencyAndThresholdPerceptionProfile.Settings.ScenarioIDType.VestibularOnly:
            case profile.ApollonAgencyAndThresholdPerceptionProfile.Settings.ScenarioIDType.VisuoVestibular:
            {
                bHasRealMotion = true;
                break;
            }
            } /* switch() */

            // check
            if (control_bridge == null || motion_system_bridge == null || virtual_motion_system_bridge == null)
            {
                // log
                UnityEngine.Debug.LogError(
                    "<color=Red>Error: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : Could not find corresponding gameplay bridge !"
                    );

                // fail
                return;
            } /* if() */

            // filtering
            foreach (var(saturation_item, index) in this.FSM.CurrentSettings.phase_C_angular_velocity_saturation_threshold.Select((e, idx) => (e, idx)))
            {
                if (saturation_item == 0.0f)
                {
                    this.FSM.CurrentSettings.phase_C_angular_velocity_saturation_threshold[index]
                        = (
                              this.FSM.CurrentSettings.phase_C_angular_acceleration_target[index]
                              * (this.FSM.CurrentSettings.phase_C_stim_duration / 1000.0f)
                              );
                }
            }
            foreach (var(saturation_item, index) in this.FSM.CurrentSettings.phase_C_linear_velocity_saturation_threshold.Select((e, idx) => (e, idx)))
            {
                if (saturation_item == 0.0f)
                {
                    this.FSM.CurrentSettings.phase_C_linear_velocity_saturation_threshold[index]
                        = (
                              this.FSM.CurrentSettings.phase_C_linear_acceleration_target[index]
                              * (this.FSM.CurrentSettings.phase_C_stim_duration / 1000.0f)
                              );
                }
            }

            // synchronisation mechanism (TCS + local function)
            var sync_detection_point = new System.Threading.Tasks.TaskCompletionSource <(bool, float, string)>();
            var sync_idle_point      = new System.Threading.Tasks.TaskCompletionSource <bool>();

            if (!bHasRealMotion)
            {
                void sync_user_response_local_function(object sender, gameplay.control.ApollonAgencyAndThresholdPerceptionControlDispatcher.EventArgs e)
                => sync_detection_point?.TrySetResult((true, UnityEngine.Time.time, System.DateTime.Now.ToString("HH:mm:ss.ffffff")));
                void sync_end_stim_local_function(object sender, gameplay.device.command.ApollonVirtualMotionSystemCommandDispatcher.EventArgs e)
                => sync_idle_point?.TrySetResult(true);

                // register our synchronisation function
                control_bridge.Dispatcher.UserResponseTriggeredEvent += sync_user_response_local_function;
                virtual_motion_system_bridge.Dispatcher.IdleEvent    += sync_end_stim_local_function;

                UnityEngine.Debug.Log(
                    "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : begin stim"
                    );

                // log stim begin timestamp
                this.FSM.CurrentResults.user_stim_unity_timestamp = UnityEngine.Time.time;
                this.FSM.CurrentResults.user_stim_host_timestamp  = System.DateTime.Now.ToString("HH:mm:ss.ffffff");

                // log
                UnityEngine.Debug.Log(
                    "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : beginning "
                    + (this.FSM.CurrentSettings.bIsTryCatch ? "fake" : "real")
                    + " stim, result [user_stim_unity_timestamp:"
                    + this.FSM.CurrentResults.user_stim_unity_timestamp
                    + ",user_stim_host_timestamp:"
                    + this.FSM.CurrentResults.user_stim_host_timestamp
                    + "]"
                    );

                // check if it's a try/catch condition & begin stim
                if (this.FSM.CurrentSettings.bIsTryCatch)
                {
                    virtual_motion_system_bridge.Dispatcher.RaiseAccelerate(
                        this.FSM.CurrentSettings.phase_C_angular_acceleration_target.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_angular_velocity_saturation_threshold.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_angular_displacement_limiter.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_acceleration_target.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_velocity_saturation_threshold.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_displacement_limiter.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_stim_duration,
                        (
                            this.FSM.CurrentSettings.scenario_type == profile.ApollonAgencyAndThresholdPerceptionProfile.Settings.ScenarioIDType.VisualOnly
                            ? true
                            : false
                        )
                        );
                }
                else
                {
                    virtual_motion_system_bridge.Dispatcher.RaiseAccelerate(
                        this.FSM.CurrentSettings.phase_C_angular_acceleration_target.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_angular_velocity_saturation_threshold.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_angular_displacement_limiter.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_acceleration_target.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_velocity_saturation_threshold.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_displacement_limiter.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_stim_duration,
                        (
                            this.FSM.CurrentSettings.scenario_type == profile.ApollonAgencyAndThresholdPerceptionProfile.Settings.ScenarioIDType.VisualOnly
                            ? true
                            : false
                        )
                        );
                } /* if() */

                // log
                UnityEngine.Debug.Log(
                    "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : begin "
                    + (this.FSM.CurrentSettings.bIsTryCatch ? "fake" : "real")
                    + " stim, result [user_stim_unity_timestamp:"
                    + this.FSM.CurrentResults.user_stim_unity_timestamp
                    + ",user_stim_host_timestamp:"
                    + this.FSM.CurrentResults.user_stim_host_timestamp
                    + "]"
                    );

                var phase_running_task
                // wait for idle state
                    = System.Threading.Tasks.Task.Factory.StartNew(
                          async() =>
                {
                    UnityEngine.Debug.Log(
                        "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : waiting for idle state"
                        );
                    await sync_idle_point.Task;
                }
                          // then sleep remaining idle time & raise end
                          ).Unwrap().ContinueWith(
                          async antecedant =>
                {
                    UnityEngine.Debug.Log(
                        "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : waiting ["
                        + (this.FSM.CurrentSettings.phase_C_total_duration - (2.0f * this.FSM.CurrentSettings.phase_C_stim_duration))
                        + " ms] for remaining phase total time"
                        );
                    await this.FSM.DoSleep(this.FSM.CurrentSettings.phase_C_total_duration - (2.0f * this.FSM.CurrentSettings.phase_C_stim_duration));
                }
                          ).Unwrap().ContinueWith(
                          antecedent =>
                {
                    if (!sync_detection_point.Task.IsCompleted)
                    {
                        UnityEngine.Debug.Log(
                            "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : user hasn't responded, injecting default result"
                            );

                        sync_detection_point?.TrySetResult((false, -1.0f, "-1.0"));
                    }
                    else
                    {
                        UnityEngine.Debug.Log(
                            "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : user has responded, keep result"
                            );
                    }         /* if() */
                }
                          );

                // wait for detection synchronisation point indefinitely & reset it once hit
                (
                    this.FSM.CurrentResults.user_response_C,
                    this.FSM.CurrentResults.user_perception_C_unity_timestamp,
                    this.FSM.CurrentResults.user_perception_C_host_timestamp
                ) = await sync_detection_point.Task;

                // unregister our control synchronisation function
                control_bridge.Dispatcher.UserResponseTriggeredEvent -= sync_user_response_local_function;

                // log
                UnityEngine.Debug.Log(
                    "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : waiting for phase end"
                    );

                // wait for phase task completion
                await phase_running_task;

                // unregister our motion synchronisation function
                virtual_motion_system_bridge.Dispatcher.IdleEvent -= sync_end_stim_local_function;

                // log
                UnityEngine.Debug.Log(
                    "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : end phase, result [user_response_C:"
                    + this.FSM.CurrentResults.user_response_C
                    + ",user_perception_C_unity_timestamp:"
                    + this.FSM.CurrentResults.user_perception_C_unity_timestamp
                    + ",user_perception_C_host_timestamp:"
                    + this.FSM.CurrentResults.user_perception_C_host_timestamp
                    + "]"
                    );
            }
            else
            {
                void sync_user_response_local_function(object sender, gameplay.control.ApollonAgencyAndThresholdPerceptionControlDispatcher.EventArgs e)
                => sync_detection_point?.TrySetResult((true, UnityEngine.Time.time, System.DateTime.Now.ToString("HH:mm:ss.ffffff")));
                void sync_end_stim_local_function(object sender, gameplay.device.command.ApollonMotionSystemCommandDispatcher.EventArgs e)
                => sync_idle_point?.TrySetResult(true);

                // register our synchronisation function
                control_bridge.Dispatcher.UserResponseTriggeredEvent += sync_user_response_local_function;
                motion_system_bridge.Dispatcher.IdleEvent            += sync_end_stim_local_function;

                UnityEngine.Debug.Log(
                    "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : begin stim"
                    );

                // log stim begin timestamp
                this.FSM.CurrentResults.user_stim_unity_timestamp = UnityEngine.Time.time;
                this.FSM.CurrentResults.user_stim_host_timestamp  = System.DateTime.Now.ToString("HH:mm:ss.ffffff");

                // log
                UnityEngine.Debug.Log(
                    "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : beginning "
                    + (this.FSM.CurrentSettings.bIsTryCatch ? "fake" : "real")
                    + " stim, result [user_stim_unity_timestamp:"
                    + this.FSM.CurrentResults.user_stim_unity_timestamp
                    + ",user_stim_host_timestamp:"
                    + this.FSM.CurrentResults.user_stim_host_timestamp
                    + "]"
                    );

                // check if it's a try/catch condition & begin stim
                if (this.FSM.CurrentSettings.bIsTryCatch)
                {
                    motion_system_bridge.Dispatcher.RaiseAccelerate(
                        this.FSM.CurrentSettings.phase_C_angular_acceleration_target.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_angular_velocity_saturation_threshold.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_angular_displacement_limiter.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_acceleration_target.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_velocity_saturation_threshold.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_displacement_limiter.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                x.IsMandatory ? x.Value : 0.0f
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_stim_duration,
                        (
                            this.FSM.CurrentSettings.scenario_type == profile.ApollonAgencyAndThresholdPerceptionProfile.Settings.ScenarioIDType.VisualOnly
                            ? true
                            : false
                        )
                        );
                }
                else
                {
                    motion_system_bridge.Dispatcher.RaiseAccelerate(
                        this.FSM.CurrentSettings.phase_C_angular_acceleration_target.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_angular_velocity_saturation_threshold.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_angular_displacement_limiter.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_angular_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_acceleration_target.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_velocity_saturation_threshold.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_linear_displacement_limiter.Select(
                            (e, idx)
                            => new {
                        Value       = e,
                        IsMandatory = this.FSM.CurrentSettings.phase_C_linear_mandatory_axis[idx]
                    }
                            ).Select(
                            x => (
                                (x.IsMandatory || (this.FSM.CurrentResults.user_command == 0.0f))
                                    ? x.Value
                                    : (x.Value * UnityEngine.Mathf.Abs(this.FSM.CurrentResults.user_command))
                                )
                            ).ToArray(),
                        this.FSM.CurrentSettings.phase_C_stim_duration,
                        (
                            this.FSM.CurrentSettings.scenario_type == profile.ApollonAgencyAndThresholdPerceptionProfile.Settings.ScenarioIDType.VisualOnly
                            ? true
                            : false
                        )
                        );
                } /* if() */

                var phase_running_task
                // wait for idle state
                    = System.Threading.Tasks.Task.Factory.StartNew(
                          async() =>
                {
                    UnityEngine.Debug.Log(
                        "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : waiting for idle state"
                        );
                    await sync_idle_point.Task;
                }
                          // then sleep remaining idle time & raise end
                          ).Unwrap().ContinueWith(
                          async antecedant =>
                {
                    UnityEngine.Debug.Log(
                        "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : waiting ["
                        + (this.FSM.CurrentSettings.phase_C_total_duration - (2.0f * this.FSM.CurrentSettings.phase_C_stim_duration))
                        + " ms] for remaining phase total time"
                        );
                    await this.FSM.DoSleep(this.FSM.CurrentSettings.phase_C_total_duration - (2.0f * this.FSM.CurrentSettings.phase_C_stim_duration));
                }
                          ).Unwrap().ContinueWith(
                          antecedent =>
                {
                    if (!sync_detection_point.Task.IsCompleted)
                    {
                        UnityEngine.Debug.Log(
                            "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : user hasn't responded, injecting default result"
                            );

                        sync_detection_point?.TrySetResult((false, -1.0f, "-1.0"));
                    }
                    else
                    {
                        UnityEngine.Debug.Log(
                            "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : user has responded, keep result"
                            );
                    }         /* if() */
                }
                          );

                // wait for detection synchronisation point indefinitely & reset it once hit
                (
                    this.FSM.CurrentResults.user_response_C,
                    this.FSM.CurrentResults.user_perception_C_unity_timestamp,
                    this.FSM.CurrentResults.user_perception_C_host_timestamp
                ) = await sync_detection_point.Task;

                // unregister our control synchronisation function
                control_bridge.Dispatcher.UserResponseTriggeredEvent -= sync_user_response_local_function;

                // log
                UnityEngine.Debug.Log(
                    "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : waiting for phase end"
                    );

                // wait for phase task completion
                await phase_running_task;

                // unregister our motion synchronisation function
                motion_system_bridge.Dispatcher.IdleEvent -= sync_end_stim_local_function;

                // log
                UnityEngine.Debug.Log(
                    "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : end phase, result [user_response_C:"
                    + this.FSM.CurrentResults.user_response_C
                    + ",user_perception_C_unity_timestamp:"
                    + this.FSM.CurrentResults.user_perception_C_unity_timestamp
                    + ",user_perception_C_host_timestamp:"
                    + this.FSM.CurrentResults.user_perception_C_host_timestamp
                    + "]"
                    );
            } /* if() */

            // log
            UnityEngine.Debug.Log(
                "<color=Blue>Info: </color> ApollonAgencyAndThresholdPerceptionPhaseC.OnEntry() : end"
                );
        } /* OnEntry() */
コード例 #31
0
 /// <summary>
 /// Returns all the identity values for this user.
 /// </summary>
 /// <returns>A Task&lt;IEnumerable&lt;IdentityItem&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IEnumerable<IdentityItem>> GetAllAsync(this Buddy.Identity identity)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<IdentityItem>>();
     identity.GetAllInternal((bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #32
0
 /// <summary>
 /// Accept a friend request from a user.
 /// </summary>
 /// <param name="user">The user to accept as friend. Can't be null and must be on the friend requests list.</param>
 /// <param name="appTag">Tag this friend accept with a string.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> AcceptAsync(this Buddy.FriendRequests friendRequests, Buddy.User user, string appTag = "")
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     friendRequests.AcceptInternal(user, appTag, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #33
0
 /// <summary>
 /// Check for the existance of an identity value in the system. The search is perform for the entire app.
 /// </summary>
 /// <param name="values">The value to search for. This can either be a single value or a semi-colon separated list of values.</param>
 /// <returns>A Task&lt;IEnumerable&lt;IdentityItemSearchResult&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IEnumerable<IdentityItemSearchResult>> CheckForValuesAsync(this Buddy.Identity identity, string values)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<IdentityItemSearchResult>>();
     identity.CheckForValuesInternal(values, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #34
0
 /// <summary>
 /// Updates the value of this metadata item.
 /// </summary>
 /// <param name="value">The new value for this item, can't be null.</param>
 /// <param name="latitude">The optional latitude for this item.</param>
 /// <param name="longitude">The optional longitude for this item.</param>
 /// <param name="appTag">The optional application tag for this item.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> SetAsync(this Buddy.MetadataItem metadataItem, string value, double latitude = 0, double longitude = 0, string appTag = "")
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     metadataItem.SetInternal(value, latitude, longitude, appTag, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #35
0
 /// <summary>
 /// Delete this message group.
 /// </summary>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> DeleteAsync(this Buddy.MessageGroup messageGroup)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     messageGroup.DeleteInternal((bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #36
0
 /// <summary>
 /// Add a new score for this user.
 /// </summary>
 /// <param name="score">The numeric value of the score.</param>
 /// <param name="board">The optional name of the game board.</param>
 /// <param name="rank">The optional rank for this score. This can be used for adding badges, achievements, etc.</param>
 /// <param name="latitude">The optional latitude for this score.</param>
 /// <param name="longitude">The optional longitude for this score.</param>
 /// <param name="oneScorePerPlayer">The optional one-score-per-player paramter. Setting this to true will always update the score for this user, instead of creating a new one.</param>
 /// <param name="appTag">An optional application tag for this score.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> AddAsync(this Buddy.GameScores gameScores, double score, string board = null, string rank = null, double latitude = 0, double longitude = 0, bool oneScorePerPlayer = false, string appTag = null)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     gameScores.AddInternal(score, board, rank, latitude, longitude, oneScorePerPlayer, appTag, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #37
0
 /// <summary>
 /// Saves a receipt for the purchase of an item made to the application's store.
 /// </summary>
 /// <param name="totalCost">The total cost for the items purchased in the transaction.</param>
 /// <param name="totalQuantity">The total number of items purchased.</param>
 /// <param name="storeItemID">The store ID of the item of the item being purchased.</param>
 /// <param name="storeName">The name of the application's store to be saved with the transaction. This field is used by the commerce analytics to track purchases.</param>
 /// <param name="receiptData">Optional information to store with the receipt such as notes about the transaction.</param>
 /// <param name="customTransactionID">An optional app-specific ID to associate with the purchase.</param>
 /// <param name="appData">Optional metadata to associate with the transaction.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> SaveReceiptAsync(this Buddy.Commerce commerce, string totalCost, int totalQuantity, int storeItemID, string storeName, string receiptData = "", string customTransactionID = "", string appData = "")
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     commerce.SaveReceiptInternal(totalCost, totalQuantity, storeItemID, storeName, receiptData, customTransactionID, appData, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #38
0
 /// <summary>
 /// Return all score entries for this user.
 /// </summary>
 /// <param name="recordLimit">Limit the number of entries returned.</param>
 /// <returns>A Task&lt;IEnumerable&lt;GameScore&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IEnumerable<GameScore>> GetAllAsync(this Buddy.GameScores gameScores, int recordLimit = 100)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<GameScore>>();
     gameScores.GetAllInternal(recordLimit, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #39
0
 /// <summary>
 /// Get all message groups that this user is part of.
 /// </summary>
 /// <returns>A Task&lt;IEnumerable&lt;MessageGroup&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IEnumerable<MessageGroup>> GetMyAsync(this Buddy.MessageGroups messageGroups)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<MessageGroup>>();
     messageGroups.GetMyInternal((bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #40
0
 /// <summary>
 /// Remove a GameState key.
 /// </summary>
 /// <param name="gameStateKey">The key to remove from the GameState.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> RemoveAsync(this Buddy.GameStates gameStates, string gameStateKey)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     gameStates.RemoveInternal(gameStateKey, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #41
0
 /// <summary>
 /// Get all sent message by the current user.
 /// </summary>
 /// <param name="afterDate">Optionally retreive only messages after a certain DateTime.</param>
 /// <returns>A Task&lt;IEnumerable&lt;Message&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IEnumerable<Message>> GetSentAsync(this Buddy.Messages messages, System.DateTime afterDate = default(DateTime))
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<Message>>();
     messages.GetSentInternal(afterDate, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #42
0
 /// <summary>
 /// Get all geo-location categories in Buddy.
 /// </summary>
 /// <returns>A Task&lt;IDictionary&lt;Int32,String&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IDictionary<Int32, String>> GetCategoriesAsync(this Buddy.Places places)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IDictionary<Int32, String>>();
     places.GetCategoriesInternal((bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #43
0
 /// <summary>
 /// Returns information about all items in the store for the current application which are marked as free.
 /// </summary>
 /// <returns>A Task&lt;IEnumerable&lt;StoreItem&gt; &gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<IEnumerable<StoreItem>> GetFreeStoreItemsAsync(this Buddy.Commerce commerce)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<IEnumerable<StoreItem>>();
     commerce.GetFreeStoreItemsInternal((bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }
コード例 #44
0
 /// <summary>
 /// Remove a user from the current list of friends.
 /// </summary>
 /// <param name="user">The user to remove from the friends list. Must be already on the list and can't be null.</param>
 /// <returns>A Task&lt;Boolean&gt;that can be used to monitor progress on this call.</returns>
 public static System.Threading.Tasks.Task<Boolean> RemoveAsync(this Buddy.Friends friends, Buddy.User user)
 {
     var tcs = new System.Threading.Tasks.TaskCompletionSource<Boolean>();
     friends.RemoveInternal(user, (bcr) =>
     {
         if (bcr.Error != BuddyServiceClient.BuddyError.None)
         {
             tcs.TrySetException(new BuddyServiceException(bcr.Error));
         }
         else
         {
             tcs.TrySetResult(bcr.Result);
         }
     });
     return tcs.Task;
 }