Exemple #1
0
        public void ClickLot(int x, int y)
        {
            var id       = MapCoordinates.Pack((ushort)x, (ushort)y);
            var occupied = IsTileOccupied(x, y);

            DataService.Get <Lot>(id).ContinueWith(result =>
            {
                if (occupied)
                {
                    GameThread.InUpdate(() => { Parent.ShowLotPage(id); });
                }
                else if (!Realestate.IsPurchasable((ushort)x, (ushort)y))
                {
                    return;
                }
                else if (result.Result.Lot_Price == 0)
                {
                    //We need to request the price
                    DataService.Request(MaskedStruct.MapView_RollOverInfo_Lot_Price, id).ContinueWith(masked =>
                    {
                        ShowLotBuyDialog((Lot)masked.Result);
                    });
                }
                else
                {
                    //Good to show dialog
                    ShowLotBuyDialog(result.Result);
                }
            });
        }
Exemple #2
0
        public void MessageReceived(AriesClient client, object message)
        {
            if (message is FindAvatarResponse)
            {
                var loc = (FindAvatarResponse)message;
                GameThread.InUpdate(() =>
                {
                    switch (loc.Status)
                    {
                    case FindAvatarResponseStatus.FOUND:
                        View.FindController <CoreGameScreenController>()?.ShowLotPage(loc.LotId & 0x3FFFFFFF);    //ignore transient part
                        break;

                    default:
                        if (loc.Status == FindAvatarResponseStatus.PRIVACY_ENABLED)
                        {
                            loc.Status = FindAvatarResponseStatus.NOT_ON_LOT;
                        }
                        UIAlert alert = null;
                        alert         = UIScreen.GlobalShowAlert(new UIAlertOptions()
                        {
                            Title     = "",
                            Message   = GameFacade.Strings.GetString("189", (49 + (int)loc.Status).ToString()),
                            Buttons   = UIAlertButton.Ok((btn) => UIScreen.RemoveDialog(alert)),
                            Alignment = TextAlignment.Left
                        }, true);
                        break;
                    }
                });
            }
        }
 public void MessageReceived(AriesClient client, object message)
 {
     if (message is RequestClientSession ||
         message is HostOnlinePDU || message is ServerByePDU)
     {
         this.AsyncProcessMessage(message);
     }
     else if (message is AnnouncementMsgPDU)
     {
         GameThread.InUpdate(() =>
         {
             var msg       = (AnnouncementMsgPDU)message;
             UIAlert alert = null;
             alert         = UIScreen.GlobalShowAlert(new UIAlertOptions()
             {
                 Title   = GameFacade.Strings.GetString("195", "30") + GameFacade.CurrentCityName,
                 Message = GameFacade.Strings.GetString("195", "28") + msg.SenderID.Substring(2) + "\r\n"
                           + GameFacade.Strings.GetString("195", "29") + msg.Subject + "\r\n"
                           + msg.Message,
                 Buttons   = UIAlertButton.Ok((btn) => UIScreen.RemoveDialog(alert)),
                 Alignment = TextAlignment.Left
             }, true);
         });
     }
     else if (message is GlobalTuningUpdate)
     {
         var msg = (message as GlobalTuningUpdate);
         DynamicTuning.Global = msg.Tuning;
         Content.Content.Get().Upgrades.LoadNetTuning(msg.ObjectUpgrades);
     }
     else if (message is ChangeRoommateResponse)
     {
     }
 }
Exemple #4
0
        public void SearchLots(string query, bool exact, Action <List <GizmoLotSearchResult> > callback)
        {
            DatabaseService.Search(new SearchRequest {
                Query = query, Type = SearchType.LOTS
            }, exact)
            .ContinueWith(x =>
            {
                GameThread.InUpdate(() =>
                {
                    object[] ids = x.Result.Items.Select(y => (object)y.EntityId).ToArray();
                    var results  = x.Result.Items.Select(q =>
                    {
                        return(new GizmoLotSearchResult()
                        {
                            Result = q
                        });
                    }).ToList();

                    if (ids.Length > 0)
                    {
                        var lots = DataService.GetMany <Lot>(ids).Result;
                        foreach (var item in lots)
                        {
                            results.First(f => f.Result.EntityId == item.Id).Lot = item;
                        }
                    }

                    callback(results);
                });
            });
        }
        private void ChangeState <TView, TController>(Callback <TView, TController> onCreated) where TView : UIScreen
        {
            Binding.DisposeAll();
            GameThread.InUpdate(() =>
            {
                GameFacade.Cursor.SetCursor(Common.Rendering.Framework.CursorType.Normal); //reset cursor
                if (CurrentController != null)
                {
                    if (CurrentController is IDisposable)
                    {
                        ((IDisposable)CurrentController).Dispose();
                    }
                }

                var view       = (UIScreen)Kernel.Get <TView>();
                var controller = ControllerUtils.BindController <TController>(view);
                GameFacade.Screens.RemoveCurrent();
                GameFacade.Screens.AddScreen(view);

                CurrentController = controller;
                CurrentView       = view;

                onCreated((TView)view, controller);
            });
        }
        public void Search(string query, bool exact)
        {
            DatabaseService.Search(new SearchRequest {
                Query = query, Type = SearchType.SIMS
            }, exact)
            .ContinueWith(x =>
            {
                GameThread.InUpdate(() =>
                {
                    object[] ids = x.Result.Items.Select(y => (object)y.EntityId).ToArray();
                    var results  = x.Result.Items.Select(q =>
                    {
                        return(new GizmoAvatarSearchResult()
                        {
                            Result = q
                        });
                    }).ToList();

                    if (ids.Length > 0)
                    {
                        var avatars = DataService.GetMany <Avatar>(ids).Result;
                        foreach (var item in avatars)
                        {
                            results.First(f => f.Result.EntityId == item.Avatar_Id).Avatar = item;
                        }
                    }

                    View.SetAvatarResults(results, exact);
                });
            });
        }
        private void Regulator_OnError(object data)
        {
            //UIScreen.RemoveDialog(View);
            GameThread.InUpdate(() =>
            {
                GameFacade.Cursor.SetCursor(CursorType.Normal);

                var errorTitle = GameFacade.Strings.GetString("211", "45");
                var errorBody  = GameFacade.Strings.GetString("211", "45");

                if (data is FindLotResponseStatus)
                {
                    var status = (FindLotResponseStatus)data;

                    switch (status)
                    {
                    case FindLotResponseStatus.NOT_OPEN:
                    case FindLotResponseStatus.NOT_PERMITTED_TO_OPEN:
                        errorTitle = GameFacade.Strings.GetString("211", "7");
                        errorBody  = GameFacade.Strings.GetString("211", "8");
                        break;

                    case FindLotResponseStatus.NO_CAPACITY:
                        errorTitle = GameFacade.Strings.GetString("211", "11");
                        errorBody  = GameFacade.Strings.GetString("211", "12");
                        break;

                    case FindLotResponseStatus.CLAIM_FAILED:
                        errorTitle = GameFacade.Strings.GetString("211", "45");
                        errorBody  = GameFacade.Strings.GetString("211", "41");
                        break;

                    case FindLotResponseStatus.NO_ADMIT:
                        errorTitle = GameFacade.Strings.GetString("211", "45");
                        errorBody  = GameFacade.Strings.GetString("211", "42");
                        break;

                    default:
                        break;
                    }
                }

                UIAlert alert = null;
                alert         = UIScreen.GlobalShowAlert(new UIAlertOptions()
                {
                    Title   = errorTitle,
                    Message = errorBody,
                    Buttons = UIAlertButton.Ok(x =>
                    {
                        UIScreen.RemoveDialog(View);
                        UIScreen.RemoveDialog(alert);
                    })
                }, true);
            });
        }
Exemple #8
0
        private void Regulator_OnTransition(string state, object data)
        {
            var progress = 0;

            GameThread.InUpdate(() =>
            {
                switch (state)
                {
                case "Disconnected":
                    UIScreen.RemoveDialog(View);
                    break;

                case "SelectLot":
                    UIScreen.GlobalShowDialog(View, true);
                    break;

                case "FindLot":
                    break;

                case "FoundLot":
                case "OpenSocket":
                case "SocketOpen":
                    progress = 1;
                    break;

                case "HostOnline":
                case "RequestClientSession":
                    progress = 2;
                    break;

                case "PartiallyConnected":
                    progress = 3;
                    break;

                case "LotCommandStream":
                    progress = 4;
                    break;
                }
                var progressPercent = (((float)progress) / 12.0f) * 100;
                if (progress < 4)
                {
                    View.Progress = progressPercent;
                }
                switch (progress)
                {
                case 0:
                    View.ProgressCaption = GameFacade.Strings.GetString("211", "4");
                    break;

                default:
                    View.ProgressCaption = GameFacade.Strings.GetString("211", (21 + progress).ToString());
                    break;
                }
            });
        }
Exemple #9
0
        public void BeginUpdate()
        {
            Updating = true;
            var progress = new UILoginProgress()
            {
                Caption = GameFacade.Strings.GetString("f101", "18")
            };

            GlobalShowDialog(progress, true);

            var  file  = File.Open("Content/Patch/1239toNI.tsop", FileMode.Open, FileAccess.Read, FileShare.Read);
            TSOp patch = new TSOp(file);

            var content   = Content.Content.Get();
            var patchPath = Path.GetFullPath(Path.Combine(content.BasePath, "../"));

            Task.Run(() => patch.Apply(patchPath, patchPath, (string message, float pct) =>
            {
                GameThread.InUpdate(() =>
                {
                    if (pct == -1)
                    {
                        UIScreen.GlobalShowAlert(new UIAlertOptions
                        {
                            Title   = GameFacade.Strings.GetString("f101", "19"),
                            Message = GameFacade.Strings.GetString("f101", "20", new string[] { message }),
                            Buttons = UIAlertButton.Ok(y =>
                            {
                                RestartGame();
                            })
                        }, true);
                    }
                    else
                    {
                        progress.Progress        = pct * 100;
                        progress.ProgressCaption = message;
                    }
                });
            })).ContinueWith((task) =>
            {
                GameThread.InUpdate(() =>
                {
                    UIScreen.RemoveDialog(progress);
                    UIScreen.GlobalShowAlert(new UIAlertOptions
                    {
                        Title   = GameFacade.Strings.GetString("f101", "3"),
                        Message = GameFacade.Strings.GetString("f101", "13"),
                        Buttons = UIAlertButton.Ok(y =>
                        {
                            RestartGame();
                        })
                    }, true);
                });
            });
        }
Exemple #10
0
 void PurchaseRegulator_OnTransition(string state, object data)
 {
     GameThread.InUpdate(() =>
     {
         if (state == "PurchaseComplete")
         {
             DataService.Request(MaskedStruct.CurrentCity, 0);
             ShowCreationProgressBar(false);
         }
     });
 }
 private void ResolveCallbacks(BulletinResponseType code)
 {
     GameThread.InUpdate(() =>
     {
         foreach (var cb in Callbacks)
         {
             cb.Invoke(code);
         }
         Callbacks.Clear();
         Blocked = false;
     });
 }
        private void Regulator_OnTransition(string state, object data)
        {
            var progress = 0;

            GameThread.InUpdate(() =>
            {
                switch (state)
                {
                case "Idle":
                    if (Callbacks.Count > 0)
                    {
                        ResolveCallbacks(BulletinResponseType.CANCEL);
                    }
                    if (BlockingDialog != null)
                    {
                        UIScreen.RemoveDialog(BlockingDialog);
                        BlockingDialog = null;
                    }
                    break;

                case "ActionInput":
                    //show blocking dialog for this action
                    //not used for bulletin right now
                    var req = ConnectionReg.CurrentRequest;
                    switch (req.Type)
                    {
                    case BulletinRequestType.CAN_POST_MESSAGE:
                    case BulletinRequestType.CAN_POST_SYSTEM_MESSAGE:
                        break;

                    default:
                        //something went terribly wrong - we don't have any dialog to handle this.
                        ConnectionReg.AsyncReset();
                        break;
                    }
                    break;

                case "ActionSuccess":
                    var packet = (BulletinResponse)data;
                    if (packet.Type == BulletinResponseType.SEND_SUCCESS)
                    {
                        CreatedMessage = packet.Messages[0];
                    }
                    else if (packet.Type == BulletinResponseType.MESSAGES)
                    {
                        BulletinBoard = packet.Messages;
                    }
                    ResolveCallbacks(BulletinResponseType.SUCCESS);
                    break;
                }
            });
        }
        private void JoinLotRegulator_OnTransition(string transition, object data)
        {
            GameThread.InUpdate(() =>
            {
                switch (transition)
                {
                case "UnexpectedDisconnect":
                    //todo: what if we disconnect from lot but not city? the reverse?
                    break;

                case "Disconnected":
                    Screen.CleanupLastWorld();
                    if (ReconnectLotID != 0)
                    {
                        GameThread.SetTimeout(() => {
                            if (ReconnectLotID != 0)
                            {
                                JoinLot(ReconnectLotID);
                            }
                        }, 100);
                    }
                    //destroy the currently active lot (if possible)
                    break;

                case "PartiallyConnected":
                    Screen.InitializeLot();
                    Screen.vm.MyUID = Network.MyCharacter;
                    //initialize a lot
                    break;

                case "LotCommandStream":
                    //forward the command to the VM
                    //doesn't really need to be next update... but we don't want to catch the VM in a half-init state.
                    if (data == null)
                    {
                        break;
                    }
                    VMNetMessage msg = null;
                    if (data is FSOVMTickBroadcast)
                    {
                        msg = new VMNetMessage(VMNetMessageType.BroadcastTick, ((FSOVMTickBroadcast)data).Data);
                    }
                    else
                    {
                        msg = new VMNetMessage(VMNetMessageType.Direct, ((FSOVMDirectToClient)data).Data);
                    }

                    Screen.Driver?.ServerMessage(msg);
                    break;
                }
            });
        }
 public void GetAvatarModel(uint key, Callback <Avatar> callback)
 {
     DataService.Get <Avatar>(key).ContinueWith(x =>
     {
         if (x.Result != null)
         {
             GameThread.InUpdate(() =>
             {
                 callback(x.Result);
             });
         }
     });
 }
Exemple #15
0
 public void Search(string name)
 {
     DatabaseService.Search(new SearchRequest {
         Query = name, Type = SearchType.SIMS
     }, false)
     .ContinueWith(x =>
     {
         GameThread.InUpdate(() =>
         {
             View.SetFilter(new HashSet <uint>(x.Result.Items.Select(y => y.EntityId)));
         });
     });
 }
Exemple #16
0
        public virtual void InitBlueprint(Blueprint blueprint)
        {
            this.Blueprint = blueprint;
            _2DWorld.Init(blueprint);
            _3DWorld.Init(blueprint);
            GameThread.InUpdate(() =>
            {
                Light?.Init(blueprint);
                State.Rooms.Init(blueprint);
            });

            HasInitBlueprint = true;
            HasInit          = HasInitGPU & HasInitBlueprint;
        }
Exemple #17
0
 private void VMRefreshed()
 {
     if (vm == null)
     {
         return;
     }
     GameThread.InUpdate(() =>
     {
         if (vm.LoadErrors.Count > 0)
         {
             HandleLoadErrors();
         }
         LotControl.ActiveEntity = null;
         LotControl.RefreshCut();
     });
 }
Exemple #18
0
        /// <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 #19
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)
     {
     }
 }
        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);
                });
            });
        }
 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);
             }
         });
     });
 }
Exemple #22
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);
                    });
                }
            }
        }
        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
        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;
        }
        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);
        }
        public void FindMyNhood(Action <uint> callback)
        {
            DataService.Get <Avatar>(Network.MyCharacter).ContinueWith(x =>
            {
                if (x.Result != null)
                {
                    x.Result.Avatar_LotGridXY           = uint.MaxValue;
                    PropertyChangedEventHandler handler = null;
                    handler = (obj, evt) =>
                    {
                        if (evt.PropertyName == "Avatar_LotGridXY")
                        {
                            x.Result.PropertyChanged -= handler;
                            DataService.Get <Lot>(x.Result.Avatar_LotGridXY).ContinueWith(y =>
                            {
                                y.Result.Lot_NeighborhoodID          = 0;
                                PropertyChangedEventHandler handler2 = null;
                                handler2 = (obj2, evt2) =>
                                {
                                    if (evt2.PropertyName == "Lot_NeighborhoodID")
                                    {
                                        y.Result.PropertyChanged -= handler2;
                                        GameThread.InUpdate(() =>
                                        {
                                            callback(y.Result.Lot_NeighborhoodID);
                                        });
                                    }
                                };
                                y.Result.PropertyChanged += handler2;
                                DataService.Request(Server.DataService.Model.MaskedStruct.PropertyPage_LotInfo, y.Result.Id);
                            });
                        }
                    };
                    x.Result.PropertyChanged += handler;

                    DataService.Request(Server.DataService.Model.MaskedStruct.SimPage_Main, Network.MyCharacter);
                }
            });
        }
Exemple #27
0
 public void EnableParticle(ushort id)
 {
     if (UseWorld)
     {
         var parts    = ((ObjectComponent)WorldUI).Particles;
         var relevant = parts.FirstOrDefault(x => x.Resource?.ChunkID == id && float.IsPositiveInfinity(x.StopTime));
         if (relevant == null)
         {
             var part = new ParticleComponent(WorldUI.blueprint, WorldUI.blueprint.ObjectParticles);
             //for now there is only one particle resource. In future get from iff.
             part.Resource = PART.BROKEN;
             part.Mode     = ParticleType.GENERIC_BOX;
             GameThread.InUpdate(() =>
             {
                 part.Tex = Content.Content.Get().RCMeshes.GetTex("FSO_smoke.png");
                 WorldUI.blueprint.ObjectParticles.Add(part);
             });
             ((ObjectComponent)WorldUI).Particles.Add(part);
             part.Owner = WorldUI;
             WorldUI.blueprint.Damage.Add(new BlueprintDamage(BlueprintDamageType.OBJECT_GRAPHIC_CHANGE, WorldUI.TileX, WorldUI.TileY, WorldUI.Level, WorldUI));
         }
     }
 }
        private void ShowLotBuyDialog(Lot lot)
        {
            GameThread.InUpdate(() =>
            {
                GameFacade.Cursor.SetCursor(Common.Rendering.Framework.CursorType.Hourglass);
                if (_LotBuyAlert != null)
                {
                    return;
                }
                _LotBuyAlert = new UIAlert(new UIAlertOptions()
                {
                    Title = "", Message = ""
                });                                                                            //just fill this space til we spawn the dialog.
                _BuyLot = lot;
                Parent.Screen.CityTooltipHitArea.HideTooltip();

                var price   = lot.Lot_Price;
                var ourCash = Parent.Screen.VisualBudget;


                DataService.Request(MaskedStruct.SimPage_Main, Network.MyCharacter).ContinueWith(x =>
                {
                    var avatar = x.Result as Avatar;
                    if (!x.IsFaulted && avatar != null && avatar.Avatar_LotGridXY != 0)
                    {
                        //we already have a lot. We need to show the right dialog depending on whether or not we're owner.
                        var oldID = avatar.Avatar_LotGridXY;
                        DataService.Request(MaskedStruct.PropertyPage_LotInfo, oldID).ContinueWith(y =>
                        {
                            GameThread.SetTimeout(() => //setting a timeout here because for some reason when the request finishes we might not have all of the data yet...
                            {
                                GameFacade.Cursor.SetCursor(Common.Rendering.Framework.CursorType.Normal);
                                bool canBuy = true;
                                if (!y.IsFaulted && y.Result != null)
                                {
                                    var old = (Lot)y.Result;
                                    UIAlertOptions AlertOptions = new UIAlertOptions();
                                    if (old.Lot_LeaderID == Network.MyCharacter)
                                    {
                                        //we are the owner
                                        var oldVal   = old.Lot_Price;
                                        var moveFee  = 2000;
                                        var moveCost = moveFee + price;

                                        canBuy = (moveCost - oldVal) <= ourCash;
                                        if (old.Lot_RoommateVec.Count > 1)
                                        {
                                            //we have other roommates.
                                            AlertOptions.Title   = GameFacade.Strings.GetString("215", "10");
                                            AlertOptions.Message = GameFacade.Strings.GetString("215", "12",
                                                                                                new string[] { "$" + price.ToString(), "$" + ourCash.ToString(), "$" + moveCost.ToString(), "$" + moveFee.ToString(), "$" + oldVal.ToString() });
                                            AlertOptions.Buttons = new UIAlertButton[] {
                                                new UIAlertButton(UIAlertButtonType.Yes, (button) => { MoveLot(false); }, GameFacade.Strings.GetString("215", "14")),
                                                new UIAlertButton(UIAlertButtonType.Cancel, BuyPropertyAlert_OnCancel)
                                            };
                                        }
                                        else
                                        {
                                            //we live alone
                                            AlertOptions.Title   = GameFacade.Strings.GetString("215", "10");
                                            AlertOptions.Message = GameFacade.Strings.GetString("215", "16",
                                                                                                new string[] { "$" + price.ToString(), "$" + ourCash.ToString(), "$" + moveCost.ToString(), "$" + moveFee.ToString(), "$" + oldVal.ToString() });
                                            AlertOptions.Buttons = new UIAlertButton[] {
                                                new UIAlertButton(UIAlertButtonType.OK, (button) => { MoveLot(false); }, GameFacade.Strings.GetString("215", "17")),
                                                new UIAlertButton(UIAlertButtonType.Yes, (button) => { MoveLot(true); }, GameFacade.Strings.GetString("215", "18")),
                                                new UIAlertButton(UIAlertButtonType.Cancel, BuyPropertyAlert_OnCancel)
                                            };
                                        }
                                    }
                                    else
                                    {
                                        //we are a roommate.
                                        //can leave and start a new lot with no issue.
                                        canBuy               = price <= ourCash;
                                        AlertOptions.Title   = GameFacade.Strings.GetString("215", "10");
                                        AlertOptions.Message = GameFacade.Strings.GetString("215", "20", new string[] { "$" + price.ToString(), "$" + ourCash.ToString() });
                                        AlertOptions.Buttons = new UIAlertButton[] {
                                            new UIAlertButton(UIAlertButtonType.Yes, (btn) => {
                                                UIScreen.RemoveDialog(_LotBuyAlert);
                                                _LotBuyAlert = UIScreen.GlobalShowAlert(new UIAlertOptions()
                                                {
                                                    Message = GameFacade.Strings.GetString("211", "57"),
                                                    Buttons = new UIAlertButton[0]
                                                }, true);
                                                Parent.MoveMeOut(oldID, (result) => {
                                                    if (result)
                                                    {
                                                        BuyPropertyAlert_OnButtonClick(btn);
                                                    }
                                                });
                                            }),
                                            new UIAlertButton(UIAlertButtonType.No, BuyPropertyAlert_OnCancel)
                                        };
                                    }

                                    AlertOptions.Width = 600;
                                    _LotBuyAlert       = UIScreen.GlobalShowAlert(AlertOptions, true);
                                    UIButton toDisable;
                                    if (_LotBuyAlert.ButtonMap.TryGetValue(UIAlertButtonType.OK, out toDisable))
                                    {
                                        toDisable.Disabled = !canBuy;
                                    }
                                    if (_LotBuyAlert.ButtonMap.TryGetValue(UIAlertButtonType.Yes, out toDisable))
                                    {
                                        toDisable.Disabled = !canBuy;
                                    }
                                }
                                else
                                {
                                    canBuy = price <= ourCash;
                                    ShowNormalLotBuy("$" + price.ToString(), "$" + ourCash.ToString());
                                    UIButton toDisable;
                                    if (_LotBuyAlert.ButtonMap.TryGetValue(UIAlertButtonType.Yes, out toDisable))
                                    {
                                        toDisable.Disabled = !canBuy;
                                    }
                                }
                            }, 100);
                        });
                    }
                    else
                    {
                        //we don't have a lot
                        _LotBuyAlert = null;
                        ShowNormalLotBuy("$" + price.ToString(), "$" + ourCash.ToString());
                        var canBuy = price <= ourCash;
                        UIButton toDisable;
                        if (_LotBuyAlert.ButtonMap.TryGetValue(UIAlertButtonType.Yes, out toDisable))
                        {
                            toDisable.Disabled = !canBuy;
                        }
                        GameFacade.Cursor.SetCursor(Common.Rendering.Framework.CursorType.Normal);
                    }
                });
            });
        }
        public void ClickLot(int x, int y)
        {
            var id       = MapCoordinates.Pack((ushort)x, (ushort)y);
            var occupied = IsTileOccupied(x, y);

            DataService.Get <Lot>(id).ContinueWith(result =>
            {
                if (occupied)
                {
                    GameThread.InUpdate(() =>
                    {
                        if (PlacingTownHall)
                        {
                            UIAlert.Alert("", GameFacade.Strings.GetString("f115", "51"), true);
                        }
                        else
                        {
                            Parent.ShowLotPage(id);
                        }
                    });
                }
                else if (!Realestate.IsPurchasable((ushort)x, (ushort)y))
                {
                    return;
                }
                else if (PlacingTownHall && View.NeighGeom.NhoodNearestDB(x, y) != TownHallNhood)
                {
                    UIAlert.Alert("", GameFacade.Strings.GetString("f115", "50", new string[] { TownHallNhoodName }), true);
                    return;
                }
                else
                {
                    if (PlacingTownHall)
                    {
                        //we don't particularly care about the price,
                        //all we need to know is if it is in the correct nhood

                        var ourCash = Parent.Screen.VisualBudget;
                        _BuyLot     = result.Result;

                        if (ourCash < 2000)
                        {
                            UIAlert.Alert("", GameFacade.Strings.GetString("f115", "90"), true);
                        }
                        else
                        {
                            UIAlert.YesNo("", GameFacade.Strings.GetString("f115", "49"), true,
                                          (complete) =>
                            {
                                if (complete)
                                {
                                    if (!TownHallMove)
                                    {
                                        //User needs to name the property
                                        _LotBuyName = new UILotPurchaseDialog();
                                        UIScreen.GlobalShowDialog(new DialogReference
                                        {
                                            Dialog     = _LotBuyName,
                                            Controller = this,
                                            Modal      = true,
                                        });
                                    }
                                    else
                                    {
                                        PurchaseRegulator.Purchase(new Regulators.PurchaseLotRequest
                                        {
                                            X          = _BuyLot.Lot_Location.Location_X,
                                            Y          = _BuyLot.Lot_Location.Location_Y,
                                            Name       = "",
                                            StartFresh = false,
                                            Mayor      = true
                                        });
                                    }
                                }
                            });
                        }
                    }
                    else
                    {
                        if (result.Result.Lot_Price == 0)
                        {
                            //We need to request the price
                            DataService.Request(MaskedStruct.MapView_RollOverInfo_Lot_Price, id).ContinueWith(masked =>
                            {
                                ShowLotBuyDialog((Lot)masked.Result);
                            });
                        }
                        else
                        {
                            //Good to show dialog
                            ShowLotBuyDialog(result.Result);
                        }
                    }
                }
            });
        }
Exemple #30
0
        public void LoadAsync(VMMarshal input)
        {
            FSOVAsyncLoading = true;
            var lastBp = Context.Blueprint; //try keep this alive I suppose

            //var oldWorld = Context.World;
            //TS1 = input.TS1;
            Context    = new VMContext(input.Context, Context);
            Context.VM = this;
            var idMap = input.Context.Architecture.IDMap;

            if (idMap != null)
            {
                idMap.Apply(this);
            }
            Context.Architecture.RegenRoomMap();
            Context.RegeneratePortalInfo();
            Context.Architecture.Terrain.RegenerateCenters();

            if (VM.UseWorld)
            {
                Context.Blueprint.Altitude        = Context.Architecture.Terrain.Heights;
                Context.Blueprint.AltitudeCenters = Context.Architecture.Terrain.Centers;
            }

            var oldSounds = new List <VMSoundTransfer>();

            if (Entities != null) //free any object resources here.
            {
                foreach (var obj in Entities)
                {
                    obj.Dead = true;
                    if (obj.HeadlineRenderer != null)
                    {
                        if (UseWorld)
                        {
                            GameThread.InUpdate(() =>
                            {
                                obj.HeadlineRenderer.Dispose();
                            });
                        }
                    }
                    oldSounds.AddRange(obj.GetActiveSounds());
                }
            }

            SoundEntities = new HashSet <VMEntity>();
            Entities      = new List <VMEntity>();
            Scheduler.Reset();
            ObjectsById  = new Dictionary <short, VMEntity>();
            FSOVObjTotal = input.Entities.Length;
            foreach (var ent in input.Entities)
            {
                VMEntity realEnt;
                var      objDefinition = FSO.Content.Content.Get().WorldObjects.Get(ent.GUID);
                if (objDefinition == null)
                {
                    LoadErrors.Add(new VMLoadError(VMLoadErrorCode.MISSING_OBJECT,
                                                   "0x" + ent.GUID.ToString("X8") + " " + input.MultitileGroups.FirstOrDefault(x => x.Objects.Contains(ent.ObjectID))?.Name ?? "(unknown name)", (ushort)ent.ObjectID));
                    ent.LoadFailed = true;
                    continue;
                }
                if (ent is VMAvatarMarshal)
                {
                    var avatar = new VMAvatar(objDefinition);
                    avatar.Load((VMAvatarMarshal)ent);
                    if (UseWorld)
                    {
                        Context.Blueprint.AddAvatar((AvatarComponent)avatar.WorldUI);
                    }
                    realEnt = avatar;
                }
                else
                {
                    var worldObject = Context.MakeObjectComponent(objDefinition);
                    var obj         = new VMGameObject(objDefinition, worldObject);
                    obj.Load((VMGameObjectMarshal)ent);
                    if (UseWorld)
                    {
                        Context.Blueprint.AddObject((ObjectComponent)obj.WorldUI);
                        Context.Blueprint.ChangeObjectLocation((ObjectComponent)obj.WorldUI, obj.Position);
                    }
                    obj.Position = obj.Position;
                    realEnt      = obj;
                }
                realEnt.FetchTreeByName(Context);
                Entities.Add(realEnt);
                Context.ObjectQueries.NewObject(realEnt);
                ObjectsById.Add(ent.ObjectID, realEnt);
                FSOVObjLoaded++;
            }

            int i = 0;
            int j = 0;

            foreach (var ent in input.Entities)
            {
                if (ent.LoadFailed)
                {
                    i++;
                    continue;
                }
                var threadMarsh = input.Threads[i];
                var realEnt     = Entities[j++];
                i++;

                realEnt.Thread = new VMThread(threadMarsh, Context, realEnt);
                Scheduler.ScheduleTickIn(realEnt, 1);

                if (realEnt is VMAvatar)
                {
                    ((VMAvatar)realEnt).LoadCrossRef((VMAvatarMarshal)ent, Context);
                }
                else
                {
                    ((VMGameObject)realEnt).LoadCrossRef((VMGameObjectMarshal)ent, Context);
                }
            }

            foreach (var multi in input.MultitileGroups)
            {
                var grp = new VMMultitileGroup(multi, Context); //should self register
                if (VM.UseWorld)
                {
                    var b      = grp.BaseObject;
                    var avgPos = new LotTilePos();
                    foreach (var obj in grp.Objects)
                    {
                        avgPos += obj.Position;
                    }
                    avgPos /= Math.Max(grp.Objects.Count, 1);

                    foreach (var obj in grp.Objects)
                    {
                        var off = obj.Position - avgPos;
                        obj.WorldUI.MTOffset = new Vector3(off.x, off.y, 0);
                        obj.Position         = obj.Position;
                    }
                }
                var persist = grp.BaseObject?.PersistID ?? 0;
                if (persist != 0 && grp.BaseObject is VMGameObject)
                {
                    Context.ObjectQueries.RegisterMultitilePersist(grp, persist);
                }
            }

            foreach (var ent in Entities)
            {
                if (ent.Container == null)
                {
                    ent.PositionChange(Context, true);                        //called recursively for contained objects.
                }
            }

            GlobalState = input.GlobalState;
            if (TS1)
            {
                ((VMTS1LotState)input.PlatformState).CurrentFamily = TS1State.CurrentFamily;
            }
            var lastPlatformState = PlatformState;

            PlatformState = input.PlatformState;
            PlatformState.ActivateValidator(this);
            if (lastPlatformState != null && lastPlatformState is VMTSOLotState)
            {
                TSOState.Names = ((VMTSOLotState)lastPlatformState).Names;
            }
            ObjectId = input.ObjectId;

            //just a few final changes to refresh everything, and avoid signalling objects
            var clock = Context.Clock;

            Context.Architecture.SetTimeOfDay();

            Context.Architecture.SignalAllDirty();
            Context.DisableRouteInvalidation = true;
            Context.Architecture.Tick();
            Context.DisableRouteInvalidation = false;

            Context.Architecture.WallDirtyState(input.Context.Architecture);

            if (oldSounds.Count > 0)
            {
                GameThread.InUpdate(() =>
                {
                    foreach (var snd in oldSounds)
                    {
                        //find new owners
                        var obj = GetObjectById(snd.SourceID);
                        if (obj == null || obj.Object.GUID != snd.SourceGUID)
                        {
                            snd.SFX.Sound.RemoveOwner(snd.SourceID);
                        }
                        else
                        {
                            SoundEntities.Add(obj);
                            obj.SoundThreads.Add(snd.SFX); // successfully transfer sound to new object
                        }
                    }
                });
            }

            Context.UpdateTSOBuildableArea();
            Tuning = input.Tuning;
            UpdateTuning();
            if (OnFullRefresh != null)
            {
                OnFullRefresh();
            }
        }