Init() static private method

static private Init ( ) : void
return void
コード例 #1
0
ファイル: CVMInstance.cs プロジェクト: glenray2000/FreeSo-1
        public void ResetVM()
        {
            VMNetDriver driver;

            driver = new VMServerDriver(Port, NetClosed);

            var vm = new VM(new VMContext(null), driver, new VMNullHeadlineProvider());

            state = vm;
            vm.Init();
            vm.OnChatEvent += Vm_OnChatEvent;

            var    path     = Settings.Default.GamePath + "housedata/blueprints/" + Settings.Default.DebugLot;
            string filename = Path.GetFileName(path);

            try
            {
                //try to load from FSOV first.
                LoadState(vm, "Content/LocalHouse/" + filename.Substring(0, filename.Length - 4) + ".fsov");
            }
            catch (Exception)
            {
                try
                {
                    Console.WriteLine("Failed FSOV load... Trying Backup");
                    LoadState(vm, "Content/LocalHouse/" + filename.Substring(0, filename.Length - 4) + "_backup.fsov");
                }
                catch (Exception)
                {
                    Console.WriteLine("CRITICAL::: Failed FSOV load... Trying Blueprint (first run or something went wrong)");
                    short jobLevel = -1;

                    //quick hack to find the job level from the chosen blueprint
                    //the final server will know this from the fact that it wants to create a job lot in the first place...

                    try
                    {
                        if (filename.StartsWith("nightclub") || filename.StartsWith("restaurant") || filename.StartsWith("robotfactory"))
                        {
                            jobLevel = Convert.ToInt16(filename.Substring(filename.Length - 9, 2));
                        }
                    }
                    catch (Exception) { }

                    vm.SendCommand(new VMBlueprintRestoreCmd
                    {
                        JobLevel = jobLevel,
                        XMLData  = File.ReadAllBytes(path)
                    });

                    vm.Context.Clock.Hours = 10;
                }
            }
            vm.MyUID = uint.MaxValue - 1;
            vm.SendCommand(new VMNetSimJoinCmd
            {
                ActorUID = uint.MaxValue - 1,
                Name     = "server"
            });
        }
コード例 #2
0
        public void PopulateList(FAMI family)
        {
            var world = new FSO.LotView.World(GameFacade.GraphicsDevice);

            world.Initialize(GameFacade.Scenes);
            var context = new VMContext(world);
            var vm      = new VM(context, new VMServerDriver(new VMTS1GlobalLinkStub()), new VMNullHeadlineProvider());

            vm.Init();
            var blueprint = new Blueprint(1, 1);

            //world.InitBlueprint(blueprint);
            context.Blueprint    = blueprint;
            context.Architecture = new VMArchitecture(1, 1, blueprint, vm.Context);

            int i     = 0;
            var baseX = 0;

            foreach (var sim in family.FamilyGUIDs)
            {
                var fam = vm.Context.CreateObjectInstance(sim, LotTilePos.OUT_OF_WORLD, Direction.NORTH, true).BaseObject;
                var btn = new UIAvatarSelectButton(UIIconCache.GetObject(fam));
                btn.Opacity = 1f;
                var id = i;
                btn.Name = fam.Name;
                btn.X    = baseX + (i++) * 100;
                btn.Y    = 0;
                btn.DeregisterHandler();
                Btns.Add(btn);
                Add(btn);
                fam.Delete(true, vm.Context);
            }
            world.Dispose();
        }
コード例 #3
0
        public void InitializeLot()
        {
            CleanupLastWorld();

            if (FSOEnvironment.Enable3D)
            {
                var rc = new LotView.RC.WorldRC(GameFacade.GraphicsDevice);
                rc.SetSurroundingWorld(CityRenderer);
                World = rc;
            }
            else
            {
                World = new World(GameFacade.GraphicsDevice);
            }

            WorldLoaded   = false;
            World.Opacity = 0;
            GameFacade.Scenes.Add(World);
            Driver = new VMClientDriver(ClientStateChange);
            Driver.OnClientCommand += VMSendCommand;
            Driver.OnShutdown      += VMShutdown;

            vm = new VM(new VMContext(World), Driver, new UIHeadlineRendererProvider())
            {
                FSOVDoAsyncLoad = true
            };
            vm.ListenBHAVChanges();
            vm.Init();

            LotControl = new UILotControl(vm, World);
            AddAt(1, LotControl);

            var time    = DateTime.UtcNow;
            var tsoTime = TSOTime.FromUTC(time);

            vm.Context.Clock.Hours   = tsoTime.Item1;
            vm.Context.Clock.Minutes = tsoTime.Item2;
            if (m_ZoomLevel > 3)
            {
                World.Visible      = false;
                LotControl.Visible = false;
            }

            ZoomLevel = Math.Max(ZoomLevel, 4);

            if (IDEHook.IDE != null)
            {
                IDEHook.IDE.StartIDE(vm);
            }

            vm.OnFullRefresh      += VMRefreshed;
            vm.OnChatEvent        += Vm_OnChatEvent;
            vm.OnEODMessage       += LotControl.EODs.OnEODMessage;
            vm.OnRequestLotSwitch += VMLotSwitch;
            vm.OnGenericVMEvent   += Vm_OnGenericVMEvent;
        }
コード例 #4
0
ファイル: UIInteractiveDGRP.cs プロジェクト: fourks/FreeSO
        public override void Update(UpdateState state)
        {
            base.Update(state);
            if (TempVM == null && GUID != 0)
            {
                var world = new ExternalWorld(GameFacade.GraphicsDevice);
                world.Initialize(GameFacade.Scenes);
                var context = new VMContext(world);

                TempVM = new VM(context, new VMServerDriver(new VMTSOGlobalLinkStub()), new VMNullHeadlineProvider());
                TempVM.Init();

                var blueprint = new Blueprint(32, 32);
                blueprint.Light = new RoomLighting[]
                {
                    new RoomLighting()
                    {
                        OutsideLight = 100
                    },
                    new RoomLighting()
                    {
                        OutsideLight = 100
                    },
                    new RoomLighting()
                    {
                        OutsideLight = 100
                    },
                };
                blueprint.OutsideColor = Color.White;
                blueprint.GenerateRoomLights();
                blueprint.RoomColors[2].A /= 2;
                world.State.AmbientLight.SetData(blueprint.RoomColors);

                world.InitBlueprint(blueprint);
                context.Blueprint    = blueprint;
                context.Architecture = new VMArchitecture(1, 1, blueprint, TempVM.Context);
            }

            if (GUID != oldGUID)
            {
                SetGUIDLocal(GUID, TempVM);
                state.SharedData["ExternalDraw"] = true;
            }

            if (ForceRedraw)
            {
                state.SharedData["ExternalDraw"] = true;
                ForceRedraw = false;
            }

            if (TempVM != null)
            {
                TempVM.Update();
            }
        }
コード例 #5
0
ファイル: Main.cs プロジェクト: kongyt/AtomScript
        public void Start()
        {
            Console.WriteLine("Atom Script.");

            scanner  = new Scanner.Scanner();
            parser   = new Parser.Parser();
            compiler = new Compiler.Compiler();

            vm = new VM();
            vm.Init();
        }
コード例 #6
0
        public void InitializeLot()
        {
            CleanupLastWorld();

            if (FSOEnvironment.Enable3D)
            {
                World = new FSO.LotView.RC.WorldRC(GameFacade.GraphicsDevice);
            }
            else
            {
                World = new FSO.LotView.World(GameFacade.GraphicsDevice);
            }

            World.Opacity = 1;
            GameFacade.Scenes.Add(World);

            var globalLink = new VMTSOGlobalLinkStub();

            Driver = new VMServerDriver(globalLink);

            vm = new VM(new VMContext(World), Driver, new UIHeadlineRendererProvider());
            vm.ListenBHAVChanges();
            vm.Init();

            LotControl = new UILotControl(vm, World);
            this.AddAt(0, LotControl);
            Frontend = new UISimitoneFrontend(this);
            this.Add(Frontend);

            var time    = DateTime.UtcNow;
            var tsoTime = TSOTime.FromUTC(time);

            vm.Context.Clock.Hours   = tsoTime.Item1;
            vm.Context.Clock.Minutes = tsoTime.Item2;
            if (m_ZoomLevel > 3)
            {
                World.Visible      = false;
                LotControl.Visible = false;
            }

            ZoomLevel = Math.Max(ZoomLevel, 4);

            if (IDEHook.IDE != null)
            {
                IDEHook.IDE.StartIDE(vm);
            }

            vm.OnFullRefresh += VMRefreshed;
            //vm.OnEODMessage += LotControl.EODs.OnEODMessage;
            vm.OnRequestLotSwitch += VMLotSwitch;
            vm.OnGenericVMEvent   += Vm_OnGenericVMEvent;
        }
コード例 #7
0
        public static FSOF RenderFSOF(byte[] fsov, GraphicsDevice gd)
        {
            var marshal = new VMMarshal();

            using (var mem = new MemoryStream(fsov))
            {
                marshal.Deserialize(new BinaryReader(mem));
            }

            var world = new FSO.LotView.RC.WorldRC(gd);

            world.Opacity = 1;
            Layer.Add(world);

            var globalLink = new VMTSOGlobalLinkStub();
            var driver     = new VMServerDriver(globalLink);

            var vm = new VM(new VMContext(world), driver, new VMNullHeadlineProvider());

            vm.Init();

            vm.Load(marshal);

            SetOutsideTime(gd, vm, world, 0.5f, false);
            world.State.PrepareLighting();
            var facade = new LotFacadeGenerator();

            facade.FLOOR_TILES        = 64;
            facade.GROUND_SUBDIV      = 5;
            facade.FLOOR_RES_PER_TILE = 2;

            SetAllLights(vm, world, 0.5f, 0);

            var result = facade.GetFSOF(gd, world, vm.Context.Blueprint, () => { SetAllLights(vm, world, 0.0f, 100); }, true);

            Layer.Remove(world);
            world.Dispose();
            vm.Context.Ambience.Kill();
            foreach (var ent in vm.Entities)
            { //stop object sounds
                var threads = ent.SoundThreads;
                for (int i = 0; i < threads.Count; i++)
                {
                    threads[i].Sound.RemoveOwner(ent.ObjectID);
                }
                threads.Clear();
            }

            return(result);
        }
コード例 #8
0
        private static void InitVM()
        {
            var world = new World(GameFacade.GraphicsDevice);

            world.Initialize(GameFacade.Scenes);
            var context = new VMContext(world);

            TempVM = new VM(context, new VMServerDriver(new VMTSOGlobalLinkStub()), new VMNullHeadlineProvider());
            TempVM.Init();

            var blueprint = new Blueprint(3, 3);

            world.InitBlueprint(blueprint);
            context.Blueprint    = blueprint;
            context.Architecture = new VMArchitecture(3, 3, blueprint, TempVM.Context);
            blueprint.Terrain    = new FSO.LotView.Components.TerrainComponent(new Rectangle(0, 0, 3, 3), blueprint);
            TempVM.Tick();
        }
コード例 #9
0
        public CVMInstance(int port)
        {
            VM.UseWorld = false;
            VMNetDriver driver;

            driver = new VMServerDriver(port);

            var vm = new VM(new VMContext(null), driver);

            vm.Init();

            vm.SendCommand(new VMBlueprintRestoreCmd
            {
                XMLData = File.ReadAllBytes(Path.Combine(Settings.Default.GamePath + "housedata/blueprints/" + Settings.Default.DebugLot))
            });
            vm.Context.Clock.Hours = 10;

            state = vm;
        }
コード例 #10
0
        public void LoadSurrounding(short houseID)
        {
            return;

            var       surrounding = new NBHm(new OBJ(File.OpenRead(@"C:\Users\Rhys\Desktop\fso 2018\nb4.obj")));
            NBHmHouse myH         = null;
            var       myHeight    = vm.Context.Blueprint.InterpAltitude(new Vector3(0, 0, 0));

            if (!surrounding.Houses.TryGetValue(houseID, out myH))
            {
                return;
            }
            foreach (var house in surrounding.Houses)
            {
                if (house.Key == houseID)
                {
                    continue;
                }
                var h = house.Value;
                //let's make their lot as a surrounding lot
                var gd       = World.State.Device;
                var subworld = World.MakeSubWorld(gd);
                subworld.Initialize(gd);
                var tempVM = new VM(new VMContext(subworld), new VMServerDriver(new VMTSOGlobalLinkStub()), new VMNullHeadlineProvider());
                tempVM.Init();
                BlueprintReset(Content.Get().Neighborhood.GetHousePath(house.Key), tempVM);
                subworld.State.Level = 5;
                var subHeight = tempVM.Context.Blueprint.InterpAltitude(new Vector3(0, 0, 0));
                tempVM.Context.Blueprint.BaseAlt = (int)Math.Round(((subHeight - myHeight) + myH.Position.Y - h.Position.Y) / tempVM.Context.Blueprint.TerrainFactor);
                subworld.GlobalPosition          = new Vector2((myH.Position.X - h.Position.X), (myH.Position.Z - h.Position.Z));

                foreach (var obj in tempVM.Entities)
                {
                    obj.Position = obj.Position;
                }

                vm.Context.Blueprint.SubWorlds.Add(subworld);
            }
            vm.Context.World.InitSubWorlds();
        }
コード例 #11
0
        public FSOF RenderFSOF(byte[] fsov)
        {
            var marshal = new VMMarshal();

            using (var mem = new MemoryStream(fsov)) {
                marshal.Deserialize(new BinaryReader(mem));
            }

            var world = new FSO.LotView.RC.WorldRC(GameFacade.GraphicsDevice);

            world.Opacity = 1;
            GameFacade.Scenes.Add(world);

            var globalLink = new VMTSOGlobalLinkStub();
            var driver     = new VMServerDriver(globalLink);

            var vm = new VM(new VMContext(world), driver, new UIHeadlineRendererProvider());

            vm.Init();

            vm.Load(marshal);

            SetOutsideTime(GameFacade.GraphicsDevice, vm, world, 0.5f, false);
            world.State.PrepareLighting();
            var facade = new LotFacadeGenerator();

            facade.FLOOR_TILES        = 64;
            facade.GROUND_SUBDIV      = 5;
            facade.FLOOR_RES_PER_TILE = 2;

            SetAllLights(vm, world, 0.5f, 0);

            var result = facade.GetFSOF(GameFacade.GraphicsDevice, world, vm.Context.Blueprint, () => { SetAllLights(vm, world, 0.0f, 100); }, true);

            GameFacade.Scenes.Remove(world);
            world.Dispose();

            return(result);
        }
コード例 #12
0
        public void InitializeLot()
        {
            CleanupLastWorld();
            World = new FSO.LotView.World(GameFacade.GraphicsDevice);

            World.Opacity = 1;
            GameFacade.Scenes.Add(World);

            var globalLink = new VMTS1GlobalLinkStub();

            Driver = new VMServerDriver(globalLink);

            vm = new VM(new VMContext(World), Driver, new UIHeadlineRendererProvider());
            vm.ListenBHAVChanges();
            vm.Init();

            LotControl = new UILotControl(vm, World);
            this.AddAt(0, LotControl);

            if (m_ZoomLevel > 3)
            {
                World.Visible      = false;
                LotControl.Visible = false;
            }

            ZoomLevel = Math.Max(ZoomLevel, 4);

            if (IDEHook.IDE != null)
            {
                IDEHook.IDE.StartIDE(vm);
            }

            vm.OnFullRefresh += VMRefreshed;
            //vm.OnEODMessage += LotControl.EODs.OnEODMessage;
            vm.OnRequestLotSwitch += VMLotSwitch;
            vm.OnGenericVMEvent   += Vm_OnGenericVMEvent;
        }
コード例 #13
0
        public override void Update(UpdateState state)
        {
            base.Update(state);
            if (TempVM == null && GUID != 0)
            {
                var world = new ExternalWorld(GameFacade.GraphicsDevice);
                world.Initialize(GameFacade.Scenes);
                var context = new VMContext(world);

                TempVM = new VM(context, new VMServerDriver(37565), new VMNullHeadlineProvider());
                TempVM.Init();

                var blueprint = new Blueprint(1, 1);
                world.InitBlueprint(blueprint);
                context.Blueprint    = blueprint;
                context.Architecture = new VMArchitecture(1, 1, blueprint, TempVM.Context);
            }

            if (GUID != oldGUID)
            {
                SetGUIDLocal(GUID);
                state.SharedData["ExternalDraw"] = true;
            }
        }
コード例 #14
0
        public Orders()
        {
            InitializeComponent();

            VM.Init();
        }
コード例 #15
0
        public static void RestoreSurroundings(VM vm, byte[][] hollowAdj)
        {
            var myArch   = vm.Context.Architecture;
            var terrain  = vm.TSOState.Terrain;
            var size     = myArch.Width;
            var lotsMode = WorldConfig.Current.SurroundingLots;

            foreach (var world in vm.Context.Blueprint.SubWorlds)
            {
                world.Dispose();
            }
            vm.Context.Blueprint.SubWorlds.Clear();
            if (lotsMode == 0)
            {
                return;
            }
            for (int y = 0; y < 3; y++)
            {
                for (int x = 0; x < 3; x++)
                {
                    if (x == 1 & y == 1)
                    {
                        continue;                  //that's us...
                    }
                    var gd       = vm.Context.World.State.Device;
                    var subworld = new SubWorldComponent(gd);
                    subworld.Initialize(gd);
                    var tempVM = new VM(new VMContext(subworld), new VMServerDriver(new VMTSOGlobalLinkStub()), new VMNullHeadlineProvider());
                    tempVM.Init();

                    var state = (hollowAdj == null)? null : hollowAdj[y * 3 + x];
                    if (lotsMode == 1)
                    {
                        state = null;
                    }

                    VMHollowMarshal hollow = null;
                    if (state != null)
                    {
                        try
                        {
                            hollow = new VMHollowMarshal();
                            using (var reader = new BinaryReader(new MemoryStream(state))) {
                                hollow.Deserialize(reader);
                            }
                            tempVM.HollowLoad(hollow);
                            RestoreTerrain(tempVM, terrain.BlendN[x, y], terrain.Roads[x, y]);
                            tempVM.Tick();
                        } catch (Exception)
                        {
                            hollow = null;
                        }
                    }

                    if (hollow == null)
                    {
                        var blueprint = new Blueprint(size, size);
                        tempVM.Context.Blueprint = blueprint;
                        subworld.InitBlueprint(blueprint);
                        tempVM.Context.Architecture = new VMArchitecture(size, size, blueprint, tempVM.Context);

                        tempVM.Context.Architecture.RegenRoomMap();
                        tempVM.Context.RegeneratePortalInfo();

                        var terrainC = new TerrainComponent(new Rectangle(1, 1, size - 2, size - 2), blueprint);
                        terrainC.Initialize(subworld.State.Device, subworld.State);
                        blueprint.Terrain = terrainC;

                        RestoreTerrain(tempVM, terrain.BlendN[x, y], terrain.Roads[x, y]);
                        PopulateBlankTerrain(tempVM);

                        tempVM.Tick();
                    }

                    subworld.State.Level    = 5;
                    subworld.GlobalPosition = new Vector2((1 - y) * (size - 2), (x - 1) * (size - 2));

                    vm.Context.Blueprint.SubWorlds.Add(subworld);
                }
            }
        }
コード例 #16
0
        public static void RestoreSurroundings(VM vm, byte[][] hollowAdj)
        {
            var myArch   = vm.Context.Architecture;
            var terrain  = vm.TSOState.Terrain;
            var size     = myArch.Width;
            var lotsMode = WorldConfig.Current.SurroundingLots;

            foreach (var world in vm.Context.Blueprint.SubWorlds)
            {
                world.Dispose();
            }
            vm.Context.Blueprint.SubWorlds.Clear();

            var baseHeight = GetBaseLevel(vm, terrain, 1, 1);

            //vm.Context.Blueprint.BaseAlt = 0;// 128;
            //vm.Context.World.State.BaseHeight = 0;// (128 * 3) / 16f;

            if (lotsMode == 0)
            {
                return;
            }
            for (int y = 0; y < 3; y++)
            {
                for (int x = 0; x < 3; x++)
                {
                    if (x == 1 & y == 1)
                    {
                        continue;                  //that's us...
                    }
                    var gd       = vm.Context.World.State.Device;
                    var subworld = vm.Context.World.MakeSubWorld(gd);
                    subworld.Initialize(gd);
                    var tempVM = new VM(new VMContext(subworld), new VMServerDriver(new VMTSOGlobalLinkStub()), new VMNullHeadlineProvider());
                    tempVM.Init();

                    var state = (hollowAdj == null)? null : hollowAdj[y * 3 + x];
                    if (lotsMode == 1)
                    {
                        state = null;
                    }

                    float           height = 0;
                    VMHollowMarshal hollow = null;
                    if (state != null)
                    {
                        try
                        {
                            hollow = new VMHollowMarshal();
                            using (var reader = new BinaryReader(new MemoryStream(state))) {
                                hollow.Deserialize(reader);
                            }
                            tempVM.HollowLoad(hollow);
                            RestoreTerrain(tempVM, terrain.BlendN[x, y], terrain.Roads[x, y]);
                            if (hollow.Version < 19)
                            {
                                height = RestoreHeight(tempVM, terrain, x, y);
                            }
                            else
                            {
                                height = GetBaseLevel(tempVM, terrain, x, y);
                            }
                            tempVM.Context.Blueprint.BaseAlt = (int)((baseHeight - height));
                            foreach (var obj in tempVM.Entities)
                            {
                                obj.Position = obj.Position;
                            }

                            tempVM.Tick();
                            subworld.CalculateFloorsUsed();
                        } catch (Exception)
                        {
                            hollow = null;
                        }
                    }

                    if (hollow == null)
                    {
                        var blueprint = new Blueprint(size, size);
                        tempVM.Context.Blueprint = blueprint;
                        subworld.InitBlueprint(blueprint);
                        tempVM.Context.Architecture = new VMArchitecture(size, size, blueprint, tempVM.Context);

                        tempVM.Context.Architecture.EmptyRoomMap();
                        tempVM.Context.RegeneratePortalInfo();

                        var terrainC = new TerrainComponent(new Rectangle(0, 0, size, size), blueprint);
                        terrainC.Initialize(subworld.State.Device, subworld.State);
                        blueprint.Terrain = terrainC;

                        tempVM.Context.Architecture.Terrain.LowQualityGrassState = true;
                        RestoreTerrain(tempVM, terrain.BlendN[x, y], terrain.Roads[x, y]);
                        height = RestoreHeight(tempVM, terrain, x, y);
                        tempVM.Context.Blueprint.BaseAlt = (int)((baseHeight - height));

                        PopulateBlankTerrain(tempVM);
                        tempVM.Context.Architecture.ClearDirty();
                        tempVM.Context.Architecture.RegenRoomMap();
                        tempVM.Context.RegeneratePortalInfo();
                        tempVM.Context.RefreshAllLighting();
                        tempVM.Tick();
                    }

                    subworld.State.Level = 5;

                    subworld.GlobalPosition = new Vector2((1 - y) * (size - 2), (x - 1) * (size - 2));

                    vm.Context.Blueprint.SubWorlds.Add(subworld);
                }
            }
            vm.Context.World.InitSubWorlds();
        }
コード例 #17
0
        public void InitializeLot(string lotName, bool external)
        {
            if (lotName == "")
            {
                return;
            }
            var recording = lotName.ToLowerInvariant().EndsWith(".fsor");

            CleanupLastWorld();

            Content.Content.Get().Upgrades.LoadJSONTuning();

            if (FSOEnvironment.Enable3D)
            {
                var rc = new LotView.RC.WorldRC(GameFacade.GraphicsDevice);
                World = rc;
            }
            else
            {
                World = new World(GameFacade.GraphicsDevice);
            }
            World.Opacity = 1;
            GameFacade.Scenes.Add(World);

            var settings = GlobalSettings.Default;
            var myState  = new VMNetAvatarPersistState()
            {
                Name         = settings.LastUser,
                DefaultSuits = new VMAvatarDefaultSuits(settings.DebugGender),
                BodyOutfit   = settings.DebugBody,
                HeadOutfit   = settings.DebugHead,
                PersistID    = (uint)(new Random()).Next(),
                SkinTone     = (byte)settings.DebugSkin,
                Gender       = (short)(settings.DebugGender ? 0 : 1),
                Permissions  = SimAntics.Model.TSOPlatform.VMTSOAvatarPermissions.Admin,
                //CustomGUID = 0x396CD3D1,
                Budget = 1000000,
            };

            if (recording)
            {
                var stream = new FileStream(lotName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                var rd     = new VMFSORDriver(stream);
                Driver = rd;
            }
            else if (external)
            {
                var cd = new VMClientDriver(ClientStateChange);
                SandCli             = new FSOSandboxClient();
                cd.OnClientCommand += (msg) => { SandCli.Write(new VMNetMessage(VMNetMessageType.Command, msg)); };
                cd.OnShutdown      += (reason) => SandCli.Disconnect();
                SandCli.OnMessage  += cd.ServerMessage;
                SandCli.Connect(lotName);
                Driver = cd;

                var dat = new MemoryStream();
                var str = new BinaryWriter(dat);
                myState.SerializeInto(str);
                var ava = new VMNetMessage(VMNetMessageType.AvatarData, dat.ToArray());
                dat.Close();
                SandCli.OnConnectComplete += () =>
                {
                    SandCli.Write(ava);
                };
            }
            else
            {
                var globalLink = new VMTSOGlobalLinkStub();
                globalLink.Database = new SimAntics.Engine.TSOGlobalLink.VMTSOStandaloneDatabase();
                var sd = new VMServerDriver(globalLink);
                SandServer = new FSOSandboxServer();

                Driver                   = sd;
                sd.OnDropClient         += SandServer.ForceDisconnect;
                sd.OnTickBroadcast      += SandServer.Broadcast;
                sd.OnDirectMessage      += SandServer.SendMessage;
                SandServer.OnConnect    += sd.ConnectClient;
                SandServer.OnDisconnect += sd.DisconnectClient;
                SandServer.OnMessage    += sd.HandleMessage;

                SandServer.Start((ushort)37564);
            }

            //Driver.OnClientCommand += VMSendCommand;
            //Driver.OnShutdown += VMShutdown;

            vm = new VM(new VMContext(World), Driver, new UIHeadlineRendererProvider());
            vm.ListenBHAVChanges();
            vm.Init();

            LotControl = new UILotControl(vm, World);
            this.AddAt(0, LotControl);

            var time    = DateTime.UtcNow;
            var tsoTime = TSOTime.FromUTC(time);

            vm.Context.Clock.Hours   = tsoTime.Item1;
            vm.Context.Clock.Minutes = tsoTime.Item2;
            if (m_ZoomLevel > 3)
            {
                World.Visible      = false;
                LotControl.Visible = false;
            }

            if (IDEHook.IDE != null)
            {
                IDEHook.IDE.StartIDE(vm);
            }

            vm.OnFullRefresh      += VMRefreshed;
            vm.OnChatEvent        += Vm_OnChatEvent;
            vm.OnEODMessage       += LotControl.EODs.OnEODMessage;
            vm.OnRequestLotSwitch += VMLotSwitch;
            vm.OnGenericVMEvent   += Vm_OnGenericVMEvent;

            if (!external && !recording)
            {
                if (!Downtown && ActiveFamily != null)
                {
                    ActiveFamily.SelectWholeFamily();
                    vm.TS1State.ActivateFamily(vm, ActiveFamily);
                }
                BlueprintReset(lotName);

                var experimentalTuning = new Common.Model.DynamicTuning(new List <Common.Model.DynTuningEntry> {
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 15, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 5, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 6, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 7, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 8, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "overfill", tuning_table = 255, tuning_index = 9, value = 200
                    },
                    new Common.Model.DynTuningEntry()
                    {
                        tuning_type = "feature", tuning_table = 0, tuning_index = 0, value = 1
                    },                                                                                                            //ts1/tso engine animation timings (1.2x faster)
                });
                vm.ForwardCommand(new VMNetTuningCmd {
                    Tuning = experimentalTuning
                });

                vm.TSOState.PropertyCategory = 255; //11 is community
                vm.TSOState.ActivateValidator(vm);
                vm.Context.Clock.Hours = 0;
                vm.TSOState.Size      &= unchecked ((int)0xFFFF0000);
                vm.TSOState.Size      |= (10) | (3 << 8);
                vm.Context.UpdateTSOBuildableArea();

                if (vm.GetGlobalValue(11) > -1)
                {
                    for (int y = 0; y < 3; y++)
                    {
                        for (int x = 0; x < 3; x++)
                        {
                            vm.TSOState.Terrain.Roads[x, y] = 0xF; //crossroads everywhere
                        }
                    }
                    VMLotTerrainRestoreTools.RestoreTerrain(vm);
                }

                var myClient = new VMNetClient
                {
                    PersistID   = myState.PersistID,
                    RemoteIP    = "local",
                    AvatarState = myState
                };

                var server = (VMServerDriver)Driver;
                server.ConnectClient(myClient);

                GameFacade.Cursor.SetCursor(CursorType.Normal);
                ZoomLevel = 1;
            }
            vm.MyUID  = myState.PersistID;
            ZoomLevel = 1;
        }
コード例 #18
0
        public static void SaveOBJ(string destPath, STR locations)
        {
            var exportedFlr = new HashSet <ushort>();
            var gd          = GameFacade.GraphicsDevice;
            var mtlBuilder  = new StringBuilder();

            Directory.CreateDirectory(destPath);

            //var mtlMem = new MemoryStream();
            //var mtlIO = new StreamWriter(mtlMem);
            var mtlIO = new StreamWriter(new FileStream(Path.Combine(destPath, "neighbourhood.mtl"), FileMode.Create, FileAccess.Write, FileShare.None));

            var path     = Path.Combine(destPath, "neighbourhood.obj");
            var filename = Path.GetFileNameWithoutExtension(path);

            using (var io = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None)))
            {
                io.WriteLine("# Generated by the Simitone Neighbourhood Exporter.");
                io.WriteLine("# The purpose is to allow users to mesh neighbourhood surroundings using");
                io.WriteLine("# the projected physical positions and terrain profiles of lots as a starting point.");

                io.WriteLine("mtllib neighbourhood.mtl");
                io.WriteLine("s 1");

                int indCount = 1;
                for (int i = 0; i < locations.Length; i++)
                {
                    var loc   = locations.GetString(i).Split(',');
                    var num   = int.Parse(loc[0].TrimStart());
                    var pos2d = new Vector2(int.Parse(loc[1].TrimStart()), int.Parse(loc[2].TrimStart()));

                    var house = Content.Get().Neighborhood.GetHouse(num);

                    World world = new FSO.LotView.World(GameFacade.GraphicsDevice);

                    world.Opacity = 1;
                    GameFacade.Scenes.Add(world);

                    var globalLink = new VMTS1GlobalLinkStub();
                    var driver     = new VMServerDriver(globalLink);

                    var vm = new VM(new VMContext(world), driver, new UIHeadlineRendererProvider());
                    vm.ListenBHAVChanges();
                    vm.Init();

                    vm.SetGlobalValue(11, (short)num);

                    var activator = new VMTS1Activator(vm, vm.Context.World, (short)num);
                    var blueprint = activator.LoadFromIff(house);

                    var floorVerts = blueprint.Terrain.GetVertices(gd);
                    blueprint.FloorGeom.FullReset(gd, false);
                    var groundfloor = blueprint.FloorGeom.Floors[0];

                    //we need to calculate the
                    var minHeight = int.MaxValue;
                    var heights   = vm.Context.Architecture.Terrain.Heights;
                    for (int j = 0; j < heights.Length; j++)
                    {
                        if ((j % blueprint.Width) == 0 || (j % blueprint.Width) == blueprint.Width - 1 || j < blueprint.Width || j >= (blueprint.Height - 1) * blueprint.Width)
                        {
                            continue;
                        }
                        var h = heights[j];
                        if (h != 0 && h < minHeight)
                        {
                            minHeight = h;
                        }
                    }
                    if (minHeight == int.MaxValue)
                    {
                        minHeight = 0;
                    }
                    var scale = (locations.Length > 30 ? 1f : 2f) * 1.4142135623730950488016887242097f;
                    var baseV = new Vector3(pos2d.X + pos2d.Y * 2, 0, pos2d.Y * 2 - pos2d.X) / scale;
                    baseV.Y -= (minHeight * 3 / 160f) * 3;

                    var ctr = blueprint.GetFineBounds().Location.ToVector2() + blueprint.GetFineBounds().Size.ToVector2() / 2;

                    var voff = baseV + new Vector3(ctr.X, 0, ctr.Y) * 3f / -1;

                    voff.X = (int)(voff.X / 3) * 3;
                    voff.Z = (int)(voff.Z / 3) * 3;

                    SetOutsideTime(GameFacade.GraphicsDevice, vm, world, 0.5f, false);
                    world.State.PrepareLighting();
                    var facade = new LotFacadeGenerator();
                    facade.FLOOR_TILES        = blueprint.Width;
                    facade.GROUND_SUBDIV      = blueprint.Width;
                    facade.FLOOR_RES_PER_TILE = 4;
                    facade.LotName            = "p" + num.ToString();
                    facade.Generate(GameFacade.GraphicsDevice, world, blueprint);
                    facade.AppendOBJ(io, filename, indCount, voff / 3);
                    facade.AppendMTL(mtlIO, Path.GetDirectoryName(path));
                    indCount = facade.LastIndex;

                    /*
                     * foreach (var group in groundfloor.GroupForTileType)
                     * {
                     *  if (!exportedFlr.Contains(group.Key) && group.Key != 0 && group.Key < 65000)
                     *  {
                     *      //get and export this floor's texture. add it as a material as well.
                     *      var floor = Content.Get().WorldFloors.Get(group.Key).Near.Frames[0].GetTexture(gd);
                     *      using (var flrStream = new FileStream(Path.Combine(destPath, "flr_" + group.Key + ".png"), FileMode.Create, FileAccess.Write, FileShare.None))
                     *          floor.SaveAsPng(flrStream, floor.Width, floor.Height);
                     *
                     *      //add as material
                     *      GenerateMTL("flr_" + group.Key, mtlBuilder);
                     *  }
                     *  //write out verts and indices.
                     *
                     *
                     *  var indices = group.Value.BuildIndexData();
                     *  var done = new Dictionary<int, int>(); //index remap
                     *
                     *  if (group.Key == 0)
                     *  {
                     *      //grass... export as grass colour
                     *      io.WriteLine("usemtl " + "grass");
                     *      io.WriteLine("o " + "lot_" + num + "_grass");
                     *
                     *  }
                     *  else
                     *  {
                     *      //export with floor textured material
                     *      io.WriteLine("usemtl " + "flr_" + group.Key);
                     *      io.WriteLine("o " + "lot_" + num + "_" + group.Key);
                     *  }
                     *
                     *  var indexStr = new StringBuilder();
                     *  indexStr.Append("f ");
                     *
                     *  for (int j = 0; j < indices.Length; j++)
                     *  {
                     *      var index = indices[j];
                     *      int remapped = index;
                     *      if (!done.TryGetValue(index, out remapped))
                     *      {
                     *          remapped = indCount;
                     *          done.Add(index, indCount++);
                     *          //append a vertex
                     *          var vert = floorVerts[index];
                     *          vert.Position += voff;
                     *          io.Write("v " + vert.Position.X.ToString(CultureInfo.InvariantCulture) + " " + vert.Position.Y.ToString(CultureInfo.InvariantCulture) + " " + vert.Position.Z.ToString(CultureInfo.InvariantCulture));
                     *          io.WriteLine((group.Key == 0) ? " " + vert.Color.X.ToString(CultureInfo.InvariantCulture) + " " + vert.Color.Y.ToString(CultureInfo.InvariantCulture) + " " + vert.Color.Z.ToString(CultureInfo.InvariantCulture) : "");
                     *          io.WriteLine("vt " + vert.GrassInfo.Y.ToString(CultureInfo.InvariantCulture) + " " + (1 - vert.GrassInfo.Z).ToString(CultureInfo.InvariantCulture));
                     *      }
                     *      indexStr.Append(remapped + "/" + remapped);
                     *      if (j % 3 == 2)
                     *      {
                     *          indexStr.AppendLine();
                     *          if (j != indices.Length - 1) indexStr.Append("f ");
                     *      }
                     *      else indexStr.Append(" ");
                     *  }
                     *
                     *  io.WriteLine(indexStr);
                     * }
                     */

                    GameFacade.Scenes.Remove(world);
                    world.Dispose();
                }
            }

            mtlIO.Close();
        }
コード例 #19
0
        public void InitializeLot()
        {
            CleanupLastWorld();

            if (FSOEnvironment.Enable3D)
            {
                var rc = new FSO.LotView.RC.WorldRC(GameFacade.GraphicsDevice);
                World = rc;
            }
            else
            {
                World = new FSO.LotView.World(GameFacade.GraphicsDevice);
            }

            World.Opacity = 1;
            GameFacade.Scenes.Add(World);

            var globalLink = new VMTS1GlobalLinkStub();

            Driver = new VMServerDriver(globalLink);

            vm = new VM(new VMContext(World), Driver, new UIHeadlineRendererProvider());
            vm.ListenBHAVChanges();
            vm.Init();

            using (var file = new BinaryReader(File.OpenRead(Path.Combine(FSOEnvironment.ContentDir, "cas.fsov"))))
            {
                var marshal = new FSO.SimAntics.Marshals.VMMarshal();
                marshal.Deserialize(file);
                marshal.PlatformState = new VMTS1LotState();
                vm.Load(marshal);
                vm.Reset();
            }
            vm.Tick();

            vm.Context.Clock.Hours = 12;
            vm.MyUID = uint.MaxValue;
            var settings = GlobalSettings.Default;
            var myClient = new VMNetClient
            {
                PersistID   = uint.MaxValue,
                RemoteIP    = "local",
                AvatarState = new VMNetAvatarPersistState()
                {
                    Name         = settings.LastUser ?? "",
                    DefaultSuits = new VMAvatarDefaultSuits(settings.DebugGender),
                    BodyOutfit   = settings.DebugBody,
                    HeadOutfit   = settings.DebugHead,
                    PersistID    = uint.MaxValue,
                    SkinTone     = (byte)settings.DebugSkin,
                    Gender       = (short)(settings.DebugGender ? 1 : 0),
                    Permissions  = FSO.SimAntics.Model.TSOPlatform.VMTSOAvatarPermissions.Admin,
                    Budget       = 1000000
                }
            };

            var server = (VMServerDriver)Driver;

            server.ConnectClient(myClient);

            HeadAvatars = new VMAvatar[18];
            for (int i = 0; i < 18; i++)
            {
                HeadAvatars[i] = (VMAvatar)vm.Context.CreateObjectInstance(0x7FD96B54, LotTilePos.OUT_OF_WORLD, Direction.NORTH, true).BaseObject;
            }

            BodyAvatars = new VMAvatar[18];
            for (int i = 0; i < 18; i++)
            {
                BodyAvatars[i] = (VMAvatar)vm.Context.CreateObjectInstance(0x7FD96B54, LotTilePos.OUT_OF_WORLD, Direction.NORTH, true).BaseObject;
            }

            PopulateSimType("ma");
        }
コード例 #20
0
ファイル: Globals.cs プロジェクト: pkelm1/Choreo
 private static void Plc_SymbolsUpdated(object sender, EventArgs e) => VM.Init();
コード例 #21
0
ファイル: VMInstance.cs プロジェクト: simscolony/FreeSims
        public void ResetVM()
        {
            VMNetDriver driver;

            driver = new VMServerDriver(Port, NetClosed);

            var vm = new VM(new VMContext(null), new VMNullHeadlineProvider());

            state = vm;
            vm.Init();
            vm.VM_SetDriver(driver);
            vm.OnChatEvent += Vm_OnChatEvent;

            Console.WriteLine("Select the lot type");
            Console.WriteLine("1-Empty");
            Console.WriteLine("2-Blueprint");
            Console.WriteLine("3-House");

            string path = "";
            int    lot  = Convert.ToInt32(Console.ReadLine());

            if (lot == 1)
            {
                if (Settings.Default.DebugLot != String.Empty)
                {
                    path = AppDomain.CurrentDomain.BaseDirectory + "Content/Houses/" + Settings.Default.DebugLot;
                }
                else
                {
                    path = AppDomain.CurrentDomain.BaseDirectory + "Content/Houses/empty_lot.xml";
                }
            }
            else if (lot == 2)
            {
                Console.WriteLine("Specify lot name");
                path = AppDomain.CurrentDomain.BaseDirectory + "Content/Houses/" + Console.ReadLine() + ".xml";
            }
            else if (lot == 3)
            {
                Console.WriteLine("Specify house name");
                path = AppDomain.CurrentDomain.BaseDirectory + "Content/Houses/" + Console.ReadLine() + ".iff";
                TS1  = true;
            }


            XmlHouseData lotInfo;
            IffFile      HouseInfo = null;
            string       filename  = Path.GetFileName(path);

            if (!TS1)
            {
                try
                {
                    //try to load from FSOV first.
                    LoadState(vm, "Content/LocalHouse/" + filename.Substring(0, filename.Length - 4) + ".fsov");
                }
                catch (Exception)
                {
                    try
                    {
                        Console.WriteLine("Failed FSOV load... Trying Backup");
                        LoadState(vm, "Content/LocalHouse/" + filename.Substring(0, filename.Length - 4) + "_backup.fsov");
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("CRITICAL::: Failed FSOV load... Trying Blueprint (first run or something went wrong)");
                        short jobLevel = -1;

                        //quick hack to find the job level from the chosen blueprint
                        //the final server will know this from the fact that it wants to create a job lot in the first place...

                        try
                        {
                            if (filename.StartsWith("nightclub") || filename.StartsWith("restaurant") || filename.StartsWith("robotfactory"))
                            {
                                jobLevel = Convert.ToInt16(filename.Substring(filename.Length - 9, 2));
                            }
                        }
                        catch (Exception) { }

                        //vm.SendCommand(new VMBlueprintRestoreCmd
                        //{
                        // JobLevel = jobLevel,
                        // XMLData = File.ReadAllBytes(path)
                        //});

                        using (var stream = new MemoryStream(File.ReadAllBytes(path)))
                        {
                            lotInfo = XmlHouseData.Parse(stream);
                        }

                        VMWorldActivator activator = new VMWorldActivator(vm, vm.Context.World);

                        vm.Activator = activator;

                        var blueprint = activator.LoadFromXML(lotInfo);

                        if (VM.UseWorld)
                        {
                            vm.Context.World.InitBlueprint(blueprint);
                            vm.Context.Blueprint = blueprint;
                        }


                        vm.Context.Clock.Hours = 10;

                        vm.MyUID = uint.MaxValue - 1;
                    }
                }
            }
            else
            {
                if (File.Exists(path))
                {
                    HouseInfo = new IffFile(path);
                }

                VMWorldActivator activator = new VMWorldActivator(vm, vm.Context.World);

                vm.Activator = activator;

                var blueprint = activator.LoadFromIff(HouseInfo);

                if (VM.UseWorld)
                {
                    vm.Context.World.InitBlueprint(blueprint);
                    vm.Context.Blueprint = blueprint;
                }


                vm.Context.Clock.Hours = 10;

                vm.MyUID = uint.MaxValue - 1;
            }



            Console.WriteLine("Select the server type");
            Console.WriteLine("1-Host");
            Console.WriteLine("2-Dedicated");

            int host = Convert.ToInt32(Console.ReadLine());

            if (host == 1)
            {
                vm.SendCommand(new VMNetSimJoinCmd
                {
                    ActorUID = uint.MaxValue - 1,
                    Name     = "server"
                });
            }
            else if (host == 2)
            {
                Dedicated = true;
            }
        }
コード例 #22
0
ファイル: SandboxGameScreen.cs プロジェクト: fourks/FreeSO
        public void InitializeLot(string lotName, bool external)
        {
            if (lotName == "")
            {
                return;
            }
            CleanupLastWorld();

            World         = new LotView.World(GameFacade.GraphicsDevice);
            World.Opacity = 1;
            GameFacade.Scenes.Add(World);

            if (external)
            {
                //external not yet implemented
                Driver = new VMClientDriver(ClientStateChange);
            }
            else
            {
                var globalLink = new VMTSOGlobalLinkStub();
                Driver = new VMServerDriver(globalLink);
            }

            //Driver.OnClientCommand += VMSendCommand;
            //Driver.OnShutdown += VMShutdown;

            vm = new VM(new VMContext(World), Driver, new UIHeadlineRendererProvider());
            vm.ListenBHAVChanges();
            vm.Init();

            LotControl = new UILotControl(vm, World);
            this.AddAt(0, LotControl);

            var time    = DateTime.UtcNow;
            var tsoTime = TSOTime.FromUTC(time);

            vm.Context.Clock.Hours   = tsoTime.Item1;
            vm.Context.Clock.Minutes = tsoTime.Item2;
            if (m_ZoomLevel > 3)
            {
                World.Visible      = false;
                LotControl.Visible = false;
            }

            ZoomLevel = Math.Max(ZoomLevel, 4);

            if (IDEHook.IDE != null)
            {
                IDEHook.IDE.StartIDE(vm);
            }

            vm.OnFullRefresh      += VMRefreshed;
            vm.OnChatEvent        += Vm_OnChatEvent;
            vm.OnEODMessage       += LotControl.EODs.OnEODMessage;
            vm.OnRequestLotSwitch += VMLotSwitch;
            vm.OnGenericVMEvent   += Vm_OnGenericVMEvent;

            if (!external)
            {
                vm.ActivateFamily(ActiveFamily);
                BlueprintReset(lotName);

                vm.Context.Clock.Hours = 0;
                vm.TSOState.Size       = (10) | (3 << 8);
                vm.Context.UpdateTSOBuildableArea();
                vm.MyUID = 1;
                var settings = GlobalSettings.Default;
                var myClient = new VMNetClient
                {
                    PersistID   = 1,
                    RemoteIP    = "local",
                    AvatarState = new VMNetAvatarPersistState()
                    {
                        Name         = settings.LastUser,
                        DefaultSuits = new VMAvatarDefaultSuits(settings.DebugGender),
                        BodyOutfit   = settings.DebugBody,
                        HeadOutfit   = settings.DebugHead,
                        PersistID    = 1,
                        SkinTone     = (byte)settings.DebugSkin,
                        Gender       = (short)(settings.DebugGender ? 1 : 0),
                        Permissions  = SimAntics.Model.TSOPlatform.VMTSOAvatarPermissions.Admin,
                        Budget       = 100000
                    }
                };

                var server = (VMServerDriver)Driver;
                server.ConnectClient(myClient);

                GameFacade.Cursor.SetCursor(CursorType.Normal);
                ZoomLevel = 1;
            }
        }
コード例 #23
0
        bool AddVMCode(uint FirstByte, byte[] Code, int CodeSize)
        {
            VMCodeInp.InitBitInput();
            //x memcpy(VMCodeInp.InBuf,Code,Min(BitInput.MAX_SIZE,CodeSize));
            Array.Copy(Code, 0, VMCodeInp.InBuf, 0, Math.Min(BitInput.MAX_SIZE, CodeSize));
            VM.Init();

            uint FiltPos;

            if ((FirstByte & 0x80) != 0)
            {
                FiltPos = RarVM.ReadData(VMCodeInp);
                if (FiltPos == 0)
                {
                    InitFilters30(false);
                }
                else
                {
                    FiltPos--;
                }
            }
            else
            {
                FiltPos = (uint)this.LastFilter; // Use the same filter as last time.
            }
            if (FiltPos > Filters30.Count || FiltPos > OldFilterLengths.Count)
            {
                return(false);
            }
            LastFilter = (int)FiltPos;
            bool NewFilter = (FiltPos == Filters30.Count);

            UnpackFilter30 StackFilter = new UnpackFilter30(); // New filter for PrgStack.

            UnpackFilter30 Filter;

            if (NewFilter) // New filter code, never used before since VM reset.
            {
                if (FiltPos > MAX3_UNPACK_FILTERS)
                {
                    // Too many different filters, corrupt archive.
                    //delete StackFilter;
                    return(false);
                }

                Filters30.Add(1);
                Filters30[Filters30.Count - 1] = Filter = new UnpackFilter30();
                StackFilter.ParentFilter       = (uint)(Filters30.Count - 1);

                // Reserve one item to store the data block length of our new filter
                // entry. We'll set it to real block length below, after reading it.
                // But we need to initialize it now, because when processing corrupt
                // data, we can access this item even before we set it to real value.
                OldFilterLengths.Add(0);
            }
            else // Filter was used in the past.
            {
                Filter = Filters30[(int)FiltPos];
                StackFilter.ParentFilter = FiltPos;
            }

            int EmptyCount = 0;

            for (int I = 0; I < PrgStack.Count; I++)
            {
                PrgStack[I - EmptyCount] = PrgStack[I];
                if (PrgStack[I] == null)
                {
                    EmptyCount++;
                }
                if (EmptyCount > 0)
                {
                    PrgStack[I] = null;
                }
            }
            if (EmptyCount == 0)
            {
                if (PrgStack.Count > MAX3_UNPACK_FILTERS)
                {
                    //delete StackFilter;
                    return(false);
                }
                PrgStack.Add(1);
                EmptyCount = 1;
            }
            size_t StackPos = (uint)(this.PrgStack.Count - EmptyCount);

            PrgStack[(int)StackPos] = StackFilter;

            uint BlockStart = RarVM.ReadData(VMCodeInp);

            if ((FirstByte & 0x40) != 0)
            {
                BlockStart += 258;
            }
            StackFilter.BlockStart = (uint)((BlockStart + UnpPtr) & MaxWinMask);
            if ((FirstByte & 0x20) != 0)
            {
                StackFilter.BlockLength = RarVM.ReadData(VMCodeInp);

                // Store the last data block length for current filter.
                OldFilterLengths[(int)FiltPos] = (int)StackFilter.BlockLength;
            }
            else
            {
                // Set the data block size to same value as the previous block size
                // for same filter. It is possible for corrupt data to access a new
                // and not filled yet item of OldFilterLengths array here. This is why
                // we set new OldFilterLengths items to zero above.
                StackFilter.BlockLength = FiltPos < OldFilterLengths.Count ? OldFilterLengths[(int)FiltPos]:0;
            }

            StackFilter.NextWindow = WrPtr != UnpPtr && ((WrPtr - UnpPtr) & MaxWinMask) <= BlockStart;

//  DebugLog("\nNextWindow: UnpPtr=%08x WrPtr=%08x BlockStart=%08x",UnpPtr,WrPtr,BlockStart);

            memset(StackFilter.Prg.InitR, 0, sizeof(StackFilter.Prg.InitR));
            StackFilter.Prg.InitR[4] = StackFilter.BlockLength;

            if ((FirstByte & 0x10) != 0) // Set registers to optional parameters if any.
            {
                uint InitMask = VMCodeInp.fgetbits() >> 9;
                VMCodeInp.faddbits(7);
                for (int I = 0; I < 7; I++)
                {
                    if ((InitMask & (1 << I)) != 0)
                    {
                        StackFilter.Prg.InitR[I] = RarVM.ReadData(VMCodeInp);
                    }
                }
            }

            if (NewFilter)
            {
                uint VMCodeSize = RarVM.ReadData(VMCodeInp);
                if (VMCodeSize >= 0x10000 || VMCodeSize == 0)
                {
                    return(false);
                }
                Array <byte> VMCode(VMCodeSize);

                for (uint I = 0; I < VMCodeSize; I++)
                {
                    if (VMCodeInp.Overflow(3))
                    {
                        return(false);
                    }
                    VMCode[I] = VMCodeInp.fgetbits() >> 8;
                    VMCodeInp.faddbits(8);
                }
                VM.Prepare(&VMCode[0], VMCodeSize, &Filter->Prg);
            }
            StackFilter.Prg.Type = Filter.Prg.Type;

            return(true);
        }
コード例 #24
0
        public void InitializeLot(string lotName, bool external)
        {
            if (lotName == "")
            {
                return;
            }
            var recording = lotName.ToLowerInvariant().EndsWith(".fsor");

            CleanupLastWorld();

            if (FSOEnvironment.Enable3D)
            {
                var rc = new LotView.RC.WorldRC(GameFacade.GraphicsDevice);
                World = rc;
            }
            else
            {
                World = new World(GameFacade.GraphicsDevice);
            }
            World.Opacity = 1;
            GameFacade.Scenes.Add(World);

            var settings = GlobalSettings.Default;
            var myState  = new VMNetAvatarPersistState()
            {
                Name         = settings.LastUser,
                DefaultSuits = new VMAvatarDefaultSuits(settings.DebugGender),
                BodyOutfit   = settings.DebugBody,
                HeadOutfit   = settings.DebugHead,
                PersistID    = (uint)(new Random()).Next(),
                SkinTone     = (byte)settings.DebugSkin,
                Gender       = (short)(settings.DebugGender ? 0 : 1),
                Permissions  = SimAntics.Model.TSOPlatform.VMTSOAvatarPermissions.Admin,
                Budget       = 1000000,
            };

            if (recording)
            {
                var stream = new FileStream(lotName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                var rd     = new VMFSORDriver(stream);
                Driver = rd;
            }
            else if (external)
            {
                var cd = new VMClientDriver(ClientStateChange);
                SandCli             = new FSOSandboxClient();
                cd.OnClientCommand += (msg) => { SandCli.Write(new VMNetMessage(VMNetMessageType.Command, msg)); };
                cd.OnShutdown      += (reason) => SandCli.Disconnect();
                SandCli.OnMessage  += cd.ServerMessage;
                SandCli.Connect(lotName);
                Driver = cd;

                var dat = new MemoryStream();
                var str = new BinaryWriter(dat);
                myState.SerializeInto(str);
                var ava = new VMNetMessage(VMNetMessageType.AvatarData, dat.ToArray());
                dat.Close();
                SandCli.OnConnectComplete += () =>
                {
                    SandCli.Write(ava);
                };
            }
            else
            {
                var globalLink = new VMTSOGlobalLinkStub();
                var sd         = new VMServerDriver(globalLink);
                SandServer = new FSOSandboxServer();

                Driver                   = sd;
                sd.OnDropClient         += SandServer.ForceDisconnect;
                sd.OnTickBroadcast      += SandServer.Broadcast;
                sd.OnDirectMessage      += SandServer.SendMessage;
                SandServer.OnConnect    += sd.ConnectClient;
                SandServer.OnDisconnect += sd.DisconnectClient;
                SandServer.OnMessage    += sd.HandleMessage;

                SandServer.Start((ushort)37564);
            }

            //Driver.OnClientCommand += VMSendCommand;
            //Driver.OnShutdown += VMShutdown;

            vm = new VM(new VMContext(World), Driver, new UIHeadlineRendererProvider());
            vm.ListenBHAVChanges();
            vm.Init();

            LotControl = new UILotControl(vm, World);
            this.AddAt(0, LotControl);

            var time    = DateTime.UtcNow;
            var tsoTime = TSOTime.FromUTC(time);

            vm.Context.Clock.Hours   = tsoTime.Item1;
            vm.Context.Clock.Minutes = tsoTime.Item2;
            if (m_ZoomLevel > 3)
            {
                World.Visible      = false;
                LotControl.Visible = false;
            }

            if (IDEHook.IDE != null)
            {
                IDEHook.IDE.StartIDE(vm);
            }

            vm.OnFullRefresh      += VMRefreshed;
            vm.OnChatEvent        += Vm_OnChatEvent;
            vm.OnEODMessage       += LotControl.EODs.OnEODMessage;
            vm.OnRequestLotSwitch += VMLotSwitch;
            vm.OnGenericVMEvent   += Vm_OnGenericVMEvent;

            if (!external && !recording)
            {
                if (!Downtown && ActiveFamily != null)
                {
                    ActiveFamily.SelectWholeFamily();
                    vm.ActivateFamily(ActiveFamily);
                }
                BlueprintReset(lotName);

                vm.TSOState.PropertyCategory = 255;
                vm.Context.Clock.Hours       = 0;
                vm.TSOState.Size             = (10) | (3 << 8);
                vm.Context.UpdateTSOBuildableArea();
                var myClient = new VMNetClient
                {
                    PersistID   = myState.PersistID,
                    RemoteIP    = "local",
                    AvatarState = myState
                };

                var server = (VMServerDriver)Driver;
                server.ConnectClient(myClient);

                GameFacade.Cursor.SetCursor(CursorType.Normal);
                ZoomLevel = 1;
            }
            vm.MyUID  = myState.PersistID;
            ZoomLevel = 1;
        }
コード例 #25
0
        public override void Update(UpdateState state)
        {
            base.Update(state);
            if (TempVM == null && GUID != 0)
            {
                var world = new ExternalWorld(GameFacade.GraphicsDevice);
                world.Initialize(GameFacade.Scenes);
                var context = new VMContext(world);

                TempVM = new VM(context, new VMServerDriver(new VMTSOGlobalLinkStub()), new VMNullHeadlineProvider());
                TempVM.Init();

                var blueprint = new Blueprint(1, 1);
                blueprint.Light = new RoomLighting[]
                {
                    new RoomLighting()
                    {
                        OutsideLight = 100
                    },
                    new RoomLighting()
                    {
                        OutsideLight = 100
                    },
                    new RoomLighting()
                    {
                        OutsideLight = 100
                    },
                };
                blueprint.OutsideColor = Color.White;
                blueprint.GenerateRoomLights();
                blueprint.RoomColors[2].A /= 2;
                world.State.AmbientLight.SetData(blueprint.RoomColors);
                world.State.OutsidePx.SetData(new Color[] { Color.White });

                world.InitBlueprint(blueprint);
                context.Blueprint    = blueprint;
                context.Architecture = new VMArchitecture(1, 1, blueprint, TempVM.Context);
            }

            if (GUID != oldGUID)
            {
                SetGUIDLocal(GUID, TempVM);
                state.SharedData["ExternalDraw"] = true;
            }

            if (ForceRedraw)
            {
                state.SharedData["ExternalDraw"] = true;
                ForceRedraw = false;
            }

            if (TempVM != null)
            {
                var lcount = TempVM.Scheduler.CurrentTickID;
                TempVM.Update();
                var count = TempVM.Scheduler.CurrentTickID;
                foreach (var ent in TempVM.Entities)
                {
                    if (ent is VMAvatar)
                    {
                        for (uint i = lcount; i < count; i++)
                        {
                            ent.Tick();
                        }
                    }
                }
                TempVM.PreDraw();
            }
        }
コード例 #26
0
        /// <summary>
        /// 在应用程序由最终用户正常启动时进行调用。
        /// 将在启动应用程序以打开特定文件等情况下使用。
        /// </summary>
        /// <param name="e">有关启动请求和过程的详细信息。</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            //初始化默认图片
            await PictureHandler.SetDefaultPixels();

            //初始化数据库
            SQLiteService.InitializeDatabase();

            //Load DB
            VM.Init();

            //磁贴
            TileService.CreateTile();

            // 不要在窗口已包含内容时重复应用程序初始化,
            // 只需确保窗口处于活动状态
            if (rootFrame == null)
            {
                // 创建要充当导航上下文的框架,并导航到第一页
                rootFrame = new Frame();

                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: 从之前挂起的应用程序加载状态
                    if (ApplicationData.Current.LocalSettings.Values.ContainsKey("NavigationState"))
                    {
                        rootFrame.SetNavigationState((string)ApplicationData.Current.LocalSettings.Values["NavigationState"]);
                    }
                }
                else
                {
                    ApplicationData.Current.LocalSettings.Values.Clear();
                }

                // 将框架放在当前窗口中
                Window.Current.Content = rootFrame;
            }

            if (e.PrelaunchActivated == false)
            {
                if (rootFrame.Content == null)
                {
                    // 当导航堆栈尚未还原时,导航到第一页,
                    // 并通过将所需信息作为导航参数传入来配置
                    // 参数
                    rootFrame.Navigate(typeof(MainPage), e.Arguments);
                }

                // 确保当前窗口处于活动状态
                Window.Current.Activate();
            }

            //挂起后恢复
            SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
                rootFrame.CanGoBack ? AppViewBackButtonVisibility.Visible : AppViewBackButtonVisibility.Collapsed;

            //是否加入返回键
            rootFrame.Navigated += OnNavagated;

            //返回事件
            SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;

            CustomSetting.LoadBg();
        }
コード例 #27
0
        public LotScreenNew()
        {
            var lotInfo = XmlHouseData.Parse(GameFacade.GameFilePath("housedata/blueprints/restaurant07_00.xml"));

            World = new World();
            GameFacade.Scenes.Add(World);

            vm = new VM(new VMContext(World));
            vm.Init();

            var activator = new VMWorldActivator(vm, World);
            var blueprint = activator.LoadFromXML(lotInfo);

            World.InitBlueprint(blueprint);
            vm.Context.Blueprint = blueprint;

            var sim = activator.CreateAvatar();

            //sim.Position = new Vector3(31.5f, 55.5f, 0.0f);
            sim.Position = new Vector3(26.5f, 41.5f, 0.0f);

            VMDebug = new UIButton()
            {
                Caption = "Simantics",
                Y       = 45,
                Width   = 100,
                X       = GlobalSettings.Default.GraphicsWidth - 110
            };
            VMDebug.OnButtonClick += new ButtonClickDelegate(VMDebug_OnButtonClick);
            this.Add(VMDebug);

            //var lotInfo = HouseData.Parse("C:\\restaurant00_00_small.xml");
            //for (int i = 1; i < 64; i++)
            //{
            //    lotInfo.World.Floors.Add(new HouseDataFloor {
            //         X = 1,
            //         Y = i,
            //         Level = 0,
            //         Value = 9
            //    });
            //}

            //lotInfo.World.Floors.Add(new HouseDataFloor {
            //    X = 0, Y = 0,
            //    Level = 0, Value = 20
            //});

            //lotInfo.World.Floors.Add(new HouseDataFloor
            //{
            //    X = 63,
            //    Y = 63,
            //    Level = 0,
            //    Value = 40
            //});

            //lotInfo.World.Floors.Add(new HouseDataFloor
            //{
            //    X = 0,
            //    Y = 63,
            //    Level = 0,
            //    Value = 20
            //});

            //lotInfo.World.Floors.Add(new HouseDataFloor
            //{
            //    X = 63,
            //    Y = 0,
            //    Level = 0,
            //    Value = 20
            //});



            //Renderer = new HouseRenderer();
            //Renderer.SetModel(lotInfo);
            ////Renderer.Position = new Microsoft.Xna.Framework.Vector3(-32.0f, -40.0f, 0.0f);

            //var scene = new ThreeDScene();
            //var focusPoint = Vector3.Zero;

            //var yValue = (float)Math.Cos(MathHelper.ToRadians(30.0f)) * 96.0f;
            //var cameraOffset = new Vector3(-96.0f, yValue, 96.0f);
            //var rotatedOffset = Vector3.Transform(cameraOffset, Microsoft.Xna.Framework.Matrix.CreateRotationY(MathHelper.PiOver2 * 0.5f));

            ////rotatedOffset = Vector3.Transform(rotatedOffset, Microsoft.Xna.Framework.Matrix.CreateScale(3f));
            ////Renderer.Position = new Vector3(-96.0f, 0.0f, -96.0f);

            //scene.Camera.Position = cameraOffset;// new Microsoft.Xna.Framework.Vector3(0, 0, 80);
            //scene.Add(Renderer);
            //Renderer.Scale = new Vector3(0.005f);

            //GameFacade.Scenes.AddScene(scene);


            ucp                  = new UIUCP();
            ucp.Y                = ScreenHeight - 210;
            ucp.OnZoomChanged   += new UCPZoomChangeEvent(ucp_OnZoomChanged);
            ucp.OnRotateChanged += new UCPRotateChangeEvent(ucp_OnRotateChanged);
            this.Add(ucp);
        }
コード例 #28
0
        public void ResetVM()
        {
            LOG.Info("Resetting VM for lot with dbid = " + Context.DbId);
            VMGlobalLink              = Kernel.Get <LotServerGlobalLink>();
            VMDriver                  = new VMServerDriver(VMGlobalLink);
            VMDriver.OnTickBroadcast += TickBroadcast;
            VMDriver.OnDirectMessage += DirectMessage;
            VMDriver.OnDropClient    += DropClient;

            Lot = new VM(new VMContext(null), VMDriver, new VMNullHeadlineProvider());
            Lot.Init();

            bool isNew   = false;
            bool isMoved = (LotPersist.move_flags > 0);

            LoadAdj();
            if (!JobLot && LotPersist.ring_backup_num > -1 && AttemptLoadRing())
            {
                LOG.Info("Successfully loaded and cleaned fsov for dbid = " + Context.DbId);
            }
            else
            {
                isNew = true;
                BlueprintReset();
            }

            Lot.TSOState.Terrain          = Terrain;
            Lot.TSOState.Name             = LotPersist.name;
            Lot.TSOState.OwnerID          = LotPersist.owner_id;
            Lot.TSOState.Roommates        = new HashSet <uint>();
            Lot.TSOState.BuildRoommates   = new HashSet <uint>();
            Lot.TSOState.PropertyCategory = (byte)LotPersist.category;
            foreach (var roomie in LotRoommates)
            {
                if (roomie.is_pending > 0)
                {
                    continue;
                }
                Lot.TSOState.Roommates.Add(roomie.avatar_id);
                if (roomie.permissions_level > 0)
                {
                    Lot.TSOState.BuildRoommates.Add(roomie.avatar_id);
                }
                if (roomie.permissions_level > 1)
                {
                    Lot.TSOState.OwnerID = roomie.avatar_id;
                }
            }

            var time    = DateTime.UtcNow;
            var tsoTime = TSOTime.FromUTC(time);

            Lot.Context.UpdateTSOBuildableArea();

            Lot.MyUID = uint.MaxValue - 1;
            if ((LotPersist.move_flags & 2) > 0)
            {
                isNew = true;
            }
            ReturnInvalidObjects();
            if (!JobLot)
            {
                ReturnOOWObjects();
            }

            if (isMoved || isNew)
            {
                VMLotTerrainRestoreTools.RestoreTerrain(Lot);
            }
            if (isNew)
            {
                VMLotTerrainRestoreTools.PopulateBlankTerrain(Lot);
            }

            Lot.Context.Clock.Hours   = tsoTime.Item1;
            Lot.Context.Clock.Minutes = tsoTime.Item2;

            Lot.Context.UpdateTSOBuildableArea();

            var entClone = new List <VMEntity>(Lot.Entities);

            foreach (var ent in entClone)
            {
                if (ent is VMGameObject)
                {
                    ((VMGameObject)ent).Disabled &= ~VMGameObjectDisableFlags.TransactionIncomplete;
                    ((VMGameObject)ent).DisableIfTSOCategoryWrong(Lot.Context);
                    if (ent.GetFlag(VMEntityFlags.Occupied))
                    {
                        ent.ResetData();
                        ent.Init(Lot.Context); //objects should not be occupied when we join the lot...
                    }
                    {
                        ent.ExecuteEntryPoint(2, Lot.Context, true);
                    }
                }
            }
            LotActive.Set();
            ActiveYet = true;
        }
コード例 #29
0
ファイル: Products.xaml.cs プロジェクト: hal-wang/Sqless
        public Products()
        {
            InitializeComponent();

            VM.Init();
        }