Exemple #1
0
        public D2GS(String character, String account, UInt32 chickenLife, UInt32 potLife)
        {
            //ConnectedToGs = false;
            m_d2gsConnection = new D2gsConnection();
            m_d2gsReader = new D2gsReader(ref m_d2gsConnection, character);
            m_d2gsHandler = new D2gsHandler(ref m_d2gsConnection);
            m_gsPing = new GameServerPing(ref m_d2gsConnection);
            m_gameThread = new GameThread(m_d2gsConnection, chickenLife, potLife);
            m_asciiMap = new AsciiMap(m_gameThread.GameData, m_d2gsConnection);

            m_d2gsConnection.StartThread += delegate {
                m_d2gsHandlerThread = new Thread(m_d2gsHandler.ThreadFunction);
                m_d2gsHandlerThread.Name = account + " [D2Gs]:";
                m_d2gsReaderThread = new Thread(m_d2gsReader.ThreadFunction);
                m_d2gsReaderThread.Name = account + " [D2GS]:";

                m_d2gsHandlerThread.Start();
                m_d2gsReaderThread.Start();
            };

            m_d2gsHandler.StartPinging += delegate
            {
                m_gsPingThread = new Thread(m_gsPing.Run);
                m_gsPingThread.Name = account + " [D2GS]:";
                m_gsPingThread.Start();
                m_mapThread = new Thread(m_asciiMap.ThreadFunction);
                m_mapThread.Start();
            };

            m_botThread = new Thread(m_gameThread.BotThread);
            m_botThread.Name = account + " [BOT]:";
            m_botThread.Start();

            SubscribeGameServerEvents();
        }
        public void DoUpdate(string versionName, string url)
        {
            var str = GlobalSettings.Default.ClientVersion;

            var    split     = str.LastIndexOf('-');
            int    verNum    = 0;
            string curBranch = str;

            if (split != -1)
            {
                int.TryParse(str.Substring(split + 1), out verNum);
                curBranch = str.Substring(0, split);
            }

            _UpdaterAlert = UIScreen.GlobalShowAlert(new UIAlertOptions()
            {
                Title   = "",
                Message = GameFacade.Strings.GetString("f101", "27"),
                Buttons = new UIAlertButton[0]
            }, true);

            Api.GetUpdateList((updates) =>
            {
                UIScreen.RemoveDialog(_UpdaterAlert);
                GameThread.InUpdate(() =>
                {
                    UpdatePath path = null;
                    if (updates != null)
                    {
                        path = UpdatePath.FindPath(updates.ToList(), str, versionName);
                    }
                    if (path == null)
                    {
                        path = new UpdatePath(new List <ApiUpdate>()
                        {
                            new ApiUpdate()
                            {
                                version_name = versionName, full_zip = url
                            }
                        }, true);
                        path.MissingInfo = true;
                    }
                    ShowUpdateDialog(path);
                });
            });
        }
Exemple #3
0
        public void GetFSOV(uint shardID, uint lotLocation, Action <byte[]> callback)
        {
            var client  = Client();
            var request = new RestRequest("userapi/city/" + shardID + "/" + lotLocation + ".fsov", Method.GET);

            request.AddHeader("authorization", "bearer " + AuthKey);

            client.ExecuteAsync(request, (resp, h) =>
            {
                var ok     = resp.StatusCode == System.Net.HttpStatusCode.OK;
                byte[] dat = resp.RawBytes;
                GameThread.NextUpdate(x =>
                {
                    callback(ok?dat:null);
                });
            });
        }
Exemple #4
0
        public static void WorkerLoop()
        {
            int loggedIn      = 0;
            int loginAttempts = 0;

            while (true)
            {
                if (!LoginSent)
                {
                    LoginSent = true;
                    Console.WriteLine("Attempting Login... (" + (loginAttempts++) + ")");
                    Login();
                }
                GameThread.OnWork.WaitOne(1000);
                GameThread.DigestUpdate(null);
            }
        }
Exemple #5
0
        public TSOVersionPatchScreen() : base()
        {
            Background = new UISetupBackground();
            Add(Background);

            Version   = Content.Content.Get().VersionString;
            CanUpdate = Version == Patchable;

            GameThread.NextUpdate((state) =>
            {
                UIAlert.Alert(GameFacade.Strings.GetString("f101", "14"),
                              GameFacade.Strings.GetString("f101", "15", new string[] {
                    Version, GameFacade.Strings.GetString("f101", CanUpdate ? "16" : "17")
                }),
                              true);
            });
        }
Exemple #6
0
 public void MessageReceived(AriesClient client, object message)
 {
     if (message is RequestClientSession ||
         message is HostOnlinePDU)
     {
         this.AsyncProcessMessage(message);
     }
     else if (message is AnnouncementMsgPDU)
     {
         GameThread.InUpdate(() => {
             UIScreen.GlobalShowAnnouncement((AnnouncementMsgPDU)message);
         });
     }
     else if (message is ChangeRoommateResponse)
     {
     }
 }
Exemple #7
0
        public void UploadFSOF(uint shardID, uint lotLocation, byte[] data, Action <bool> callback)
        {
            var client  = Client();
            var request = new RestRequest("userapi/city/" + shardID + "/uploadfacade/" + lotLocation, Method.POST);

            request.AddFile("application/octet-stream", data, lotLocation + ".fsof");
            request.AddHeader("authorization", "bearer " + AuthKey);

            client.ExecuteAsync(request, (resp, h) =>
            {
                var ok = resp.StatusCode == System.Net.HttpStatusCode.OK;
                GameThread.NextUpdate(x =>
                {
                    callback(ok);
                });
            });
        }
        /// <summary>
        /// Setup anything that needs a GraphicsDevice
        /// </summary>
        /// <param name="layer"></param>
        public void Initialize(GraphicsDevice device)
        {
            /**
             * Setup world state, this object acts as a facade
             * to world objects as well as providing various
             * state settings for the world and helper functions
             */
            State = new WorldState(device, device.Viewport.Width, device.Viewport.Height, this);
            GameThread.InUpdate(() =>
            {
                State.AmbientLight = new Texture2D(device, 256, 256);
                State.OutsidePx    = new Texture2D(device, 1, 1);
            });

            HasInitGPU = true;
            HasInit    = HasInitGPU & HasInitBlueprint;
        }
Exemple #9
0
        public ClientDataService(IModelSerializer serializer,
                                 FSO.Content.Content content,
                                 IKernel kernel) : base(serializer, content)
        {
            AddProvider(kernel.Get <ClientAvatarProvider>());
            AddProvider(kernel.Get <ClientLotProvider>());
            AddProvider(kernel.Get <ClientCityProvider>());
            AddProvider(kernel.Get <ClientNeighProvider>());
            AddProvider(kernel.Get <ClientMayorRatingProvider>());
            CityClient = kernel.Get <AriesClient>("City");
            CityClient.AddSubscriber(this);

            //When a new object is made, this data will be requested automatically
            SetDefaultDataStruct(typeof(Avatar), MaskedStruct.SimPage_Main);

            PollInterval = GameThread.SetInterval(PollTopics, 5000);
        }
        private void PurchaseRegulator_OnError(object data)
        {
            GameThread.NextUpdate(x =>
            {
                ShowCreationProgressBar(false);
                //TODO: Find error messages in lang table
                var reason = (PurchaseLotFailureReason)data;

                string error = "An error occurred.";
                switch (reason)
                {
                case PurchaseLotFailureReason.INSUFFICIENT_FUNDS:
                    error = GameFacade.Strings.GetString("215", "26");
                    break;

                case PurchaseLotFailureReason.NOT_OFFLINE_FOR_MOVE:
                    error = GameFacade.Strings.GetString("211", "53");
                    break;

                case PurchaseLotFailureReason.IN_LOT_CANT_EVICT:
                    error = GameFacade.Strings.GetString("211", "64");
                    break;

                case PurchaseLotFailureReason.LOT_TAKEN:
                case PurchaseLotFailureReason.LOT_NOT_PURCHASABLE:
                    error = GameFacade.Strings.GetString("211", "46");
                    break;

                case PurchaseLotFailureReason.NAME_TAKEN:
                    error = GameFacade.Strings.GetString("247", "15");
                    break;

                default:
                    error = GameFacade.Strings.GetString("211", "55") + " (" + reason.ToString() + ")";
                    break;
                }
                UIScreen.GlobalShowAlert(new UIAlertOptions
                {
                    Message = error,
                    //TODO: Find something in string tables?
                    Title = "",
                    Width = 300
                }, true);
            });
        }
 public void WriteEmail(uint avatarId, string subject)
 {
     DataService.Get <Avatar>(avatarId).ContinueWith(x =>
     {
         GameThread.InUpdate(() =>
         {
             var msg = Chat.WriteLetter(UserReference.Wrap(x.Result));
             Chat.SetEmailMessage(msg, new MessageItem()
             {
                 Subject = subject, Body = ""
             });
             if (msg != null)
             {
                 Chat.ShowWindow(msg);
             }
         });
     });
 }
        private void RefreshCity(BindingChange[] changes)
        {
            if (CurrentCity.Value != null)
            {
                var mapData   = LotTileEntry.GenFromCity(CurrentCity.Value);
                var neighJSON = CurrentCity.Value.City_NeighJSON;

                //We know if lots are online, we can update the data service
                DataService.GetMany <Lot>(mapData.Select(x => (object)(uint)x.packed_pos).ToArray()).ContinueWith(x =>
                {
                    if (!x.IsCompleted)
                    {
                        return;
                    }

                    foreach (var lot in x.Result)
                    {
                        var mapItem = mapData.FirstOrDefault(y => y.packed_pos == lot.Id);
                        if (mapItem != null)
                        {
                            lot.Lot_IsOnline = (mapItem.flags & LotTileFlags.Online) == LotTileFlags.Online;
                        }
                    }
                });

                GameThread.NextUpdate((state) => {
                    View.populateCityLookup(mapData);
                    if (neighJSON != LastLotJSON)
                    {
                        try
                        {
                            var neigh = JsonConvert.DeserializeObject <List <Rendering.City.Model.CityNeighbourhood> >(neighJSON);
                            Rendering.City.Model.CityNeighbourhood.Init(neigh);
                            View.NeighGeom.Data = neigh;
                            View.NeighGeom.Generate(GameFacade.GraphicsDevice);
                        } catch
                        {
                        }

                        LastLotJSON = neighJSON;
                    }
                });
            }
        }
Exemple #13
0
        protected override void OnAfterTransition(RegulatorState oldState, RegulatorState newState, object data)
        {
            switch (newState.Name)
            {
            case "StartPurchase":
                if (!Network.CityClient.IsConnected)
                {
                    ThrowErrorAndReset("City server disconnected");
                    return;
                }
                CurrentRequest = data as PurchaseLotRequest;
                AsyncTransition("SendPurchaseRequest");
                break;

            case "SendPurchaseRequest":
                Network.CityClient.Write(new FSO.Server.Protocol.Electron.Packets.PurchaseLotRequest
                {
                    LotLocation_X = CurrentRequest.X,
                    LotLocation_Y = CurrentRequest.Y,
                    Name          = CurrentRequest.Name,
                    StartFresh    = CurrentRequest.StartFresh,
                    MayorMode     = CurrentRequest.Mayor
                });
                break;

            case "ReceivedPurchaseResponse":
                var response = data as FSO.Server.Protocol.Electron.Packets.PurchaseLotResponse;
                if (response.Status == Server.Protocol.Electron.Packets.PurchaseLotStatus.FAILED)
                {
                    //Error
                    ThrowErrorAndReset(response.Reason);
                }
                else
                {
                    AsyncTransition("PurchaseComplete");
                    GameThread.NextUpdate(x => { OnPurchased(response.NewFunds); });
                }
                break;

            case "PurchaseComplete":
                AsyncTransition("Idle");
                break;
            }
        }
        private void DPISlider_OnChange(UIElement element)
        {
            GameThread.NextUpdate((cb) =>
            {
                FSOEnvironment.DPIScaleFactor         = DPISlider.Value / 4f;
                GlobalSettings.Default.DPIScaleFactor = FSOEnvironment.DPIScaleFactor;

                var width  = Math.Max(1, GameFacade.Game.Window.ClientBounds.Width);
                var height = Math.Max(1, GameFacade.Game.Window.ClientBounds.Height);

                UIScreen.Current.ScaleX = UIScreen.Current.ScaleY = FSOEnvironment.DPIScaleFactor;

                GlobalSettings.Default.GraphicsWidth  = (int)(width / FSOEnvironment.DPIScaleFactor);
                GlobalSettings.Default.GraphicsHeight = (int)(height / FSOEnvironment.DPIScaleFactor);

                UIScreen.Current.GameResized();
                GlobalSettings.Default.Save();
            });
        }
Exemple #15
0
        /// <summary>
        /// Certain actions are invoked on the audio thread.
        /// Here we simulate this process on a correctly named thread to avoid endless blocking.
        /// </summary>
        /// <param name="action">The action to perform.</param>
        private void runOnAudioThread(Action action)
        {
            var resetEvent = new ManualResetEvent(false);

            new Thread(() =>
            {
                action();

                resetEvent.Set();
            })
            {
                Name = GameThread.PrefixedThreadNameFor("Audio")
            }.Start();

            if (!resetEvent.WaitOne(TimeSpan.FromSeconds(10)))
            {
                throw new TimeoutException();
            }
        }
        public static void EnterGameMode(string lotName, bool external)
        {
            GameThread.NextUpdate((x) =>
            {
                var screen = new TS1GameScreen();
                var last   = GameFacade.Screens.CurrentUIScreen;
                GameFacade.Screens.RemoveCurrent();
                GameFacade.Screens.AddScreen(screen);

                ((LoadingScreen)last).Close();
                var children = new List <UIElement>(last.GetChildren());
                for (int i = 0; i < children.Count; i++)
                {
                    last.Remove(children[i]);
                    screen.Add(children[i]);
                }
                screen.Initialize(lotName, external);
            });
        }
Exemple #17
0
        public CameraManager(GameThread updateThread)
        {
            thread = updateThread;

            scheduler.Add(() =>
            {
                new Thread(() =>
                {
                    while (!cancelSource.Token.IsCancellationRequested)
                    {
                        syncCameraDevices();
                        Thread.Sleep(1000);
                    }
                })
                {
                    IsBackground = true
                }.Start();
            });
        }
Exemple #18
0
 public Texture2D Get(GraphicsDevice device)
 {
     lock (this)
     {
         if (_Instance == null || _Instance.IsDisposed) //|| ((CachableTexture2D)result).BeingDisposed)
         {
             using (var stream = GetStream())
             {
                 if (Thread.CurrentThread == FSOEnvironment.GameThread)
                 {
                     _Instance = Process(device, stream);
                 }
                 else
                 {
                     //We need to get into the game thread to do this work
                     _Instance = GameThread.NextUpdate <Texture2D>(x =>
                     {
                         return(Process(device, stream));
                     }).Result;
                 }
             }
             if (!FSOEnvironment.DirectX)
             {
                 GC.SuppressFinalize(_Instance);                          //do not run the default finalizer on the texture.
             }
             if (ReplacePath != null)
             {
                 using (var str = File.Open(ReplacePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                 {
                     var hidef = ImageLoader.FromStream(device, str);
                     hidef.Tag     = new { obj = this, _Instance };
                     _Instance.Tag = hidef;
                 }
             }
             else
             {
                 _Instance.Tag = this; //form a destiny bond with the texture
             }
         }
         return(_Instance);
     }
 }
Exemple #19
0
        public void Initialize(string cityName, int cityMap, TerrainController terrainController)
        {
            Title.SetTitle(cityName);
            GameFacade.CurrentCityName = cityName;
            InitializeMap(cityMap);
            InitializeMouse();
            ZoomLevel = 5; //screen always starts at far zoom, city visible.
            CityRenderer.m_ZoomProgress = 0;

            JoinLotProgress = new UIJoinLotProgress();
            ControllerUtils.BindController <JoinLotProgressController>(JoinLotProgress);

            terrainController.Init(CityRenderer);
            CityRenderer.SetController(terrainController);

            GameThread.NextUpdate(x =>
            {
                FSOFacade.Hints.TriggerHint("screen:city");
            });
        }
Exemple #20
0
        public void GetFacadeAsync(uint shardID, uint location, Action <byte[]> callback)
        {
            //var client = Client();
            var request = new RestRequest("userapi/city/" + shardID + "/" + location + ".fsof");

            client.ExecuteAsync(request, (resp, h) =>
            {
                GameThread.NextUpdate(x =>
                {
                    if (resp.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        callback(null);
                    }
                    else
                    {
                        callback(resp.RawBytes);
                    }
                });
            });
        }
Exemple #21
0
 public void AsyncAPILotThumbnail(uint shardId, uint lotId, Action <Texture2D> callback)
 {
     Api.GetThumbnailAsync(shardId, lotId, (data) =>
     {
         if (data != null)
         {
             GameThread.NextUpdate(x =>
             {
                 if (UIScreen.Current != this)
                 {
                     return;
                 }
                 using (var mem = new MemoryStream(data))
                 {
                     callback(ImageLoader.FromStream(GameFacade.GraphicsDevice, mem));
                 }
             });
         }
     });
 }
Exemple #22
0
        public void DisplayChange(int change)
        {
            var newLabel = new UILabel();

            newLabel.Y                  = -20f;
            newLabel.CaptionStyle       = MoneyLabel.CaptionStyle.Clone();
            newLabel.CaptionStyle.Size  = 15;
            newLabel.CaptionStyle.Color = (change > 0) ? UIStyle.Current.PosMoney : UIStyle.Current.NegMoney;
            newLabel.Alignment          = FSO.Client.UI.Framework.TextAlignment.Right | FSO.Client.UI.Framework.TextAlignment.Middle;
            newLabel.Size               = new Microsoft.Xna.Framework.Vector2(128, 24);

            newLabel.Caption = ((change > 0) ? "+" : "-") + "§" + Math.Abs(change);
            Add(newLabel);

            GameFacade.Screens.Tween.To(newLabel, 1.5f, new Dictionary <string, float>()
            {
                { "Y", -50 }, { "Opacity", 0 }
            });
            GameThread.SetTimeout(() => { Remove(newLabel); }, 1500);
        }
        public override bool Execute(VM vm)
        {
            if (Traces != null && vm.Driver.DesyncTick != 0)
            {
                vm.Trace.CompareFirstError(Traces.FirstOrDefault(x => x.TickID == vm.Driver.DesyncTick));
            }

            vm.Driver.DesyncTick = 0;
            if (!Run)
            {
                return(true);
            }

            if (vm.FSOVDoAsyncLoad)
            {
                vm.FSOVDoAsyncLoad  = false;
                vm.FSOVAsyncLoading = true;
                Task.Run(() =>
                {
                    vm.FSOVClientJoin = (vm.Context.Architecture == null);
                    vm.LoadAsync(State);
                    if (VM.UseWorld && vm.Context.Blueprint.SubWorlds.Count == 0)
                    {
                        VMLotTerrainRestoreTools.RestoreSurroundings(vm, vm.HollowAdj);
                    }
                    GameThread.InUpdate(() =>
                    {
                        vm.LoadComplete();
                    });
                });
            }
            else
            {
                vm.Load(State);
                if (VM.UseWorld && vm.Context.Blueprint.SubWorlds.Count == 0)
                {
                    VMLotTerrainRestoreTools.RestoreSurroundings(vm, vm.HollowAdj);
                }
            }
            return(true);
        }
Exemple #24
0
        protected BasicGameHost(string gameName = @"")
        {
            Instance = this;

            AppDomain.CurrentDomain.UnhandledException += exceptionHandler;

            Dependencies.Cache(this);
            name = gameName;

            threads = new[]
            {
                DrawThread = new GameThread(DrawFrame, @"Draw")
                {
                    OnThreadStart = DrawInitialize,
                },
                UpdateThread = new GameThread(UpdateFrame, @"Update")
                {
                    OnThreadStart = UpdateInitialize,
                    Monitor       = { HandleGC = true }
                },
                InputThread = new InputThread(null, @"Input") //never gets started.
            };

            Clock = UpdateThread.Clock;

            MaximumUpdateHz = GameThread.DEFAULT_ACTIVE_HZ;
            MaximumDrawHz   = (DisplayDevice.Default?.RefreshRate ?? 0) * 4;

            // Note, that RegisterCounters only has an effect for the first
            // BasicGameHost to be passed into it; i.e. the first BasicGameHost
            // to be instantiated.
            FrameStatistics.RegisterCounters(this);

            Environment.CurrentDirectory = System.IO.Path.GetDirectoryName(FullPath);

            setActive(true);

            AddInternal(inputManager = new UserInputManager(this));

            Dependencies.Cache(inputManager);
        }
Exemple #25
0
        public void MessageReceived(AriesClient client, object message)
        {
            if (client == City)
            {
                if (message is FindLotResponse)
                {
                    AsyncProcessMessage(message);
                }
            }
            else if (client == Client)
            {
                if (message is RequestClientSession ||
                    message is HostOnlinePDU ||
                    message is FSOVMTickBroadcast ||
                    message is FSOVMDirectToClient ||
                    message is ServerByePDU)
                {
                    if (message is ServerByePDU)
                    {
                    }
                    //force in order
                    this.SyncProcessMessage(message);
                }

                if (message is FSOVMProtocolMessage)
                {
                    var msg = (FSOVMProtocolMessage)message;
                    GameThread.InUpdate(() => {
                        if (msg.UseCst)
                        {
                            if (msg.Title != "")
                            {
                                msg.Title = GameFacade.Strings.GetString("223", msg.Title);
                            }
                            msg.Message = GameFacade.Strings.GetString("223", msg.Message);
                        }
                        UIAlert.Alert(msg.Title, msg.Message, true);
                    });
                }
            }
        }
        internal PerformanceMonitor(GameThread thread, IEnumerable <StatisticsCounterType> counters)
        {
            Clock      = thread.Clock;
            threadName = thread.Name;

            isActive = thread.IsActive.GetBoundCopy();
            isActive.BindValueChanged(_ => updateEnabledState());

            currentFrame = FramesPool.Get();

            foreach (var c in counters)
            {
                ActiveCounters[(int)c] = true;
            }

            for (int i = 0; i < FrameStatistics.NUM_PERFORMANCE_COLLECTION_TYPES; i++)
            {
                var t = (PerformanceCollectionType)i;
                endCollectionDelegates[i] = new InvokeOnDisposal(() => endCollecting(t));
            }
        }
Exemple #27
0
        public virtual void InitBlueprint(Blueprint blueprint)
        {
            this.Blueprint = blueprint;
            Platform?.Dispose();
            InitDefaultGraphicsMode();
            State.ProjectTilePos = EstTileAtPosWithScrollHeight;

            Entities     = new WorldEntities(blueprint);
            Architecture = new WorldArchitecture(blueprint);
            Static?.InitBlueprint(blueprint);

            State.Changes = blueprint.Changes;
            GameThread.InUpdate(() =>
            {
                Light?.Init(blueprint);
                State.Rooms.Init(blueprint);
            });

            HasInitBlueprint = true;
            HasInit          = HasInitGPU & HasInitBlueprint;
        }
Exemple #28
0
        public void GetUpdateList(string branchName, Action <ApiUpdate[]> callback)
        {
            var client  = Client();
            var request = new RestRequest("userapi/updates/" + branchName);

            client.ExecuteAsync(request, (resp, h) =>
            {
                GameThread.NextUpdate(x =>
                {
                    if (resp.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        callback(null);
                    }
                    else
                    {
                        var obj = JsonConvert.DeserializeObject <ApiUpdate[]>(resp.Content);
                        callback(obj);
                    }
                });
            });
        }
        public static void RunOnAudioThread(Action action)
        {
            var resetEvent = new ManualResetEvent(false);

            new Thread(() =>
            {
                ThreadSafety.IsAudioThread = true;

                action();

                resetEvent.Set();
            })
            {
                Name = GameThread.PrefixedThreadNameFor("Audio")
            }.Start();

            if (!resetEvent.WaitOne(TimeSpan.FromSeconds(10)))
            {
                throw new TimeoutException();
            }
        }
        public static float[] DequantizeDepth(GraphicsDevice gd, Texture2D depthIn)
        {
            var wait = new AutoResetEvent(false);

            float[] data = null;
            GameThread.InUpdate(() =>
            {
                var targetPrep = new RenderTarget2D(gd, depthIn.Width, depthIn.Height, false, SurfaceFormat.Vector4, DepthFormat.None);
                var target     = new RenderTarget2D(gd, depthIn.Width, depthIn.Height, false, SurfaceFormat.Single, DepthFormat.None);
                gd.SetRenderTarget(targetPrep);

                var effect = SpriteEffect;
                EnsureBatch(gd);

                effect.CurrentTechnique = effect.Techniques["DerivativeDepth"];
                effect.Parameters["pixelSize"].SetValue(new Vector2(1f / depthIn.Width, 1f / depthIn.Height));

                Batch.Begin(rasterizerState: RasterizerState.CullNone, effect: effect);
                Batch.Draw(depthIn, Vector2.Zero, Color.White);
                Batch.End();

                gd.SetRenderTarget(target);

                effect.CurrentTechnique = effect.Techniques["DequantizeDepth"];

                Batch.Begin(rasterizerState: RasterizerState.CullNone, effect: effect);
                Batch.Draw(targetPrep, Vector2.Zero, Color.White);
                Batch.End();

                gd.SetRenderTarget(null);

                data = new float[depthIn.Width * depthIn.Height];
                target.GetData <float>(data);
                target.Dispose();
                targetPrep.Dispose();
                wait.Set();
            });
            wait.WaitOne();
            return(data);
        }
Exemple #31
0
        public static void EnterGameMode(string lotName, bool external)
        {
            GameThread.NextUpdate((x) =>
            {
                var mode = NeighSelectionMode.Normal;
                if (lotName.Length > 1 && lotName[0] == '!')
                {
                    switch (lotName[1])
                    {
                    case 'n':
                        mode = NeighSelectionMode.MoveIn; break;

                    case 'm':
                        mode = NeighSelectionMode.MoveInMagic; break;
                    }
                }
                var screen = new TS1GameScreen(mode);
                if (mode != NeighSelectionMode.Normal)
                {
                    screen.StartMoveIn(int.Parse(lotName.Substring(2)));
                }
                var last = GameFacade.Screens.CurrentUIScreen;
                GameFacade.Screens.RemoveCurrent();
                GameFacade.Screens.AddScreen(screen);

                var load = (last as LoadingScreen);

                if (load != null)
                {
                    load.Close();
                    var children = new List <UIElement>(last.GetChildren());
                    for (int i = 0; i < children.Count; i++)
                    {
                        last.Remove(children[i]);
                        screen.Add(children[i]);
                    }
                }
                screen.Initialize(lotName, external);
            });
        }