Esempio n. 1
0
        private static void PatchTexts(string resourceFile)
        {
            if (!File.Exists(resourceFile))
                return;

            using (var stream = MyFileSystem.OpenRead(resourceFile))
            using (var reader = new ResXResourceReader(stream))
            {
                foreach (DictionaryEntry entry in reader)
                {
                    string key = entry.Key as string;
                    string value = entry.Value as string;

                    Debug.Assert(key != null && value != null, string.Format("Text has incorrect format. [{0}:{1}]", key.GetType().Name, value.GetType().Name));
                    if (key == null || value == null)
                        continue;

                    var id = MyStringId.GetOrCompute(key);
                    m_strings[id] = value;
                    m_stringBuilders[id] = new StringBuilder(value);
                }
            }

        }
Esempio n. 2
0
        public static void LoadContent(MyFontDescription[] fonts)
        {
            VRageRender.MyRenderProxy.Log.WriteLine("MyGuiManager2.LoadContent() - START");
            VRageRender.MyRenderProxy.Log.IncreaseIndent();

            var path = Path.Combine(MyFileSystem.ContentPath, Path.Combine("Textures", "GUI", "MouseCursorHW.png"));

            using (var stream = MyFileSystem.OpenRead(path))
            {
                m_mouseCursorBitmap = System.Drawing.Bitmap.FromStream(stream) as System.Drawing.Bitmap;
            }
            SetMouseCursorTexture(MyGuiConstants.CURSOR_ARROW);
            SetHWCursorBitmap(m_mouseCursorBitmap);


            m_backgroundScreenTextures = new List <MyGuiTextureScreen>
            {
                new MyGuiTextureScreen(MyGuiConstants.TEXTURE_SCREEN_BACKGROUND.Texture,
                                       (int)MyGuiConstants.TEXTURE_SCREEN_BACKGROUND.SizePx.X,
                                       (int)MyGuiConstants.TEXTURE_SCREEN_BACKGROUND.SizePx.Y),
            };

            foreach (var font in fonts)
            {
                m_fontsById[(int)font.Id] = new VRageRender.MyFont(font.Path);
                VRageRender.MyRenderProxy.CreateFont((int)font.Id, font.Path, font.IsDebug);
            }

            VRageRender.MyRenderProxy.PreloadTextures(@"Textures\GUI\Icons", true);
            VRageRender.MyRenderProxy.PreloadTextures(@"Textures\GUI\Controls", true);

            MouseCursorPosition = new Vector2(0.5f, 0.5f);// new MyMwcVector2Int(MySandboxGame.ScreenSizeHalf.X, MySandboxGame.ScreenSizeHalf.Y);

            VRageRender.MyRenderProxy.Log.DecreaseIndent();
            VRageRender.MyRenderProxy.Log.WriteLine("MyGuiManager2.LoadContent() - END");
        }
Esempio n. 3
0
 public static string[] UpdateCompatibility(string[] files)
 {
     string[] sources = new string[files.Length];
     for (int i = 0; i < files.Length; ++i)
     {
         using (Stream stream = MyFileSystem.OpenRead(files[i]))
         {
             if (stream != null)
             {
                 using (StreamReader sr = new StreamReader(stream))
                 {
                     string source = sr.ReadToEnd();
                     source = source.Insert(0, "using VRage;\r\nusing VRage.Components;\r\nusing VRage.ObjectBuilders;\r\nusing VRage.ModAPI;\r\n");
                     foreach (var value in m_compatibilityChanges)
                     {
                         source = source.Replace(value.Key, value.Value);
                     }
                     sources[i] = source;
                 }
             }
         }
     }
     return(sources);
 }
        public void InitMyFileSystem(string instanceName = "", bool reset = true)
        {
            string contentPath  = Path.Combine(new FileInfo(MyFileSystem.ExePath).Directory.FullName, "Content");
            string userDataPath = SandboxGameAssemblyWrapper.Instance.GetUserDataPath(instanceName);

            if (reset)
            {
                MyFileSystem.Reset();
            }
            else
            {
                try
                {
                    if (!string.IsNullOrWhiteSpace(MyFileSystem.ContentPath))
                    {
                        return;
                    }
                    if (!string.IsNullOrWhiteSpace(MyFileSystem.UserDataPath))
                    {
                        return;
                    }
                }
                catch (Exception)
                {
                    //Do nothing
                }
            }

            MyFileSystem.Init(contentPath, userDataPath);
            MyFileSystem.InitUserSpecific((string)null);

            string debugContentPath  = MyFileSystem.ContentPath;
            string debugUserDataPath = MyFileSystem.UserDataPath;

            m_instanceName = instanceName;
        }
Esempio n. 5
0
        public static void LoadTexts(string rootDirectory, string cultureName = null, string subcultureName = null)
        {
            HashSet<string> baseFiles = new HashSet<string>();
            var files = MyFileSystem.GetFiles(rootDirectory, "*.resx", FileSystem.MySearchOption.TopDirectoryOnly);
            foreach (var file in files)
            {
                baseFiles.Add(Path.GetFileNameWithoutExtension(file).Split('.')[0]);
            }

            foreach (var baseFile in baseFiles)
                PatchTexts(Path.Combine(rootDirectory, string.Format("{0}.resx", baseFile)));

            if (cultureName == null)
                return;

            foreach (var baseFile in baseFiles)
                PatchTexts(Path.Combine(rootDirectory, string.Format("{0}.{1}.resx", baseFile, cultureName)));

            if (subcultureName == null)
                return;

            foreach (var baseFile in baseFiles)
                PatchTexts(Path.Combine(rootDirectory, string.Format("{0}.{1}-{2}.resx", baseFile, cultureName, subcultureName)));
        }
Esempio n. 6
0
            public void Load()
            {
                if (TextureState == FileTextureState.Loaded)
                {
                    return;
                }

                string path = Path.Combine(MyFileSystem.ContentPath, Name);

                Debug.Assert(m_resource == null);
                Debug.Assert(m_srv == null, "Texture " + Name + " in invalid state");

                Image img = null;

                if (MyFileSystem.FileExists(path))
                {
                    try
                    {
                        using (var s = MyFileSystem.OpenRead(path))
                        {
                            img = Image.Load(s);
                            m_imageFormatInFile = img.Description.Format;
                        }
                    }
                    catch (Exception e)
                    {
                        MyRender11.Log.WriteLine("Error while loading texture: " + path + ", exception: " + e);
                    }
                }

                bool loaded = false;

                if (img != null)
                {
                    int skipMipmaps = (m_type != MyFileTextureEnum.GUI && m_type != MyFileTextureEnum.GPUPARTICLES && img.Description.MipLevels > 1)
                        ? MyRender11.RenderSettings.TextureQuality.MipmapsToSkip(img.Description.Width,
                                                                                 img.Description.Height)
                        : 0;

                    if (m_skipQualityReduction)
                    {
                        skipMipmaps = 0;
                    }

                    int totalSize = 0;

                    int targetMipmaps = img.Description.MipLevels - skipMipmaps;
                    var mipmapsData   = new DataBox[(img.Description.MipLevels - skipMipmaps) * img.Description.ArraySize];

                    long delta    = 0;
                    int  lastSize = 0;

                    for (int z = 0; z < img.Description.ArraySize; z++)
                    {
                        for (int i = 0; i < targetMipmaps; i++)
                        {
                            var pixels = img.GetPixelBuffer(z, i + skipMipmaps);
                            mipmapsData[Resource.CalculateSubResourceIndex(i, z, targetMipmaps)] =
                                new DataBox {
                                DataPointer = pixels.DataPointer, RowPitch = pixels.RowStride
                            };
                            delta = pixels.DataPointer.ToInt64() - img.DataPointer.ToInt64();

                            lastSize   = pixels.BufferStride;
                            totalSize += lastSize;
                        }
                    }

                    var targetWidth  = img.Description.Width >> skipMipmaps;
                    var targetHeight = img.Description.Height >> skipMipmaps;

                    bool overwriteFormatToSrgb = (m_type != MyFileTextureEnum.NORMALMAP_GLOSS) &&
                                                 !FormatHelper.IsSRgb(img.Description.Format);

                    var desc = new Texture2DDescription
                    {
                        MipLevels         = targetMipmaps,
                        Format            = overwriteFormatToSrgb ? MyResourceUtils.MakeSrgb(img.Description.Format) : img.Description.Format,
                        Height            = targetHeight,
                        Width             = targetWidth,
                        ArraySize         = img.Description.ArraySize,
                        BindFlags         = BindFlags.ShaderResource,
                        CpuAccessFlags    = CpuAccessFlags.None,
                        Usage             = ResourceUsage.Immutable,
                        SampleDescription = new SampleDescription {
                            Count = 1, Quality = 0
                        },
                        OptionFlags =
                            img.Description.Dimension == TextureDimension.TextureCube
                                ? ResourceOptionFlags.TextureCube
                                : ResourceOptionFlags.None
                    };

                    try
                    {
                        m_resource = new Texture2D(MyRender11.Device, desc, mipmapsData);
                        m_size     = new Vector2I(targetWidth, targetHeight);
                        //m_skippedMipmaps = skipMipmaps;
                        m_fileExists = true;
                        m_byteSize   = totalSize;
                        m_ownsData   = true;

                        m_srv = new ShaderResourceView(MyRender11.Device, m_resource);
                        m_resource.DebugName = m_name;
                        m_srv.DebugName      = m_name;

                        img.Dispose();

                        loaded = true;
                    }
                    catch (SharpDXException)
                    {
                        img.Dispose();
                    }
                }
                if (!loaded)
                {
                    ISrvBindable replacingTexture = MyGeneratedTextureManager.ZeroTex;
                    switch (m_type)
                    {
                    case MyFileTextureEnum.NORMALMAP_GLOSS:
                        replacingTexture = MyGeneratedTextureManager.MissingNormalGlossTex;
                        break;

                    case MyFileTextureEnum.EXTENSIONS:
                        replacingTexture = MyGeneratedTextureManager.MissingExtensionTex;
                        break;

                    case MyFileTextureEnum.ALPHAMASK:
                        replacingTexture = MyGeneratedTextureManager.MissingAlphamaskTex;
                        break;

                    case MyFileTextureEnum.CUBEMAP:
                        replacingTexture = MyGeneratedTextureManager.MissingCubeTex;
                        break;
                    }

                    MyRender11.Log.WriteLine("Could not load texture: " + path);

                    m_srv        = replacingTexture.Srv;
                    m_resource   = replacingTexture.Resource;
                    m_size       = replacingTexture.Size;
                    m_ownsData   = false;
                    m_fileExists = false;
                    m_byteSize   = 0;
                    MyRender11.Log.WriteLine("Missing or invalid texture: " + Name);
                }

                TextureState = FileTextureState.Loaded;
            }
Esempio n. 7
0
        public void AttachPilot(MyCharacter pilot, bool storeOriginalPilotWorld = true, bool calledFromInit = false)
        {
            System.Diagnostics.Debug.Assert(pilot != null);
            System.Diagnostics.Debug.Assert(m_pilot == null);

            m_pilot = pilot;
            m_pilot.OnMarkForClose += m_pilotClosedHandler;
            m_pilot.IsUsing         = this;

            //m_soundEmitter.OwnedBy = m_pilot;
            if (MyFakes.ENABLE_NEW_SOUNDS)
            {
                StartLoopSound();
            }

            if (storeOriginalPilotWorld)
            {
                m_pilotRelativeWorld = (Matrix)MatrixD.Multiply(pilot.WorldMatrix, this.PositionComp.GetWorldMatrixNormalizedInv());
                if (Sync.IsServer)
                {
                    var relativeEntry = new MyPositionAndOrientation(m_pilotRelativeWorld.Value);
                    SyncObject.SendPilotRelativeEntryUpdate(ref relativeEntry);
                }
            }

            if (pilot.InScene)
            {
                MyEntities.Remove(pilot);
            }

            m_pilot.Physics.Enabled = false;
            m_pilot.PositionComp.SetWorldMatrix(WorldMatrix);
            m_pilot.Physics.Clear();
            //m_pilot.SetPosition(GetPosition() - WorldMatrix.Forward * 0.5f);

            Hierarchy.AddChild(m_pilot, true, true);

            var gunEntity = m_pilot.CurrentWeapon as MyEntity;

            if (gunEntity != null)
            {
                var ob = gunEntity.GetObjectBuilder();
                m_pilotGunDefinition = ob.GetId();
            }
            else
            {
                m_pilotGunDefinition = null;
            }

            MyAnimationDefinition animationDefinition;
            MyDefinitionId        id = new MyDefinitionId(typeof(MyObjectBuilder_AnimationDefinition), BlockDefinition.CharacterAnimation);

            if (!MyDefinitionManager.Static.TryGetDefinition(id, out animationDefinition) && !MyFileSystem.FileExists(BlockDefinition.CharacterAnimation))
            {
                BlockDefinition.CharacterAnimation = null;
            }

            PlacePilotInSeat(pilot);
            m_rechargeSocket.PlugIn(m_pilot.SuitBattery);

            // Control should be handled elsewhere if we initialize the grid in the Init(...)
            if (!calledFromInit)
            {
                GiveControlToPilot();
            }
            m_pilot.SwitchToWeapon(null);
        }
Esempio n. 8
0
        public void FindType()
        {
            Type ivms = typeof(VRage.Game.ModAPI.IMyVoxelMaps);

            var binPath = @"D:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin";

            var assemblyFiles = Directory.GetFiles(binPath /*GlobalSettings.Default.SEBinPath*/, "*.dll");

            _spaceEngineersAssemblies = assemblyFiles.Select(f => Path.GetFileName(f)).ToList();

            Type      baseType      = typeof(Sandbox.Definitions.MyDefinitionManager);
            AppDomain currentDomain = AppDomain.CurrentDomain;

            currentDomain.AssemblyResolve += currentDomain_AssemblyResolve;
            currentDomain.ReflectionOnlyAssemblyResolve += currentDomain_ReflectionOnlyAssemblyResolve;

            currentDomain.TypeResolve += currentDomain_TypeResolve;
            try
            {
                MyFileSystem.Reset();
                MyFileSystem.Init(@"C:\Program Files (x86)\Steam\SteamApps\common\SpaceEngineers\Content", Environment.ExpandEnvironmentVariables(@"%AppData%\SpaceEngineers"));
                MyFileSystem.InitUserSpecific((string)null);

                // #########################
                // MySandboxGame (obsfcated) has to be created in memory to be able to load Voxel Material Definitions.
                // Without the Voxel Material Definitions, you cannot use the IMyStorage to load an asteroid.
                // So, this is a pointless waste of effort to try and use the in game code.
                // #########################

                Sandbox.Definitions.MyDefinitionManager.Static.LoadData(new List <MyObjectBuilder_Checkpoint.ModItem>());
                var materials = Sandbox.Definitions.MyDefinitionManager.Static.GetVoxelMaterialDefinitions();

                //DictionaryValuesReader<string, MyVoxelMaterialDefinition>;
                //var dict = materials as Dictionary<string, MyVoxelMaterialDefinition>;


                //var matx = Sandbox.Definitions.MyDefinitionManager.Static.m_definitions.m_voxelMaterialsByName;
                var xz = Sandbox.Definitions.MyDefinitionManager.Static.GetDefaultVoxelMaterialDefinition();

                //var tt = ass2.GetType("Sandbox.ModAPI.IMyVoxelMaps");
                //var ass = System.Reflection.Assembly.ReflectionOnlyLoad("Sandbox.Game");
                var ass = baseType.Assembly;

                //               ass.GetType();
                //var modules = ass.GetModules(false);
                //var types = modules[0].GetTypes();
                var types = ass.GetTypes();

                var myVoxelMapsType = types.Where(p => ivms.IsAssignableFrom(p)).First();
                var myVoxelMaps     = Activator.CreateInstance(myVoxelMapsType) as VRage.Game.ModAPI.IMyVoxelMaps;

                //5BCAC68007431E61367F5B2CF24E2D6F.5217D2CFAB7CCD6299A3F53DAEE1DEB1
                //public static 6922E99EC72C10627AA239B8167BF7DC A109856086C45CF523B23AFCDDB82F43(byte[] 06D95B424FC4150954FF019440A547AE)
                var filename = @"C:\Program Files (x86)\Steam\SteamApps\common\SpaceEngineers\Content\VoxelMaps\Arabian_Border_7.vx2";

                byte[] buffer  = File.ReadAllBytes(filename);
                var    storage = myVoxelMaps.CreateStorage(buffer);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 9
0
    int ProcessFiles(DirectoryInfo diTop, int i)
    {
        fsscript = transform.gameObject.GetComponent <MyFileSystem>();
        int   samples   = diTop.GetDirectories("*").Length;
        float rnd       = 1;
        bool  randomize = true;

        if (randomize)
        {
            rnd = UnityEngine.Random.value * samples;
        }

        float offset    = 2.0f / samples;
        float increment = Mathf.PI * (3.0f - Mathf.Sqrt(5.0f));

        foreach (var fi in diTop.EnumerateFiles())
        {
            try
            {
                float y = ((i * offset) - 1) + (offset / 2);
                float r = Mathf.Sqrt(1 - Mathf.Pow(y, 2));

                float phi = ((i + rnd) % samples) * increment;

                float x = Mathf.Cos(phi) * r;
                float z = Mathf.Sin(phi) * r;

                var gObj = GameObject.CreatePrimitive(PrimitiveType.Cube);
                gObj.transform.position    = new Vector3(x + transform.position.x, y + transform.position.y, z + transform.position.z);
                gObj.transform.localScale *= 0.1f;

                gObj.transform.GetComponent <Renderer>().material.color = new Color(x, y, z);
                gObj.transform.GetComponent <Renderer>().material.SetColor("_EmissionColor", new Color(255, 0, 0));

                gObj.transform.SetParent(transform);
                gObj.name = fi.FullName;
                gObj.transform.LookAt(transform);

                gObj.AddComponent <DataNode>();
                DataNode dn = gObj.GetComponent <DataNode>();
                dn.Name     = fi.Name;
                dn.Size     = -1;
                dn.FullName = fi.FullName;
                dn.IsFolder = false;

                dn.ParentObject    = transform.gameObject;
                dn.CurrentPosition = transform.position;

                c1    = transform.GetComponent <Renderer>().material.color;
                c2    = new Color(x, y, z);
                p1    = transform;
                p2    = gObj.transform;
                cGObj = gObj;
                DrawConnection(p1.position, p2.position, cGObj);


                //Debug.Log($"{ fi.FullName}\t\t{fi.Parent}");
            }
            catch (UnauthorizedAccessException unAuthTop)
            {
                Debug.LogWarning($"{unAuthTop.Message}");
            }
            i++;
        }
        return(i);
    }
Esempio n. 10
0
        public static void InvokeBeforeRun(uint appId, string appName, string userDataPath, bool addDateToLog = false)
        {
            m_appName = appName;

            var logName = new StringBuilder(m_appName);

            if (addDateToLog)
            {
                logName.Append("_");
                logName.Append(new StringBuilder().GetFormatedDateTimeForFilename(DateTime.Now));
            }
            logName.Append(".log");

            var rootPath    = new FileInfo(MyFileSystem.ExePath).Directory.FullName;
            var contentPath = Path.Combine(rootPath, "Content");

            MyFileSystem.Init(contentPath, userDataPath);

            bool isSteamPath     = SteamHelpers.IsSteamPath(rootPath);
            bool manifestPresent = SteamHelpers.IsAppManifestPresent(rootPath, appId);

            MySandboxGame.IsPirated = !isSteamPath && !manifestPresent;

            MySandboxGame.Log.Init(logName.ToString(), MyFinalBuildConstants.APP_VERSION_STRING);
            MySandboxGame.Log.WriteLine("Steam build: Always true");
            MySandboxGame.Log.WriteLine(string.Format("Is official: {0} {1}{2}{3}",
                                                      MyFinalBuildConstants.IS_OFFICIAL,
                                                      (MyObfuscation.Enabled ? "[O]" : "[NO]"),
                                                      (isSteamPath ? "[IS]" : "[NIS]"),
                                                      (manifestPresent ? "[AMP]" : "[NAMP]")));
            MySandboxGame.Log.WriteLine("Environment.ProcessorCount: " + Environment.ProcessorCount);
            MySandboxGame.Log.WriteLine("Environment.OSVersion: " + Environment.OSVersion);
            MySandboxGame.Log.WriteLine("Environment.CommandLine: " + Environment.CommandLine);
            MySandboxGame.Log.WriteLine("Environment.Is64BitProcess: " + Environment.Is64BitProcess);
            MySandboxGame.Log.WriteLine("Environment.Is64BitOperatingSystem: " + Environment.Is64BitOperatingSystem);
            MySandboxGame.Log.WriteLine("Environment.Version: " + Environment.Version);
            MySandboxGame.Log.WriteLine("Environment.CurrentDirectory: " + Environment.CurrentDirectory);
            MySandboxGame.Log.WriteLine("MainAssembly.ProcessorArchitecture: " + Assembly.GetExecutingAssembly().GetArchitecture());
            MySandboxGame.Log.WriteLine("ExecutingAssembly.ProcessorArchitecture: " + MyFileSystem.MainAssembly.GetArchitecture());
            MySandboxGame.Log.WriteLine("IntPtr.Size: " + IntPtr.Size.ToString());
            MySandboxGame.Log.WriteLine("Default Culture: " + CultureInfo.CurrentCulture.Name);
            MySandboxGame.Log.WriteLine("Default UI Culture: " + CultureInfo.CurrentUICulture.Name);
            MySandboxGame.Log.WriteLine("IsAdmin: " + new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator));

            MyLog.Default = MySandboxGame.Log;
            MyTrace.InitWinTrace();

            MyEnumDuplicitiesTester.CheckEnumNotDuplicitiesInRunningApplication(); // About 300 ms

            Debug.WriteLine(string.Format("{0}: Started", m_appName));

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
            Thread.CurrentThread.Name = "Main thread";

            //Because we want exceptions from users to be in english
            Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

            MySandboxGame.Config = new MyConfig(appName + ".cfg");
            MySandboxGame.Config.Load();
            //MySandboxGame.ConfigDedicated = new MyConfigDedicated("MedievalEngineers-Dedicated.cfg");
        }
Esempio n. 11
0
        public SpaceEngineersCore()
        {
            var    contentPath  = ToolboxUpdater.GetApplicationContentPath();
            string userDataPath = SpaceEngineersConsts.BaseLocalPath.DataPath;

            MyFileSystem.Reset();
            MyFileSystem.Init(contentPath, userDataPath);

            MyLog.Default        = MySandboxGame.Log;
            MySandboxGame.Config = new MyConfig("SpaceEngineers.cfg"); // TODO: Is specific to SE, not configurable to ME.
            MySandboxGame.Config.Load();

            MyFileSystem.InitUserSpecific(null);

            MyFakes.ENABLE_INFINARIO = false;

            SpaceEngineersGame.SetupPerGameSettings();

            VRageRender.MyRenderProxy.Initialize(new MyNullRender());
            // We create a whole instance of MySandboxGame!
            MySandboxGame gameTemp = new MySandboxGame(null);

            // creating MySandboxGame will reset the CurrentUICulture, so I have to reapply it.
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(GlobalSettings.Default.LanguageCode);
            SpaceEngineersApi.LoadLocalization();
            MyStorageBase.UseStorageCache = false;

            try
            {
                // Replace the private constructor on MySession, so we can create it without getting involed with Havok and other depdancies.
                var keenStart = typeof(Sandbox.Game.World.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null);
                var ourStart  = typeof(SEToolbox.Interop.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(MySyncLayer), typeof(bool) }, null);
                ReflectionUtil.ReplaceMethod(ourStart, keenStart);


                // Create an empty instance of MySession for use by low level code.
                ConstructorInfo constructorInfo = typeof(Sandbox.Game.World.MySession).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null);
                object          mySession       = constructorInfo.Invoke(new object[0]);

                // Assign the instance back to the static.
                Sandbox.Game.World.MySession.Static          = (Sandbox.Game.World.MySession)mySession;
                Sandbox.Game.World.MySession.Static.Settings = new MyObjectBuilder_SessionSettings {
                    EnableVoxelDestruction = true
                };
            }
            catch (Exception ex)
            {
                Debugger.Break();
            }

            try
            {
                Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static = new MyHeightMapLoadingSystem();
                Sandbox.Game.GameSystems.MyHeightMapLoadingSystem.Static.LoadData();
            }
            catch (Exception ex)
            {
                Debugger.Break();
            }

            _stockDefinitions = new SpaceEngineersResources();
            _stockDefinitions.LoadDefinitions();
            _manageDeleteVoxelList = new List <string>();
        }
Esempio n. 12
0
        public override void Init(MyObjectBuilder_SessionComponent sessionComponent)
        {
            base.Init(sessionComponent);

            // Only servers can run this session component
            if (!Session.IsServer)
            {
                return;
            }
            MyObjectBuilder_VisualScriptManagerSessionComponent ob = (MyObjectBuilder_VisualScriptManagerSessionComponent)sessionComponent;

            m_objectBuilder = ob;
            m_relativePathsToAbsolute.Clear();
            m_stateMachineDefinitionFilePaths.Clear();

            // Runs game started event
            m_firstUpdate = ob.FirstRun;

            // load vanilla level script files
            if (ob.LevelScriptFiles != null)
            {
                foreach (string relativeFilePath in ob.LevelScriptFiles)
                {
                    var absolutePath = Path.Combine(MyFileSystem.ContentPath, relativeFilePath);
                    // Add only existing files
                    if (MyFileSystem.FileExists(absolutePath))
                    {
                        m_relativePathsToAbsolute.Add(relativeFilePath, absolutePath);
                    }
                    else
                    {
                        MyLog.Default.WriteLine(relativeFilePath + " Level Script was not found.");
                        Debug.Fail(relativeFilePath + " Level Script was not found.");
                    }
                }
            }

            // load vanilla mission manchines
            if (ob.StateMachines != null)
            {
                foreach (var relativeFilePath in ob.StateMachines)
                {
                    var absolutePath = Path.Combine(MyFileSystem.ContentPath, relativeFilePath);
                    // Add only existing files
                    if (MyFileSystem.FileExists(absolutePath))
                    {
                        if (!m_relativePathsToAbsolute.ContainsKey(relativeFilePath))
                        {
                            m_stateMachineDefinitionFilePaths.Add(absolutePath);
                        }

                        m_relativePathsToAbsolute.Add(relativeFilePath, absolutePath);
                    }
                    else
                    {
                        MyLog.Default.WriteLine(relativeFilePath + " Mission File was not found.");
                        Debug.Fail(relativeFilePath + " Mission File was not found.");
                    }
                }
            }

            // Load mission machines and level scripts from mods
            // Overrides vanilla files
            if (Session.Mods != null)
            {
                foreach (var modItem in Session.Mods)
                {
                    // First try is a mod archive
                    var directoryPath = Path.Combine(MyFileSystem.ModsPath, modItem.PublishedFileId + ".sbm");
                    if (!MyFileSystem.DirectoryExists(directoryPath))
                    {
                        directoryPath = Path.Combine(MyFileSystem.ModsPath, modItem.Name);
                        if (!MyFileSystem.DirectoryExists(directoryPath))
                        {
                            directoryPath = null;
                        }
                    }

                    if (!string.IsNullOrEmpty(directoryPath))
                    {
                        foreach (var filePath in MyFileSystem.GetFiles(directoryPath, "*", MySearchOption.AllDirectories))
                        {
                            var extension    = Path.GetExtension(filePath);
                            var relativePath = MyFileSystem.MakeRelativePath(Path.Combine(directoryPath, "VisualScripts"), filePath);
                            if (extension == ".vs" || extension == ".vsc")
                            {
                                if (m_relativePathsToAbsolute.ContainsKey(relativePath))
                                {
                                    m_relativePathsToAbsolute[relativePath] = filePath;
                                }
                                else
                                {
                                    m_relativePathsToAbsolute.Add(relativePath, filePath);
                                }
                            }
                        }
                    }
                }
            }

            // Provider will compile all required scripts for the session.
            MyVSAssemblyProvider.Init(m_relativePathsToAbsolute.Values);
            // Retrive the Level script instances
            m_levelScripts = new CachingList <IMyLevelScript>();
            var scriptInstances = MyVSAssemblyProvider.GetLevelScriptInstances();

            if (scriptInstances != null)
            {
                scriptInstances.ForEach(script => m_levelScripts.Add(script));
            }
            m_levelScripts.ApplyAdditions();

            // Store the names of the level scripts
            m_runningLevelScriptNames         = m_levelScripts.Select(x => x.GetType().Name).ToArray();
            m_failedLevelScriptExceptionTexts = new string[m_runningLevelScriptNames.Length];

            // mission manager initialization - state machine definitions
            m_smManager = new MyVSStateMachineManager();
            foreach (var stateMachineFilePath in m_stateMachineDefinitionFilePaths)
            {
                m_smManager.AddMachine(stateMachineFilePath);
            }
        }
Esempio n. 13
0
        public bool StartServer(string instanceName = "", string overridePath = "", bool useConsole = true)
        {
            try
            {
                Sandbox.Engine.Platform.Game.IsDedicated = true;
                MyFileSystem.Reset( );

                //Prepare the parameters
                bool     isUsingInstance = instanceName != string.Empty;
                object[] methodParams    =
                {
                    instanceName,
                    overridePath,
                    isUsingInstance,
                    useConsole
                };

                //Initialize config
                SpaceEngineersGame.SetupPerGameSettings();
                SpaceEngineersGame.SetupBasicGameInfo();
                MyPerGameSettings.SendLogToKeen       = DedicatedServer.SendLogToKeen;
                MyPerServerSettings.GameName          = MyPerGameSettings.GameName;
                MyPerServerSettings.GameNameSafe      = MyPerGameSettings.GameNameSafe;
                MyPerServerSettings.GameDSName        = MyPerServerSettings.GameNameSafe + "Dedicated";
                MyPerServerSettings.GameDSDescription = "Your place for space engineering, destruction and exploring.";
                MyPerServerSettings.AppId             = 0x3bc72;

                //Start the server
                MethodInfo dedicatedServerRunMainMethod = InternalType.GetMethod(DedicatedServerRunMainMethod, BindingFlags.Static | BindingFlags.NonPublic);
                dedicatedServerRunMainMethod.Invoke(null, methodParams);
                ApplicationLog.BaseLog.Info(MyLog.Default.GetFilePath());

                return(true);
            }

            /* these are all redundant
             *          catch ( Win32Exception ex )
             *          {
             *                  ApplicationLog.BaseLog.Error( ex );
             *
             *                  return false;
             *          }
             *          catch ( ExternalException ex )
             *          {
             *                  ApplicationLog.BaseLog.Error( ex );
             *
             *                  return false;
             *          }
             *          catch ( TargetInvocationException ex )
             *          {
             *  //Generally, we won't log this, since it will always be thrown on server stop.
             *  //if ( ExtenderOptions.IsDebugging )
             *      ApplicationLog.BaseLog.Error( ex );
             *  //ApplicationLog.BaseLog.Trace( ex );
             *
             *  return false;
             *          }
             */
            catch (Exception ex)
            {
                ApplicationLog.BaseLog.Error(ex);

                return(false);
            }

            /*
             * finally
             * {
             * _instance = null;
             * Reset();
             * if (_domain != null)
             * {
             *      AppDomain.Unload(_domain);
             * }
             *
             * GC.Collect();
             * GC.WaitForPendingFinalizers();
             * }
             */
        }
Esempio n. 14
0
        public static string SaveScreenshot(Texture tex, string file)
        {
#if !XB1
            MyRender.Log.WriteLine("MyScreenshot.SaveTexture2D() - START");
            MyRender.Log.IncreaseIndent();

            string filename = null;

            using (Texture systemTex = new Texture(MyRender.GraphicsDevice, tex.GetLevelDescription(0).Width, tex.GetLevelDescription(0).Height, 1, Usage.None, Format.A8R8G8B8, Pool.SystemMemory))
            {
                string extension = Path.GetExtension(file);

                using (Surface sourceSurface = tex.GetSurfaceLevel(0))
                    using (Surface destSurface = systemTex.GetSurfaceLevel(0))
                    {
                        MyRender.GraphicsDevice.GetRenderTargetData(sourceSurface, destSurface);
                    }

                try
                {
                    MyRender.Log.WriteLine("File: " + file);

                    Stack <SharpDX.Rectangle> tiles = new Stack <SharpDX.Rectangle>();

                    int tileWidth  = systemTex.GetLevelDescription(0).Width;
                    int tileHeight = systemTex.GetLevelDescription(0).Height;

                    while (tileWidth > 3200)
                    {
                        tileWidth  /= 2;
                        tileHeight /= 2;
                    }

                    int widthOffset  = 0;
                    int heightOffset = 0;

                    while (widthOffset < systemTex.GetLevelDescription(0).Width)
                    {
                        while (heightOffset < systemTex.GetLevelDescription(0).Height)
                        {
                            tiles.Push(new SharpDX.Rectangle(widthOffset, heightOffset, widthOffset + tileWidth, heightOffset + tileHeight));
                            heightOffset += tileHeight;
                        }

                        heightOffset = 0;
                        widthOffset += tileWidth;
                    }

                    bool multipleTiles = tiles.Count > 1;

                    int    sc   = 0;
                    byte[] data = new byte[tileWidth * tileHeight * 4];

                    int sysTexWidth  = systemTex.GetLevelDescription(0).Width;
                    int sysTexHeight = systemTex.GetLevelDescription(0).Height;
                    while (tiles.Count > 0)
                    {
                        SharpDX.Rectangle rect = tiles.Pop();
                        //texture2D.GetData<byte>(0, rect2, data, 0, data.Length);
                        DataStream ds;
                        //DataRectangle dr = texture2D.LockRectangle(0, rect2, LockFlags.ReadOnly, out ds);
                        DataRectangle dr = systemTex.LockRectangle(0, LockFlags.ReadOnly, out ds);

                        //we have to go line by line..
                        ds.Seek(rect.Y * sysTexWidth * 4, SeekOrigin.Begin);
                        int targetOffset = 0;

                        int linesCount = tileHeight;

                        int pixelsBefore = rect.X;
                        int pixelsAfter  = sysTexWidth - tileWidth - rect.X;

                        while (linesCount-- > 0)
                        {
                            if (pixelsBefore > 0)
                            {
                                ds.Seek(pixelsBefore * 4, SeekOrigin.Current);
                            }

                            ds.Read(data, targetOffset, tileWidth * 4);
                            targetOffset += tileWidth * 4;

                            if (pixelsAfter > 0 && linesCount > 0)
                            {
                                ds.Seek(pixelsAfter * 4, SeekOrigin.Current);
                            }
                        }

                        systemTex.UnlockRectangle(0);
                        filename = file;

                        if (multipleTiles)
                        {
                            filename = file.Replace(extension, "_" + sc.ToString("##00") + extension);
                        }

                        using (var stream = MyFileSystem.OpenWrite(MyFileSystem.UserDataPath, filename))
                        {
                            using (System.Drawing.Bitmap image = new System.Drawing.Bitmap(tileWidth, tileHeight))
                            {
                                System.Drawing.Imaging.BitmapData imageData = image.LockBits(new System.Drawing.Rectangle(0, 0, tileWidth, tileHeight), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                                System.Runtime.InteropServices.Marshal.Copy(data, 0, imageData.Scan0, data.Length);

                                if (extension == ".png")
                                {
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                                }
                                else if (extension == ".jpg" || extension == ".jpeg")
                                {
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                                else if (extension == ".bmp")
                                {
                                    image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                                }
                                else
                                {
                                    throw new InvalidOperationException("Invalid file extension: " + extension + ", please use png, jpg or bmp");
                                }

                                image.UnlockBits(imageData);
                            }

                            //texture2D.SaveAsPng(stream, texture2D.Width, texture2D.Height);
                            //BaseTexture.ToStream(texture2D, ImageFileFormat.Png);
                        }

                        sc++;
                        GC.Collect();
                    }
                }
                catch (Exception exc)
                {
                    //  Write exception to log, but continue as if nothing wrong happened
                    MyRender.Log.WriteLine(exc);
                    filename = null;
                }
            }
            //BaseTexture.ToFile(texture2D, "c:\\test.png", ImageFileFormat.Png);

            MyRender.Log.DecreaseIndent();
            MyRender.Log.WriteLine("MyScreenshot.SaveTexture2D() - END");

            return(filename);
#else
            System.Diagnostics.Debug.Assert(false, "Not Screenshoot support on XB1 yet!");
            return(null);
#endif
        }
Esempio n. 15
0
        private MyLocalizationContext LoadLocalizationFile(string filePath, MyStringId bundleId, bool disposableContext = false)
        {
            MyStringId fileContextId = MyStringId.NullOrEmpty;
            string     fileLanguage  = null;
            ulong      fileId        = UInt64.MaxValue;
            bool?      fileIsDefault = null;
            bool       valid         = false;

            if (!MyFileSystem.FileExists(filePath))
            {
                return(null);
            }


            try
            {
                // Just reading part of the file. This does not parse it whole.
                int missedThreshold = 3;
                int missed          = 0;
                using (XmlReader reader = XmlReader.Create(filePath))
                {
                    while (reader.Read())
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            switch (reader.Name)
                            {
                            case "Context":
                                reader.Read();
                                fileContextId = MyStringId.GetOrCompute(reader.Value);
                                break;

                            case "Language":
                                reader.Read();
                                fileLanguage = reader.Value;
                                break;

                            case "Id":
                                reader.Read();
                                fileId = ulong.Parse(reader.Value);
                                break;

                            case "Default":
                                reader.Read();
                                fileIsDefault = bool.Parse(reader.Value);
                                break;

                            default:
                                // Stop reading, not worth it
                                if (missed > missedThreshold)
                                {
                                    return(null);
                                }

                                missed++;
                                break;
                            }
                        }

                        if (fileContextId != MyStringId.NullOrEmpty &&
                            fileLanguage != null &&
                            fileId != UInt64.MaxValue &&
                            fileIsDefault.HasValue)
                        {
                            valid = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                valid = false;
                Debug.Fail(e.ToString());
            }

            if (valid)
            {
                var context = CreateOrGetContext(fileContextId, disposableContext);

                // insert the data to context
                context.InsertFileInfo(
                    new MyLocalizationContext.LocalizationFileInfo(fileLanguage, filePath, fileId, fileIsDefault.Value, bundleId));

                return(context);
            }

            return(null);
        }
Esempio n. 16
0
        // Starts new session with campaign data
        public void LoadSessionFromActiveCampaign(string relativePath, Action afterLoad = null, string campaignDirectoryName = null)
        {
            var    savePath = relativePath;
            string absolutePath;

            // >> WORLD FILE OPERATIONS
            // Find the existing file in order of modded content to vanilla
            if (m_activeCampaign.IsVanilla)
            {
                absolutePath = Path.Combine(MyFileSystem.ContentPath, savePath);

                if (!MyFileSystem.FileExists(absolutePath))
                {
                    MySandboxGame.Log.WriteLine("ERROR: Missing vanilla world file in campaign: " + m_activeCampaignName);
                    Debug.Fail("ERROR: Missing vanilla world file in campaign: " + m_activeCampaignName);
                    return;
                }
            }
            else
            {
                // Modded content
                absolutePath = Path.Combine(m_activeCampaign.ModFolderPath, savePath);
                // try finding respective vanilla file if the file does not exist
                if (!MyFileSystem.FileExists(absolutePath))
                {
                    absolutePath = Path.Combine(MyFileSystem.ContentPath, savePath);
                    if (!MyFileSystem.FileExists(absolutePath))
                    {
                        MySandboxGame.Log.WriteLine("ERROR: Missing world file in campaign: " + m_activeCampaignName);
                        Debug.Fail("ERROR: Missing world file in campaign: " + m_activeCampaignName);
                        return;
                    }
                }
            }

            // Copy the save and load the session
            if (string.IsNullOrEmpty(campaignDirectoryName))
            {
                campaignDirectoryName = ActiveCampaignName + " " + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
            }

            var directory       = new DirectoryInfo(Path.GetDirectoryName(absolutePath));
            var targetDirectory = Path.Combine(MyFileSystem.SavesPath, campaignDirectoryName, directory.Name);

            while (MyFileSystem.DirectoryExists(targetDirectory))
            {
                // Finid new unique name for the folder
                targetDirectory = Path.Combine(MyFileSystem.SavesPath, directory.Name + " " + MyUtils.GetRandomInt(int.MaxValue).ToString("########"));
            }
            MyUtils.CopyDirectory(directory.FullName, targetDirectory);

            // >> LOCALIZATION
            // Set localization for loaded level in the after load event
            if (string.IsNullOrEmpty(m_selectedLanguage))
            {
                m_selectedLanguage = m_activeCampaign.DefaultLocalizationLanguage;

                if (string.IsNullOrEmpty(m_selectedLanguage) && m_activeCampaign.LocalizationLanguages.Count > 0)
                {
                    m_selectedLanguage = m_activeCampaign.LocalizationLanguages[0];
                }
            }

            if (!string.IsNullOrEmpty(m_selectedLanguage))
            {
                // Initilize the sessionComponent in after load event
                afterLoad += () =>
                {
                    var comp = MySession.Static.GetComponent <MyLocalizationSessionComponent>();
                    comp.LoadCampaignLocalization(m_activeCampaign.LocalizationPaths, m_activeCampaign.ModFolderPath);
                    comp.SwitchLanguage(m_selectedLanguage);
                };
            }

            // ATM only single player campaigns are supported
            if (!m_activeCampaign.IsMultiplayer)
            {
                MySessionLoader.LoadSingleplayerSession(targetDirectory, afterLoad);
            }
        }
Esempio n. 17
0
        static void RunInternal(string[] args)
        {
            using (MySteamService steamService = new MySteamService(MySandboxGame.IsDedicated, AppId))
            {
                IMyRender renderer = null;

                SpaceEngineersGame.SetupPerGameSettings();

                if (MySandboxGame.IsDedicated)
                {
                    renderer = new MyNullRender();
                }
                else if (MyFakes.ENABLE_DX11_RENDERER)
                {
                    var rendererId = MySandboxGame.Config.GraphicsRenderer;
                    if (rendererId == MySandboxGame.DirectX11RendererKey)
                    {
                        renderer = new MyDX11Render();
                        if (!renderer.IsSupported)
                        {
                            MySandboxGame.Log.WriteLine("DirectX 11 renderer not supported. Reverting to DirectX 9.");
                            renderer = null;
                        }
                    }

                    if (renderer == null)
                    {
                        renderer   = new MyDX9Render();
                        rendererId = MySandboxGame.DirectX9RendererKey;
                    }

                    MySandboxGame.Config.GraphicsRenderer = rendererId;
                }
                else
                {
                    renderer = new MyDX9Render();
                }

                MyFakes.ENABLE_PLANETS &= MySandboxGame.Config.GraphicsRenderer != MySandboxGame.DirectX9RendererKey;

                VRageRender.MyRenderProxy.Initialize(renderer);

                VRageRender.MyRenderProxy.IS_OFFICIAL = MyFinalBuildConstants.IS_OFFICIAL;
                VRageRender.MyRenderProxy.GetRenderProfiler().SetAutocommit(false);
                VRageRender.MyRenderProxy.GetRenderProfiler().InitMemoryHack("MainEntryPoint");
                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyProgram.Init");
                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MySteam.Init()");

                if (!MySandboxGame.IsDedicated)
                {
                    if (steamService.IsActive)
                    {
                        steamService.SetNotificationPosition(MySteamService.NotificationPosition.TopLeft);

                        MySandboxGame.Log.WriteLineAndConsole("Steam.IsActive: " + steamService.IsActive);
                        MySandboxGame.Log.WriteLineAndConsole("Steam.IsOnline: " + steamService.IsOnline);
                        MySandboxGame.Log.WriteLineAndConsole("Steam.OwnsGame: " + steamService.OwnsGame);
                        MySandboxGame.Log.WriteLineAndConsole("Steam.UserId: " + steamService.UserId);
                        MySandboxGame.Log.WriteLineAndConsole("Steam.UserName: "******"[n/a]");
                        MySandboxGame.Log.WriteLineAndConsole("Steam.Branch: " + steamService.BranchName ?? "[n/a]");
                        MySandboxGame.Log.WriteLineAndConsole("Build date: " + MySandboxGame.BuildDateTime.ToString("yyyy-MM-dd hh:mm", CultureInfo.InvariantCulture));
                        MySandboxGame.Log.WriteLineAndConsole("Build version: " + MySandboxGame.BuildVersion.ToString());
                    }
                    else if (MyFinalBuildConstants.IS_OFFICIAL) //We dont need Steam only in VS
                    {
                        if (!(steamService.IsActive && steamService.OwnsGame))
                        {
                            if (MyFakes.ENABLE_RUN_WITHOUT_STEAM == false)
                            {
                                MessageBoxWrapper("Steam is not running!", "Please run this game from Steam." + Environment.NewLine + "(restart Steam if already running)");
                                return;
                            }
                        }
                    }
                    else
                    {
                        if (!(steamService.IsActive && steamService.OwnsGame))
                        {
                            if (MyFakes.ENABLE_RUN_WITHOUT_STEAM == false)
                            {
                                MessageBoxWrapper("Steam is not running!", "Game might be unstable when run without Steam!");
                            }
                        }
                    }
                }

                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

                VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("new MySandboxGame()");

                VRageGameServices services = new VRageGameServices(steamService);

                if (!MySandboxGame.IsDedicated)
                {
                    MyFileSystem.InitUserSpecific(steamService.UserId.ToString());
                }

                using (MySandboxGame game = new MySandboxGame(services, args))
                {
                    VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                    VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                    game.Run(disposeSplashScreen: DisposeSplashScreen);
                }
            }
        }
Esempio n. 18
0
        public MyInMemoryWave GetStreamedWave(string filename, MySoundData cue, MySoundDimensions dim = MySoundDimensions.D2)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return(null);
            }

            SharpDX.Multimedia.WaveFormatEncoding encoding = SharpDX.Multimedia.WaveFormatEncoding.Unknown;
            var fsPath = Path.IsPathRooted(filename) ? filename : Path.Combine(MyFileSystem.ContentPath, "Audio", filename);
            var exists = MyFileSystem.FileExists(fsPath);

            if (exists)
            {
                try
                {
                    MyInMemoryWave wave;
                    if (!LoadedStreamedWaves.TryGetValue(fsPath, out wave))
                    {
                        wave = LoadedStreamedWaves[fsPath] = new MyInMemoryWave(cue, fsPath, this, true);
                    }
                    else
                    {
                        wave.Reference();
                    }

                    // check the formats
                    if (encoding == SharpDX.Multimedia.WaveFormatEncoding.Unknown)
                    {
                        encoding = wave.WaveFormat.Encoding;
                    }

                    // check the formats
                    if (wave.WaveFormat.Encoding == SharpDX.Multimedia.WaveFormatEncoding.Unknown)
                    {
                        if (MyAudio.OnSoundError != null)
                        {
                            var msg = string.Format("Unknown audio encoding '{0}', '{1}'", cue.SubtypeId.ToString(), filename);
                            MyAudio.OnSoundError(cue, msg);
                        }
                        return(null);
                    }

                    // 3D sounds must be mono
                    if (dim == MySoundDimensions.D3 && wave.WaveFormat.Channels != 1)
                    {
                        if (MyAudio.OnSoundError != null)
                        {
                            var msg = string.Format("3D sound '{0}', '{1}' must be in mono, got {2} channels", cue.SubtypeId.ToString(), filename, wave.WaveFormat.Channels);
                            MyAudio.OnSoundError(cue, msg);
                        }
                        return(null);
                    }

                    // all parts of the sound must have the same encoding
                    if (wave.WaveFormat.Encoding != encoding)
                    {
                        if (MyAudio.OnSoundError != null)
                        {
                            var msg = string.Format("Inconsistent sound encoding in '{0}', '{1}', got '{2}', expected '{3}'", cue.SubtypeId.ToString(), filename, wave.WaveFormat.Encoding, encoding);
                            MyAudio.OnSoundError(cue, msg);
                        }
                        return(null);
                    }

                    return(wave);
                }
                catch (Exception e)
                {
                    if (MyAudio.OnSoundError != null)
                    {
                        var msg = string.Format("Unable to load audio file: '{0}', '{1}': {2}", cue.SubtypeId.ToString(), filename, e.ToString());
                        MyAudio.OnSoundError(cue, msg);
                    }
                    return(null);
                }
            }
            else
            {
                if (MyAudio.OnSoundError != null)
                {
                    var msg = string.Format("Unable to find audio file: '{0}', '{1}'", cue.SubtypeId.ToString(), filename);
                    MyAudio.OnSoundError(cue, msg);
                }
            }
            return(null);
        }
Esempio n. 19
0
        public static MyStorageBase LoadFromFile(string absoluteFilePath, byte[] materialChangeFrom = null, byte[] materialChangeTo = null)
        {
            //get hash code
            MyVoxelObjectDefinition definition;

            definition.filePath           = absoluteFilePath;
            definition.materialChangeFrom = materialChangeFrom;
            definition.materialChangeTo   = materialChangeTo;
            int sh = definition.GetHashCode();

            MyStorageBase result = null;

            if (UseStorageCache)
            {
                result = m_storageCache.Read(sh);
                if (result != null)
                {
                    result.Shared = true;
                    return(result);
                }
            }

            const string loadingMessage = "Loading voxel storage from file '{0}'";

            if (!MyFileSystem.FileExists(absoluteFilePath))
            {
                var oldPath = Path.ChangeExtension(absoluteFilePath, "vox");
                MySandboxGame.Log.WriteLine(string.Format(loadingMessage, oldPath));
                UpdateFileFormat(oldPath);
                Debug.Assert(MyFileSystem.FileExists(absoluteFilePath));
            }
            else
            {
                MySandboxGame.Log.WriteLine(string.Format(loadingMessage, absoluteFilePath));
            }
            Debug.Assert(absoluteFilePath.EndsWith(MyVoxelConstants.FILE_EXTENSION));


            byte[] compressedData = null;
            using (var file = MyFileSystem.OpenRead(absoluteFilePath))
            {
                compressedData = new byte[file.Length];
                file.Read(compressedData, 0, compressedData.Length);
            }

            result = Load(compressedData);

            //change materials
            result.ChangeMaterials(definition.materialChangeFrom, definition.materialChangeTo);

            if (UseStorageCache)
            {
                m_storageCache.Write(sh, result);
                result.Shared = true;
            }
            else
            {
                m_storageCache.Reset();
            }

            return(result);
        }
Esempio n. 20
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return(null);
            }

            if (!(value is string))
            {
                throw new NotSupportedException(string.Format("{0} cannot convert from {1}.", GetType().FullName, value.GetType().FullName));
            }

            var  sizeParameter = parameter as string;
            var  sizeArray     = sizeParameter?.Split(',');
            int  width         = -1;
            int  height        = -1;
            bool noAlpha       = false;

            if (sizeArray.Length > 0)
            {
                int.TryParse(sizeArray[0], out width);
            }

            if (sizeArray.Length > 1)
            {
                int.TryParse(sizeArray[1], out height);
            }

            if (sizeArray.Length > 2)
            {
                noAlpha = sizeArray[2].Equals("noalpha", StringComparison.OrdinalIgnoreCase);
            }

            var filename  = (string)value;
            var extension = Path.GetExtension(filename).ToLower();
            var name      = filename;

            if (width != -1 && height != -1)
            {
                name += string.Format(",{0},{1}", width, height);
            }

            if (Cache.ContainsKey(name))
            {
                return(Cache[name]);
            }

            if (extension == ".png")
            {
                try
                {
                    // TODO: rescale the bitmap to specified width/height.
                    var bitmapImage = new BitmapImage();
                    using (Stream textureStream = MyFileSystem.OpenRead(filename))
                    {
                        var bitmap = (Bitmap)Image.FromStream(textureStream, true);
                        using (var ms = new MemoryStream())
                        {
                            bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                            bitmapImage.BeginInit();
                            bitmapImage.StreamSource = ms;
                            bitmapImage.CacheOption  = BitmapCacheOption.OnLoad;
                            bitmapImage.EndInit();
                        }
                    }
                    Cache.Add(name, bitmapImage);
                    return(bitmapImage);
                }
                catch { return(null); }
            }

            if (extension == ".dds")
            {
                ImageSource image;
                using (Stream textureStream = MyFileSystem.OpenRead(filename))
                {
                    image = ImageTextureUtil.CreateImage(textureStream, 0, width, height, noAlpha);
                }
                Cache.Add(name, image);
                return(image);
            }

            return(null);
        }
Esempio n. 21
0
        protected MyEffectBase(string asset)
        {
            string sourceFX   = asset + ".fx";
            string compiledFX = asset + ".fxo";

            var srcPath = Path.Combine(MyFileSystem.ContentPath, sourceFX);
            var comPath = Path.Combine(MyFileSystem.ContentPath, compiledFX);

            var srcAbsolute = srcPath;

            bool needRecompile = false;

            if (File.Exists(comPath))
            {
                if (File.Exists(srcPath) && !MyRenderProxy.IS_OFFICIAL)
                {
                    var compiledTime = File.GetLastWriteTime(comPath);
                    var sourceTime   = File.GetLastWriteTime(srcAbsolute);

                    m_includeProcessor.Reset(Path.GetDirectoryName(srcAbsolute));
                    ShaderBytecode.PreprocessFromFile(srcAbsolute, null, m_includeProcessor);
                    sourceTime = m_includeProcessor.MostUpdateDateTime > sourceTime ? m_includeProcessor.MostUpdateDateTime : sourceTime;

                    if (sourceTime > compiledTime)
                    {
                        needRecompile = true;
                    }
                }
            }
            else
            {
                if (File.Exists(srcPath))
                {
                    needRecompile = true;
                }
                else
                {
                    throw new FileNotFoundException("Effect not found: " + asset);
                }
            }

            ShaderFlags flags = ShaderFlags.OptimizationLevel3 | ShaderFlags.PartialPrecision | ShaderFlags.SkipValidation;

            if (needRecompile)
            {
//#if DEBUG
//                flags |= ShaderFlags.Debug;
//#endif
                //m_D3DEffect = Effect.FromFile(MySandboxGameDX.Static.GraphicsDevice, sourceFX, flags);

                try
                {
                    var srcDir = Path.GetDirectoryName(srcAbsolute);
                    m_includeProcessor.Reset(srcDir);
                    var result = ShaderBytecode.CompileFromFile(srcAbsolute, "fx_2_0", flags, null, m_includeProcessor);

                    ShaderBytecode shaderByteCode = result;
                    shaderByteCode.Save(Path.Combine(srcDir, Path.GetFileNameWithoutExtension(srcAbsolute) + ".fxo"));
                    result.Dispose();
                }
                catch (Exception e)
                {
                    Debug.Fail(e.Message);
                    throw;
                }
            }

            using (var fs = MyFileSystem.OpenRead(comPath))
            {
                byte[] m = new byte[fs.Length];
                fs.Read(m, 0, (int)fs.Length);

                m_D3DEffect = Effect.FromMemory(MyRender.GraphicsDevice, m, flags);
            }
            Init();
        }
Esempio n. 22
0
        public bool Add(MySoundData cue, MyAudioWave cueWave)
        {
            string[] files = { cueWave.Start, cueWave.Loop, cueWave.End };
            SharpDX.Multimedia.WaveFormatEncoding encoding = SharpDX.Multimedia.WaveFormatEncoding.Unknown;
            bool result = true;
            int  i      = 0;

            foreach (var waveFilename in files)
            {
                i++;
                if (string.IsNullOrEmpty(waveFilename))
                {
                    continue;
                }

                var fsPath = Path.IsPathRooted(waveFilename) ? waveFilename : Path.Combine(MyFileSystem.ContentPath, "Audio", waveFilename);
                var exists = MyFileSystem.FileExists(fsPath);
                result |= exists;
                if (exists)
                {
                    try
                    {
                        MyInMemoryWave wave = new MyInMemoryWave(cue, fsPath);
                        if (i != 2)
                        {
                            wave.Buffer.LoopCount = 0;
                        }
                        m_waves[waveFilename] = wave;

                        // check the formats
                        if (encoding == SharpDX.Multimedia.WaveFormatEncoding.Unknown)
                        {
                            encoding = wave.WaveFormat.Encoding;
                        }

                        // check the formats
                        if (wave.WaveFormat.Encoding == SharpDX.Multimedia.WaveFormatEncoding.Unknown)
                        {
                            if (MyAudio.OnSoundError != null)
                            {
                                var msg = string.Format("Unknown audio encoding '{0}', '{1}'", cue.SubtypeId.ToString(), waveFilename);
                                MyAudio.OnSoundError(cue, msg);
                            }
                            result = false;
                        }

                        // 3D sounds must be mono
                        if (cueWave.Type == MySoundDimensions.D3 && wave.WaveFormat.Channels != 1)
                        {
                            if (MyAudio.OnSoundError != null)
                            {
                                var msg = string.Format("3D sound '{0}', '{1}' must be in mono, got {2} channels", cue.SubtypeId.ToString(), waveFilename, wave.WaveFormat.Channels);
                                MyAudio.OnSoundError(cue, msg);
                            }
                            result = false;
                        }

                        // all parts of the sound must have the same encoding
                        if (wave.WaveFormat.Encoding != encoding)
                        {
                            if (MyAudio.OnSoundError != null)
                            {
                                var msg = string.Format("Inconsistent sound encoding in '{0}', '{1}', got '{2}', expected '{3}'", cue.SubtypeId.ToString(), waveFilename, wave.WaveFormat.Encoding, encoding);
                                MyAudio.OnSoundError(cue, msg);
                            }
                            result = false;
                        }
                    }
                    catch (Exception e)
                    {
                        if (MyAudio.OnSoundError != null)
                        {
                            var msg = string.Format("Unable to load audio file: '{0}', '{1}': {2}", cue.SubtypeId.ToString(), waveFilename, e.ToString());
                            MyAudio.OnSoundError(cue, msg);
                        }
                        result = false;
                    }
                    // Second catch shouldn't be needed according to http://stackoverflow.com/questions/5345436/net-exception-catch-block
                    // all non-exceptions will be wrapped as type derived from Exception and caught above.
                    //catch
                    //{
                    //    if (MyAudio.OnSoundError != null)
                    //    {
                    //        var msg = string.Format("Unable to load audio file: '{0}', '{1}': {2}", cue.SubtypeId.ToString(), waveFilename, "Something went horribly wrong");
                    //        MyAudio.OnSoundError(cue, msg);
                    //    }
                    //    result = false;
                    //}
                }
                else
                {
                    if (MyAudio.OnSoundError != null)
                    {
                        var msg = string.Format("Unable to find audio file: '{0}', '{1}'", cue.SubtypeId.ToString(), waveFilename);
                        MyAudio.OnSoundError(cue, msg);
                    }
                    result = false;
                }
            }
            return(result);
        }
Esempio n. 23
0
 // Get back to selection of instance
 private void getBackButton_Click(object sender, EventArgs e)
 {
     HasToExit = true;
     MyFileSystem.Reset();
     Close();
 }
Esempio n. 24
0
        public static void MainBootstrap(string[] args)
        {
            var rootContentPath = args[0];

            MyLog.Default = new MyLog();
            MyFileSystem.Init(rootContentPath, "./");
            MyLanguage.Init();
            MyRenderProxy.Initialize(new MyNullRender());
            MyLog.Default.Init("converter.log", new StringBuilder());
            Workers.Init(new WorkerConfigurationFactory()
                         .AddGroup(new WorkerConfigurationFactory.Group
            {
                Id       = WorkerGroup.Background,
                Min      = 1,
                Priority = ThreadPriority.BelowNormal,
                Ratio    = .1f
            })
                         .AddGroup(new WorkerConfigurationFactory.Group
            {
                Id       = WorkerGroup.Logic,
                Min      = 1,
                Priority = ThreadPriority.Normal,
                Ratio    = .7f
            })
                         .AddGroup(new WorkerConfigurationFactory.Group
            {
                Id       = WorkerGroup.Render,
                Min      = 1,
                Priority = ThreadPriority.AboveNormal,
                Ratio    = .2f
            })
                         .SetDefault(WorkerGroup.Logic)
                         .Bake(32));

            MyMetadataSystem.LoadAssemblies(new[]
            {
                "VRage",
                "VRage.Game",
                "Sandbox.Graphics",
                "Sandbox.Game",
                "MedievalEngineers.ObjectBuilders",
                "MedievalEngineers.Game"
            }.Select(Assembly.Load));

            var config = (BlockVariantGeneratorConfig) new XmlSerializer(typeof(BlockVariantGeneratorConfig)).Deserialize(File.OpenText(args[1]));

            Console.WriteLine("Loading definitions...");

            MyDefinitionManagerSandbox.Static.LoadData(new ListReader <MyModContext>(new List <MyModContext>(config.ContentRoots.Select(contentPath =>
                                                                                                                                        new MyModContext(Path.GetFileNameWithoutExtension(contentPath), Path.GetFileNameWithoutExtension(contentPath), contentPath)))));
            MyFileSystem.SetAdditionalContentPaths(config.ContentRoots);
            Console.WriteLine("Processing definitions...");
            DefinitionObLoader.LoadObjectBuilders(MyDefinitionManagerSandbox.Static.DefinitionSet);

            Console.WriteLine("Translating definitions...");
            var translatedSet   = new DefinitionObSet();
            var modelTranslator = new ModelAssetTranslator(config.OutputDirectory, config.VariantName);
            Func <string, string> assetTranslator = (asset) =>
            {
                if (string.IsNullOrWhiteSpace(asset))
                {
                    return(asset);
                }
                if (config.AssetTranslations.TryGetValue(asset, out var assetTranslation))
                {
                    return(assetTranslation);
                }
                if (asset.EndsWith(".mwm", StringComparison.OrdinalIgnoreCase) && config.Changes != null)
                {
                    if (asset.Contains("GeneratedStoneEdge"))
                    {
                        Debugger.Break();
                    }
                    var modelMaterials = modelTranslator.GetMaterialsForModel(asset);
                    using (PoolManager.Get(out List <MyObjectBuilder_EquiModifierChangeMaterialDefinition.MaterialModifier> changes))
                    {
                        foreach (var x in config.Changes)
                        {
                            if (modelMaterials.Contains(x.Name))
                            {
                                changes.Add(x);
                            }
                        }
                        if (changes.Count > 0)
                        {
                            Console.WriteLine("Translating model " + asset);
                            using (var builder = MaterialEditsBuilder.Allocate())
                            {
                                foreach (var k in changes)
                                {
                                    var list = new List <MaterialEdit>();
                                    k.GetChanges(list);
                                    builder.Add(k.Name, list);
                                }

                                return(modelTranslator.CreateModel(asset, builder));
                            }
                        }
                    }
                }

                return(asset);
            };
            var translator = new DefinitionObTranslator(
                DefinitionObLoader.Loaded,
                translatedSet,
                assetTranslator,
                (displayName) => $"{displayName} ({config.VariantName})",
                "_" + config.VariantName,
                config.Translations);

            foreach (var id in config.DefinitionsToTranslate)
            {
                if (id.SubtypeName == "**any**")
                {
                    // Find and translate ALL with the given type ID, not forcing
                    foreach (var k in DefinitionObLoader.Loaded.AllDefinitions)
                    {
                        if (k.Id.TypeId == id.TypeId)
                        {
                            translator.Translate(k);
                        }
                    }
                }
                else if (id.SubtypeName == "**any_translated_model**")
                {
                    var ids = new HashSet <MyDefinitionId>();
                    foreach (var k in DefinitionObLoader.Loaded.AllDefinitions)
                    {
                        if (k.Id.TypeId == id.TypeId && k is MyObjectBuilder_PhysicalModelDefinition physModel)
                        {
                            var originalModel   = physModel.Model;
                            var translatedModel = assetTranslator(originalModel);
                            if (!originalModel.Equals(translatedModel))
                            {
                                ids.Add(k.Id);
                            }
                        }
                    }

                    // Include variants that contain the blocks
                    foreach (var k in DefinitionObLoader.Loaded.AllDefinitions.OfType <MyObjectBuilder_BlockVariantsDefinition>())
                    {
                        var good = false;
                        foreach (var e in k.Blocks)
                        {
                            if (ids.Contains(e))
                            {
                                good = true;
                                break;
                            }
                        }

                        if (good)
                        {
                            ids.Add(k.Id);
                        }
                    }

                    foreach (var sid in ids)
                    {
                        foreach (var def in DefinitionObLoader.Loaded.GetDefinitions(sid))
                        {
                            translator.Translate(def, true);
                        }
                    }
                }
                else
                {
                    var list = DefinitionObLoader.Loaded.GetDefinitions(id);
                    if (list.Count == 0)
                    {
                        Console.WriteLine("Couldn't find any definitions with ID " + id);
                    }
                    foreach (var def in list)
                    {
                        translator.Translate(def, true);
                    }
                }
            }

            var definitionSet = new MyObjectBuilder_Definitions
            {
                Definitions = new MySerializableList <MyObjectBuilder_DefinitionBase>(translatedSet.AllDefinitions.OrderBy(x => x.TypeId.ToString())
                                                                                      .ThenBy(x => x.SubtypeName))
            };

            XDocument doc;

            using (var baseWriter = new StringWriter())
            {
                var serializer = new XmlSerializer(typeof(MyObjectBuilder_Definitions));
                using (var writer = new XmlTextWriter(baseWriter))
                    serializer.Serialize(writer, definitionSet);
                doc = XDocument.Load(new StringReader(baseWriter.ToString()));
            }

            NullCleaner.Clean(doc);
            var translatedSbcPath = Path.Combine(config.OutputDirectory, "Data/Translated.sbc");

            Directory.CreateDirectory(Path.GetDirectoryName(translatedSbcPath));
            using (var writer = new XmlTextWriter(translatedSbcPath, Encoding.UTF8)
            {
                Formatting = Formatting.Indented,
                Indentation = 2
            })

                doc.WriteTo(writer);

            MyLog.Default.Dispose();
        }
Esempio n. 25
0
        MyRenderMeshInfo LoadMesh(string assetName, out MyLODDescriptor[] LodDescriptors)
        {
            //Debug.Assert(assetName.EndsWith(".mwm"));
            #region Temporary for mwm endings
            if (!assetName.EndsWith(".mwm"))
            {
                assetName += ".mwm";
            }
            #endregion

            var meshVertexInput = MyVertexInputLayout.Empty;
            LodDescriptors = null;
            MyRenderMeshInfo result = new MyRenderMeshInfo();

            var importer = new MyModelImporter();
            var fsPath   = Path.IsPathRooted(assetName) ? assetName : Path.Combine(MyFileSystem.ContentPath, assetName);

            if (!MyFileSystem.FileExists(fsPath))
            {
                System.Diagnostics.Debug.Fail("Model " + assetName + " does not exists!");

                return(MyAssetsLoader.GetDebugMesh().LODs[0].m_meshInfo);
            }


            string contentPath = null;
            if (Path.IsPathRooted(assetName) && assetName.ToLower().Contains("models"))
            {
                contentPath = assetName.Substring(0, assetName.ToLower().IndexOf("models"));
            }

            try
            {
                importer.ImportData(fsPath, new string[]
                {
                    MyImporterConstants.TAG_VERTICES,
                    MyImporterConstants.TAG_BLENDINDICES,
                    MyImporterConstants.TAG_BLENDWEIGHTS,
                    MyImporterConstants.TAG_NORMALS,
                    MyImporterConstants.TAG_TEXCOORDS0,
                    MyImporterConstants.TAG_TANGENTS,
                    MyImporterConstants.TAG_BINORMALS,
                    MyImporterConstants.TAG_BONES,
                    MyImporterConstants.TAG_MESH_PARTS,
                    MyImporterConstants.TAG_BOUNDING_BOX,
                    MyImporterConstants.TAG_BOUNDING_SPHERE,
                    MyImporterConstants.TAG_LODS,
                });
                Dictionary <string, object> tagData = importer.GetTagData();

                // extract data
                var positions = (HalfVector4[])tagData[MyImporterConstants.TAG_VERTICES];
                System.Diagnostics.Debug.Assert(positions.Length > 0);
                var verticesNum     = positions.Length;
                var boneIndices     = (Vector4I[])tagData[MyImporterConstants.TAG_BLENDINDICES];
                var boneWeights     = (Vector4[])tagData[MyImporterConstants.TAG_BLENDWEIGHTS];
                var normals         = (Byte4[])tagData[MyImporterConstants.TAG_NORMALS];
                var texcoords       = (HalfVector2[])tagData[MyImporterConstants.TAG_TEXCOORDS0];
                var tangents        = (Byte4[])tagData[MyImporterConstants.TAG_TANGENTS];
                var bintangents     = (Byte4[])tagData[MyImporterConstants.TAG_BINORMALS];
                var tangentBitanSgn = new Byte4[verticesNum];
                for (int i = 0; i < verticesNum; i++)
                {
                    var N = VF_Packer.UnpackNormal(normals[i].PackedValue);
                    var T = VF_Packer.UnpackNormal(tangents[i].PackedValue);
                    var B = VF_Packer.UnpackNormal(bintangents[i].PackedValue);

                    var tanW = new Vector4(T.X, T.Y, T.Z, 0);

                    tanW.W             = T.Cross(N).Dot(B) < 0 ? -1 : 1;
                    tangentBitanSgn[i] = VF_Packer.PackTangentSignB4(ref tanW);
                }
                bool hasBonesInfo = false;
                if (boneIndices.Length > 0 && boneWeights.Length > 0)
                {
                    hasBonesInfo = true;
                }
                var bones = (MyModelBone[])tagData[MyImporterConstants.TAG_BONES];

                //
                var           vertexBuffers = new List <VertexBufferId>();
                IndexBufferId indexBuffer   = IndexBufferId.NULL;
                var           submeshes     = new Dictionary <string, List <MyDrawSubmesh> >();
                var           submeshes2    = new Dictionary <string, List <MySubmeshInfo> >();
                var           submeshesMeta = new List <MySubmeshInfo>();

                int  indicesNum      = 0;
                bool missingMaterial = false;
                if (tagData.ContainsKey(MyImporterConstants.TAG_MESH_PARTS))
                {
                    var  indices  = new List <uint>(positions.Length);
                    uint maxIndex = 0;

                    var meshParts = tagData[MyImporterConstants.TAG_MESH_PARTS] as List <MyMeshPartInfo>;
                    foreach (MyMeshPartInfo meshPart in meshParts)
                    {
                        # region Bones indirection
                        int[] bonesRemapping = null;
                        if (boneIndices.Length > 0 && bones.Length > MyRender11Constants.SHADER_MAX_BONES)
                        {
                            Dictionary <int, int> vertexChanged = new Dictionary <int, int>();

                            Dictionary <int, int> bonesUsed = new Dictionary <int, int>();

                            int trianglesNum = meshPart.m_indices.Count / 3;
                            for (int i = 0; i < trianglesNum; i++)
                            {
                                for (int j = 0; j < 3; j++)
                                {
                                    int index = meshPart.m_indices[i * 3 + j];
                                    if (boneWeights[index].X > 0)
                                    {
                                        bonesUsed[boneIndices[index].X] = 1;
                                    }
                                    if (boneWeights[index].Y > 0)
                                    {
                                        bonesUsed[boneIndices[index].Y] = 1;
                                    }
                                    if (boneWeights[index].Z > 0)
                                    {
                                        bonesUsed[boneIndices[index].Z] = 1;
                                    }
                                    if (boneWeights[index].W > 0)
                                    {
                                        bonesUsed[boneIndices[index].W] = 1;
                                    }
                                }
                            }

                            if (bonesUsed.Count > MyRender11Constants.SHADER_MAX_BONES)
                            {
                                Debug.Assert(bonesUsed.Count <= MyRender11Constants.SHADER_MAX_BONES, "Model \"" + assetName + "\"'s part uses more than 60 bones, please split model on more parts");
                            }

                            var partBones = new List <int>(bonesUsed.Keys);
                            partBones.Sort();
                            if (partBones.Count > 0 && partBones[partBones.Count - 1] >= MyRender11Constants.SHADER_MAX_BONES)
                            {
                                for (int i = 0; i < partBones.Count; i++)
                                {
                                    bonesUsed[partBones[i]] = i;
                                }

                                Dictionary <int, int> vertexTouched = new Dictionary <int, int>();

                                for (int i = 0; i < trianglesNum; i++)
                                {
                                    for (int j = 0; j < 3; j++)
                                    {
                                        int index = meshPart.m_indices[i * 3 + j];
                                        if (!vertexTouched.ContainsKey(index))
                                        {
                                            if (boneWeights[index].X > 0)
                                            {
                                                boneIndices[index].X = bonesUsed[boneIndices[index].X];
                                            }
                                            if (boneWeights[index].Y > 0)
                                            {
                                                boneIndices[index].Y = bonesUsed[boneIndices[index].Y];
                                            }
                                            if (boneWeights[index].Z > 0)
                                            {
                                                boneIndices[index].Z = bonesUsed[boneIndices[index].Z];
                                            }
                                            if (boneWeights[index].W > 0)
                                            {
                                                boneIndices[index].W = bonesUsed[boneIndices[index].W];
                                            }

                                            vertexTouched[index] = 1;

                                            int changes = 0;
                                            vertexChanged.TryGetValue(index, out changes);
                                            vertexChanged[index] = changes + 1;
                                        }
                                    }
                                }

                                bonesRemapping = partBones.ToArray();
                            }

                            if (vertexChanged.Values.Count > 0)
                            {
                                Debug.Assert(vertexChanged.Values.Max() < 2, "Vertex shared between model parts, will likely result in wrong skinning");
                            }
                        }

                        #endregion

                        int startIndex = indices.Count;
                        int indexCount = meshPart.m_indices.Count;

                        uint minIndex = (uint)meshPart.m_indices[0];
                        foreach (var i in meshPart.m_indices)
                        {
                            indices.Add((uint)i);
                            minIndex = Math.Min(minIndex, (uint)i);
                        }

                        uint baseVertex = minIndex;

                        for (int i = startIndex; i < startIndex + indexCount; i++)
                        {
                            indices[i] -= minIndex;
                            maxIndex    = Math.Max(maxIndex, indices[i]);
                        }

                        #region Material
                        var materialDesc = meshPart.m_MaterialDesc;

                        var matId        = MyMeshMaterials1.GetMaterialId(materialDesc, contentPath);
                        var partKey      = MyMeshMaterials1.Table[matId.Index].Technique;
                        var materialName = MyMeshMaterials1.Table[matId.Index].Name;

                        var list = submeshes.SetDefault(partKey, new List <MyDrawSubmesh>());
                        list.Add(new MyDrawSubmesh(indexCount, startIndex, (int)baseVertex, MyMeshMaterials1.GetProxyId(matId), bonesRemapping));

                        submeshesMeta.Add(new MySubmeshInfo
                        {
                            IndexCount   = indexCount,
                            StartIndex   = startIndex,
                            BaseVertex   = (int)baseVertex,
                            BonesMapping = bonesRemapping,
                            Material     = materialName.ToString(),
                            Technique    = partKey
                        });

                        var list2 = submeshes2.SetDefault(partKey, new List <MySubmeshInfo>());
                        list2.Add(submeshesMeta[submeshesMeta.Count - 1]);

                        #endregion
                    }
                    indicesNum = indices.Count;

                    #region Fill gpu buffes
                    unsafe
                    {
                        if (maxIndex <= ushort.MaxValue)
                        {
                            // create 16 bit indices
                            var indices16 = new ushort[indices.Count];
                            for (int i = 0; i < indices.Count; i++)
                            {
                                indices16[i] = (ushort)indices[i];
                            }

                            result.Indices = indices16;

                            fixed(ushort *I = indices16)
                            {
                                indexBuffer = MyHwBuffers.CreateIndexBuffer(indices16.Length, Format.R16_UInt, BindFlags.IndexBuffer, ResourceUsage.Immutable, new IntPtr(I), assetName + " index buffer");
                            }
                        }
                        else
                        {
                            var indicesArray = indices.ToArray();
                            fixed(uint *I = indicesArray)
                            {
                                indexBuffer = MyHwBuffers.CreateIndexBuffer(indices.Count, Format.R32_UInt, BindFlags.IndexBuffer, ResourceUsage.Immutable, new IntPtr(I), assetName + " index buffer");
                            }
                        }
                    }
                    unsafe
                    {
                        if (!hasBonesInfo)
                        {
                            var vertices = new MyVertexFormatPositionH4[verticesNum];

                            for (int i = 0; i < verticesNum; i++)
                            {
                                vertices[i] = new MyVertexFormatPositionH4(positions[i]);
                            }
                            meshVertexInput = meshVertexInput.Append(MyVertexInputComponentType.POSITION_PACKED);

                            result.VertexPositions = vertices;

                            fixed(MyVertexFormatPositionH4 *V = vertices)
                            {
                                vertexBuffers.Add(MyHwBuffers.CreateVertexBuffer(verticesNum, sizeof(MyVertexFormatPositionH4), BindFlags.VertexBuffer, ResourceUsage.Immutable, new IntPtr(V), assetName + " vertex buffer " + vertexBuffers.Count));
                            }
                        }
                        else
                        {
                            var vertices = new MyVertexFormatPositionSkinning[verticesNum];
                            for (int i = 0; i < verticesNum; i++)
                            {
                                vertices[i] = new MyVertexFormatPositionSkinning(
                                    positions[i],
                                    new Byte4(boneIndices[i].X, boneIndices[i].Y, boneIndices[i].Z, boneIndices[i].W),
                                    boneWeights[i]);
                            }
                            meshVertexInput = meshVertexInput.Append(MyVertexInputComponentType.POSITION_PACKED)
                                              .Append(MyVertexInputComponentType.BLEND_WEIGHTS).Append(MyVertexInputComponentType.BLEND_INDICES);

                            fixed(MyVertexFormatPositionSkinning *V = vertices)
                            {
                                vertexBuffers.Add(MyHwBuffers.CreateVertexBuffer(verticesNum, sizeof(MyVertexFormatPositionSkinning), BindFlags.VertexBuffer, ResourceUsage.Immutable, new IntPtr(V), assetName + " vertex buffer " + vertexBuffers.Count));
                            }
                        }
                        // add second stream
                        {
                            var vertices = new MyVertexFormatTexcoordNormalTangent[verticesNum];
                            for (int i = 0; i < verticesNum; i++)
                            {
                                vertices[i] = new MyVertexFormatTexcoordNormalTangent(texcoords[i], normals[i], tangentBitanSgn[i]);
                            }

                            fixed(MyVertexFormatTexcoordNormalTangent *V = vertices)
                            {
                                vertexBuffers.Add(MyHwBuffers.CreateVertexBuffer(verticesNum, sizeof(MyVertexFormatTexcoordNormalTangent), BindFlags.VertexBuffer, ResourceUsage.Immutable, new IntPtr(V), assetName + " vertex buffer " + vertexBuffers.Count));
                            }

                            result.VertexExtendedData = vertices;

                            meshVertexInput = meshVertexInput
                                              .Append(MyVertexInputComponentType.NORMAL, 1)
                                              .Append(MyVertexInputComponentType.TANGENT_SIGN_OF_BITANGENT, 1)
                                              .Append(MyVertexInputComponentType.TEXCOORD0_H, 1);
                        }
                    }
                    #endregion
                }
                #region Extract lods
                if (tagData.ContainsKey(MyImporterConstants.TAG_LODS))
                {
                    var tagLODs = tagData[MyImporterConstants.TAG_LODS];
                    if (((MyLODDescriptor[])tagLODs).Length > 0)
                    {
                    }
                    LodDescriptors = (MyLODDescriptor[])((MyLODDescriptor[])tagLODs).Clone();
                }
                #endregion

                if (missingMaterial)
                {
                    Debug.WriteLine(String.Format("Mesh {0} has missing material", assetName));
                }

                //indexBuffer.SetDebugName(assetName + " index buffer");
                int c = 0;
                //vertexBuffers.ForEach(x => x.SetDebugName(assetName + " vertex buffer " + c++));

                //
                result.BoundingBox    = (BoundingBox)tagData[MyImporterConstants.TAG_BOUNDING_BOX];
                result.BoundingSphere = (BoundingSphere)tagData[MyImporterConstants.TAG_BOUNDING_SPHERE];
                result.VerticesNum    = verticesNum;
                result.IndicesNum     = indicesNum;
                result.VertexLayout   = meshVertexInput;
                result.IB             = indexBuffer;
                result.VB             = vertexBuffers.ToArray();
                result.IsAnimated     = hasBonesInfo;
                result.Parts          = submeshes.ToDictionary(x => x.Key, x => x.Value.ToArray());
                result.PartsMetadata  = submeshes2.ToDictionary(x => x.Key, x => x.Value.ToArray());
                result.m_submeshes    = submeshesMeta;

                IsAnimated |= result.IsAnimated;

                importer.Clear();
                return(result);
            }
Esempio n. 26
0
            public void OnDeviceInit()
            {
                MyFileTextureParams fileTexParams;
                bool ret = GetCorrectedFileTextureParams(out fileTexParams);

                //MyRenderProxy.Assert(ret, "It is not implemented mechanism, what to do, when none of the textures exist");

                m_size = fileTexParams.Resolution;
                Texture2DDescription desc = new Texture2DDescription();

                desc.ArraySize      = m_listSubresourceFilenames.Count;
                desc.BindFlags      = BindFlags.ShaderResource;
                desc.CpuAccessFlags = CpuAccessFlags.None;
                desc.Format         = fileTexParams.Format;
                desc.Height         = (int)Size.Y;
                desc.Width          = (int)Size.X;
                var mipmaps = desc.MipLevels = fileTexParams.Mipmaps;

                desc.SampleDescription.Count   = 1;
                desc.SampleDescription.Quality = 0;
                desc.Usage           = ResourceUsage.Default;
                m_resource           = new Texture2D(MyRender11.Device, desc);
                m_resource.DebugName = m_resourceName;
                TextureFormat        = fileTexParams.Format;

                // foreach mip
                int i = 0;

                foreach (var path in m_listSubresourceFilenames)
                {
                    bool         isUsedCreatedGeneratedTexture = false;
                    ISrvBindable tex   = MyManagers.FileTextures.GetTexture(path, m_type, true);
                    var          tex2D = tex.Resource as Texture2D;
                    MyRenderProxy.Assert(tex2D != null,
                                         "MyFileArrayTexture supports only 2D textures. Inconsistent texture: " + tex.Name);
                    bool consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                    if (!consistent)
                    {
                        if (!string.IsNullOrEmpty(path) && MyFileSystem.FileExists(path))
                        {
                            string msg =
                                string.Format(
                                    "Texture {0} cannot be loaded. If this message is displayed on reloading textures, please restart the game. If it is not, please notify developers.", path);
                            MyRenderProxy.Fail(msg);
                        }
                    }

                    if (!consistent && m_recoverySystem.UseErrorTexture) // if the texture cannot be used, error texture will be used
                    {
                        tex   = MyManagers.FileTextures.GetTexture(m_recoverySystem.TextureFilepath, m_type, true);
                        tex2D = tex.Resource as Texture2D;
                        MyRenderProxy.Assert(tex2D != null,
                                             "MyFileArrayTexture supports only 2D textures. Inconsistent texture: " + m_recoverySystem.TextureFilepath);
                        consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                    }
                    if (!consistent && m_recoverySystem.UseBytePattern) // if the texture cannot be used, byte pattern will be used to generate texture
                    {
                        tex = MyManagers.GeneratedTextures.CreateFromBytePattern("MyFileArrayTexture.Tmp", desc.Width,
                                                                                 desc.Height, m_recoverySystem.FormatBytePattern, m_recoverySystem.BytePattern);
                        tex2D = tex.Resource as Texture2D;
                        MyRenderProxy.Assert(tex2D != null);
                        consistent = MyResourceUtils.CheckTexturesConsistency(desc, tex2D.Description);
                        isUsedCreatedGeneratedTexture = true;
                    }
                    if (!consistent)
                    {
                        Texture2DDescription desc1 = desc;
                        Texture2DDescription desc2 = tex2D.Description;
                        string errorMsg            = string.Format("Textures ({0}) is not compatible within array texture! Width: ({1},{2}) Height: ({3},{4}) Mipmaps: ({5},{6}) Format: ({7},{8})",
                                                                   path, desc1.Width, desc2.Width, desc1.Height, desc2.Height, desc1.MipLevels, desc2.MipLevels, desc1.Format, desc2.Format);
                        MyRenderProxy.Error(errorMsg);
                        MyRender11.Log.WriteLine(errorMsg);
                    }

                    for (int m = 0; m < mipmaps; m++)
                    {
                        MyRender11.RC.CopySubresourceRegion(tex,
                                                            Resource.CalculateSubResourceIndex(m, 0, mipmaps), null, Resource,
                                                            Resource.CalculateSubResourceIndex(m, i, mipmaps));

                        int sizeX = Resource.CalculateMipSize(m, Size.X);
                        int sizeY = Resource.CalculateMipSize(m, Size.Y);
                        ByteSize += FormatHelper.ComputeScanlineCount(TextureFormat, sizeX) * 4 * FormatHelper.ComputeScanlineCount(TextureFormat, sizeY) * 4 * FormatHelper.SizeOfInBytes(TextureFormat);
                    }

                    if (isUsedCreatedGeneratedTexture)
                    {
                        IGeneratedTexture generatedTex = (IGeneratedTexture)tex;
                        MyManagers.GeneratedTextures.DisposeTex(generatedTex);
                    }
                    i++;
                }

                m_srv = new ShaderResourceView(MyRender11.Device, Resource);
            }
Esempio n. 27
0
        public SpaceEngineersCore()
        {
            var    contentPath  = ToolboxUpdater.GetApplicationContentPath();
            string userDataPath = SpaceEngineersConsts.BaseLocalPath.DataPath;

            MyFileSystem.ExePath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(FastResourceLock)).Location);

            MyLog.Default = MySandboxGame.Log;
            SpaceEngineersGame.SetupBasicGameInfo();
            _startup = new MyCommonProgramStartup(new string[] { });

            //var appDataPath = _startup.GetAppDataPath();
            //MyInitializer.InvokeBeforeRun(AppId, MyPerGameSettings.BasicGameInfo.ApplicationName + "SEToolbox", appDataPath);
            //MyInitializer.InitCheckSum();

            MyFileSystem.Reset();
            MyFileSystem.Init(contentPath, userDataPath);

            // This will start the Steam Service, and Steam will think SE is running.
            // TODO: we don't want to be doing this all the while SEToolbox is running,
            // perhaps a once off during load to fetch of mods then disconnect/Dispose.
            _steamService = MySteamGameService.Create(MySandboxGame.IsDedicated, AppId);
            MyServiceManager.Instance.AddService(_steamService);

            IMyUGCService serviceInstance = MySteamUgcService.Create(AppId, _steamService);

            MyServiceManager.Instance.AddService(serviceInstance);

            MyFileSystem.InitUserSpecific(_steamService.UserId.ToString()); // This sets the save file/path to load games from.
            //MyFileSystem.InitUserSpecific(null);
            //SpaceEngineersWorkshop.MySteam.Dispose();

            MySandboxGame.Config = new MyConfig("SpaceEngineers.cfg"); // TODO: Is specific to SE, not configurable to ME.
            MySandboxGame.Config.Load();

            SpaceEngineersGame.SetupPerGameSettings();

            VRage.MyVRage.Init(new ToolboxPlatform());
            VRage.MyVRage.Platform.Init();

            MySandboxGame.InitMultithreading();

            VRageRender.MyRenderProxy.Initialize(new MyNullRender());

            // We create a whole instance of MySandboxGame!
            // If this is causing an exception, then there is a missing dependency.
            MySandboxGame gameTemp = new DerivedGame(new string[] { "-skipintro" });

            // creating MySandboxGame will reset the CurrentUICulture, so I have to reapply it.
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfoByIetfLanguageTag(GlobalSettings.Default.LanguageCode);
            SpaceEngineersApi.LoadLocalization();
            MyStorageBase.UseStorageCache = false;

            // Create an empty instance of MySession for use by low level code.
            var mySession = (Sandbox.Game.World.MySession)FormatterServices.GetUninitializedObject(typeof(Sandbox.Game.World.MySession));

            // Required as the above code doesn't populate it during ctor of MySession.
            ReflectionUtil.ConstructField(mySession, "m_creativeTools");
            ReflectionUtil.ConstructField(mySession, "m_sessionComponents");
            ReflectionUtil.ConstructField(mySession, "m_sessionComponentsForUpdate");

            mySession.Settings = new MyObjectBuilder_SessionSettings {
                EnableVoxelDestruction = true
            };

            // change for the Clone() method to use XML cloning instead of Protobuf because of issues with MyObjectBuilder_CubeGrid.Clone()
            ReflectionUtil.SetFieldValue(typeof(VRage.ObjectBuilders.MyObjectBuilderSerializer), "ENABLE_PROTOBUFFERS_CLONING", false);

            // Assign the instance back to the static.
            Sandbox.Game.World.MySession.Static = mySession;

            var heightMapLoadingSystem = new MyHeightMapLoadingSystem();

            mySession.RegisterComponent(heightMapLoadingSystem, heightMapLoadingSystem.UpdateOrder, heightMapLoadingSystem.Priority);
            heightMapLoadingSystem.LoadData();

            _stockDefinitions = new SpaceEngineersResources();
            _stockDefinitions.LoadDefinitions();
            _manageDeleteVoxelList = new List <string>();
        }
Esempio n. 28
0
        private void Create()
        {
            bool dedicated = Sandbox.Engine.Platform.Game.IsDedicated;

            Environment.SetEnvironmentVariable("SteamAppId", _appSteamId.ToString());
            MyServiceManager.Instance.AddService <IMyGameService>(new MySteamService(dedicated, _appSteamId));
            if (dedicated && !MyGameService.HasGameServer)
            {
                _log.Warn("Steam service is not running! Please reinstall dedicated server.");
                return;
            }

            SpaceEngineersGame.SetupBasicGameInfo();
            SpaceEngineersGame.SetupPerGameSettings();
            MyFinalBuildConstants.APP_VERSION       = MyPerGameSettings.BasicGameInfo.GameVersion;
            MySessionComponentExtDebug.ForceDisable = true;
            MyPerGameSettings.SendLogToKeen         = false;
            // SpaceEngineersGame.SetupAnalytics();

            MyFileSystem.ExePath = Path.GetDirectoryName(typeof(SpaceEngineersGame).Assembly.Location);

            _tweakGameSettings();

            MyFileSystem.Reset();
            MyInitializer.InvokeBeforeRun(_appSteamId, _appName, _userDataPath);
            // MyInitializer.InitCheckSum();


            // Hook into the VRage plugin system for updates.
            _getVRagePluginList().Add(_torch);

            if (!MySandboxGame.IsReloading)
            {
                MyFileSystem.InitUserSpecific(dedicated ? null : MyGameService.UserId.ToString());
            }
            MySandboxGame.IsReloading = dedicated;

            // render init
            {
                IMyRender renderer = null;
                if (dedicated)
                {
                    renderer = new MyNullRender();
                }
                else
                {
                    MyPerformanceSettings preset = MyGuiScreenOptionsGraphics.GetPreset(MyRenderQualityEnum.NORMAL);
                    MyRenderProxy.Settings.User = MyVideoSettingsManager.GetGraphicsSettingsFromConfig(ref preset)
                                                  .PerformanceSettings.RenderSettings;
                    MyStringId graphicsRenderer = MySandboxGame.Config.GraphicsRenderer;
                    if (graphicsRenderer == MySandboxGame.DirectX11RendererKey)
                    {
                        renderer = new MyDX11Render(new MyRenderSettings?(MyRenderProxy.Settings));
                        if (!renderer.IsSupported)
                        {
                            MySandboxGame.Log.WriteLine(
                                "DirectX 11 renderer not supported. No renderer to revert back to.");
                            renderer = null;
                        }
                    }
                    if (renderer == null)
                    {
                        throw new MyRenderException(
                                  "The current version of the game requires a Dx11 card. \\n For more information please see : http://blog.marekrosa.org/2016/02/space-engineers-news-full-source-code_26.html",
                                  MyRenderExceptionEnum.GpuNotSupported);
                    }
                    MySandboxGame.Config.GraphicsRenderer = graphicsRenderer;
                }
                MyRenderProxy.Initialize(renderer);
                MyRenderProxy.GetRenderProfiler().SetAutocommit(false);
                MyRenderProxy.GetRenderProfiler().InitMemoryHack("MainEntryPoint");
            }

            // Loads object builder serializers. Intuitive, right?
            _log.Info("Setting up serializers");
            MyPlugins.RegisterGameAssemblyFile(MyPerGameSettings.GameModAssembly);
            if (MyPerGameSettings.GameModBaseObjBuildersAssembly != null)
            {
                MyPlugins.RegisterBaseGameObjectBuildersAssemblyFile(MyPerGameSettings.GameModBaseObjBuildersAssembly);
            }
            MyPlugins.RegisterGameObjectBuildersAssemblyFile(MyPerGameSettings.GameModObjBuildersAssembly);
            MyPlugins.RegisterSandboxAssemblyFile(MyPerGameSettings.SandboxAssembly);
            MyPlugins.RegisterSandboxGameAssemblyFile(MyPerGameSettings.SandboxGameAssembly);
            //typeof(MySandboxGame).GetMethod("Preallocate", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, null);
            MyGlobalTypeMetadata.Static.Init(false);
        }
Esempio n. 29
0
        //  Sort of lazy-load, where constructor just saves information about what this model should be, but real load is done here - and only one time.
        //  This loads only vertex data, doesn't touch GPU
        //  Can be called from main and background thread
        public void LoadData()
        {
            if (m_loadedData)
            {
                return;
            }

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyModel::LoadData");


            MyLog.Default.WriteLine("MyModel.LoadData -> START", LoggingOptions.LOADING_MODELS);
            MyLog.Default.IncreaseIndent(LoggingOptions.LOADING_MODELS);

            MyLog.Default.WriteLine("m_assetName: " + m_assetName, LoggingOptions.LOADING_MODELS);

            //  Read data from model TAG parameter. There are stored vertex positions, triangle indices, vectors, ... everything we need.
            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - import data");

            MyLog.Default.WriteLine(String.Format("Importing asset {0}, path: {1}", m_assetName, AssetName), LoggingOptions.LOADING_MODELS);


            string assetForImport = AssetName;
            var    fsPath         = Path.IsPathRooted(AssetName) ? AssetName : Path.Combine(MyFileSystem.ContentPath, AssetName);

            if (!MyFileSystem.FileExists(fsPath))
            {
                assetForImport = @"Models\Debug\Error.mwm";
            }

            try
            {
                m_importer.ImportData(assetForImport);
            }
            catch
            {
                MyLog.Default.WriteLine(String.Format("Importing asset failed {0}", m_assetName));
                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                throw;
            }
            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            DataVersion = m_importer.DataVersion;

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - load tag data");
            Dictionary <string, object> tagData = m_importer.GetTagData();

            if (tagData.Count == 0)
            {
                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                throw new Exception(String.Format("Uncompleted tagData for asset: {0}, path: {1}", m_assetName, AssetName));
            }
            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - vertex, normals, texture coords");


            HalfVector4[] vertices = (HalfVector4[])tagData[MyImporterConstants.TAG_VERTICES];

            System.Diagnostics.Debug.Assert(vertices.Length > 0);

            Byte4[] normals = (Byte4[])tagData[MyImporterConstants.TAG_NORMALS];
            m_vertices = new MyCompressedVertexNormal[vertices.Length];
            if (normals.Length > 0)
            {
                for (int v = 0; v < vertices.Length; v++)
                {
                    m_vertices[v] = new MyCompressedVertexNormal()
                    {
                        Position = vertices[v], // VF_Packer.PackPosition(ref vertices[v]),
                        Normal   = normals[v]   //VF_Packer.PackNormalB4(ref normals[v])
                    };
                }
            }
            else
            {
                for (int v = 0; v < vertices.Length; v++)
                {
                    m_vertices[v] = new MyCompressedVertexNormal()
                    {
                        Position = vertices[v],// VF_Packer.PackPosition(ref vertices[v]),
                    };
                }
            }


            m_verticesCount = vertices.Length;

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - mesh");
            m_meshContainer.Clear();

            if (tagData.ContainsKey(MyImporterConstants.TAG_MESH_PARTS))
            {
                List <int> indices  = new List <int>(GetVerticesCount()); // Default capacity estimation
                int        maxIndex = 0;

                List <MyMeshPartInfo> meshParts = tagData[MyImporterConstants.TAG_MESH_PARTS] as List <MyMeshPartInfo>;
                foreach (MyMeshPartInfo meshPart in meshParts)
                {
                    MyMesh mesh = new MyMesh(meshPart, m_assetName);
                    mesh.IndexStart = indices.Count;
                    mesh.TriCount   = meshPart.m_indices.Count / 3;

                    if (m_loadUV && false == m_hasUV)
                    {
                        m_texCoords = (HalfVector2[])tagData[MyImporterConstants.TAG_TEXCOORDS0];
                        m_hasUV     = true;
                        m_loadUV    = false;
                    }

                    if (meshPart.m_MaterialDesc != null && meshPart.Technique == MyMeshDrawTechnique.GLASS)
                    {
                        GlassData = mesh;

                        HalfVector2[]      forLoadingTexCoords0 = (HalfVector2[])tagData[MyImporterConstants.TAG_TEXCOORDS0];
                        List <HalfVector2> neededTexCoords      = new List <HalfVector2>();

                        for (int t = 0; t < meshPart.m_indices.Count; t++)
                        {
                            int index = meshPart.m_indices[t];
                            neededTexCoords.Add(forLoadingTexCoords0[index]);
                        }

                        GlassTexCoords = neededTexCoords.ToArray();
                    }

                    System.Diagnostics.Debug.Assert(mesh.TriCount > 0);

                    if (mesh.TriCount == 0)
                    {
                        VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                        VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
                        return;
                    }

                    foreach (var i in meshPart.m_indices)
                    {
                        indices.Add(i);
                        if (i > maxIndex)
                        {
                            maxIndex = i;
                        }
                    }



                    m_meshContainer.Add(mesh);
                }

                if (maxIndex <= ushort.MaxValue)
                {
                    // create 16 bit indices
                    m_Indices_16bit = new ushort[indices.Count];
                    for (int i = 0; i < indices.Count; i++)
                    {
                        m_Indices_16bit[i] = (ushort)indices[i];
                    }
                }
                else
                {
                    // use 32bit indices
                    m_Indices = indices.ToArray();
                }
            }

            if (tagData.ContainsKey(MyImporterConstants.TAG_MODEL_BVH))
            {
                m_bvh = new MyQuantizedBvhAdapter(tagData[MyImporterConstants.TAG_MODEL_BVH] as GImpactQuantizedBvh, this);
            }

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - other data");

            Animations = (ModelAnimations)tagData[MyImporterConstants.TAG_ANIMATIONS];
            Bones      = (MyModelBone[])tagData[MyImporterConstants.TAG_BONES];

            BoundingBox         = (BoundingBox)tagData[MyImporterConstants.TAG_BOUNDING_BOX];
            BoundingSphere      = (BoundingSphere)tagData[MyImporterConstants.TAG_BOUNDING_SPHERE];
            BoundingBoxSize     = BoundingBox.Max - BoundingBox.Min;
            BoundingBoxSizeHalf = BoundingBoxSize / 2.0f;
            Dummies             = tagData[MyImporterConstants.TAG_DUMMIES] as Dictionary <string, MyModelDummy>;
            BoneMapping         = tagData[MyImporterConstants.TAG_BONE_MAPPING] as VRageMath.Vector3I[];

            if (tagData.ContainsKey(MyImporterConstants.TAG_MODEL_FRACTURES))
            {
                ModelFractures = (MyModelFractures)tagData[MyImporterConstants.TAG_MODEL_FRACTURES];
            }

            object patternScale;

            if (tagData.TryGetValue(MyImporterConstants.TAG_PATTERN_SCALE, out patternScale))
            {
                PatternScale = (float)patternScale;
            }

            if (BoneMapping.Length == 0)
            {
                BoneMapping = null;
            }

            if (tagData.ContainsKey(MyImporterConstants.TAG_HAVOK_COLLISION_GEOMETRY))
            {
                HavokData = (byte[])tagData[MyImporterConstants.TAG_HAVOK_COLLISION_GEOMETRY];
                byte[] tagCollisionData = (byte[])tagData[MyImporterConstants.TAG_HAVOK_COLLISION_GEOMETRY];
                if (tagCollisionData.Length > 0 && HkBaseSystem.IsThreadInitialized)
                {
                    bool           containsSceneData;
                    bool           containsDestructionData;
                    List <HkShape> shapesList = new List <HkShape>();
                    if (!HkShapeLoader.LoadShapesListFromBuffer(tagCollisionData, shapesList, out containsSceneData, out containsDestructionData))
                    {
                        MyLog.Default.WriteLine(string.Format("Model {0} - Unable to load collision geometry", AssetName), LoggingOptions.LOADING_MODELS);
                        Debug.Fail("Collision model was exported in wrong way: " + m_assetName);
                    }

                    if (shapesList.Count > 10)
                    {
                        MyLog.Default.WriteLine(string.Format("Model {0} - Found too many collision shapes, only the first 10 will be used", AssetName), LoggingOptions.LOADING_MODELS);
                    }

                    if (HavokCollisionShapes != null)
                    {
                        Debug.Fail("Shapes already loaded");
                    }
                    if (shapesList.Count > 0)
                    {
                        HavokCollisionShapes = shapesList.ToArray();
                    }
                    else
                    {
                        MyLog.Default.WriteLine(string.Format("Model {0} - Unable to load collision geometry from file, default collision will be used !", AssetName));
                    }

                    if (containsDestructionData)
                    {
                        HavokDestructionData = tagCollisionData;
                    }

                    ExportedWrong = !containsSceneData;
                }
            }


            if (tagData.ContainsKey(MyImporterConstants.TAG_HAVOK_DESTRUCTION))
            {
                if (((byte[])tagData[MyImporterConstants.TAG_HAVOK_DESTRUCTION]).Length > 0)
                {
                    HavokDestructionData = (byte[])tagData[MyImporterConstants.TAG_HAVOK_DESTRUCTION];
                }
            }

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("Model - load data - copy triangle indices");
            //  Prepare data
            CopyTriangleIndices();
            m_trianglesCount = Triangles.Count();

            //  Remember this numbers as list may be cleared at the end of this method
            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();

            MyLog.Default.WriteLine("Triangles.Length: " + Triangles.Length, LoggingOptions.LOADING_MODELS);
            MyLog.Default.WriteLine("Vertexes.Length: " + GetVerticesCount(), LoggingOptions.LOADING_MODELS);
            MyLog.Default.WriteLine("Centered: " + (bool)tagData[MyImporterConstants.TAG_CENTERED], LoggingOptions.LOADING_MODELS);
            MyLog.Default.WriteLine("UseChannelTextures: " + (bool)tagData[MyImporterConstants.TAG_USE_CHANNEL_TEXTURES], LoggingOptions.LOADING_MODELS);
            MyLog.Default.WriteLine("Length in meters: " + (float)tagData[MyImporterConstants.TAG_LENGTH_IN_METERS], LoggingOptions.LOADING_MODELS);
            MyLog.Default.WriteLine("Rescale to length in meters?: " + (bool)tagData[MyImporterConstants.TAG_RESCALE_TO_LENGTH_IN_METERS], LoggingOptions.LOADING_MODELS);
            MyLog.Default.WriteLine("BoundingBox: " + BoundingBox, LoggingOptions.LOADING_MODELS);
            MyLog.Default.WriteLine("BoundingSphere: " + BoundingSphere, LoggingOptions.LOADING_MODELS);

            Stats.PerAppLifetime.MyModelsCount++;
            Stats.PerAppLifetime.MyModelsMeshesCount    += m_meshContainer.Count;
            Stats.PerAppLifetime.MyModelsVertexesCount  += GetVerticesCount();
            Stats.PerAppLifetime.MyModelsTrianglesCount += Triangles.Length;

            ModelInfo = new MyModelInfo(GetTrianglesCount(), GetVerticesCount(), BoundingBoxSize);

            m_loadedData            = true;
            m_loadingErrorProcessed = false;
            MyLog.Default.DecreaseIndent(LoggingOptions.LOADING_MODELS);
            MyLog.Default.WriteLine("MyModel.LoadData -> END", LoggingOptions.LOADING_MODELS);

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
        }
Esempio n. 30
0
        // Loads campaign data to storage.
        public void Init()
        {
            MySandboxGame.Log.WriteLine("MyCampaignManager.Constructor() - START");

            // Variables needed for loading
            var vanillaFiles =
                MyFileSystem.GetFiles(Path.Combine(MyFileSystem.ContentPath, CAMPAIGN_CONTENT_RELATIVE_PATH), "*.vs",
                                      MySearchOption.TopDirectoryOnly);
            var localModFolders       = Directory.GetDirectories(MyFileSystem.ModsPath);
            var modFiles              = MyFileSystem.GetFiles(MyFileSystem.ModsPath, "*.sbm", MySearchOption.TopDirectoryOnly);
            var localModCampaignFiles = new List <string>();
            var modCampaignFiles      = new List <string>();

            // Gather local mod campaign files
            foreach (var localModFolder in localModFolders)
            {
                localModCampaignFiles.AddRange(
                    MyFileSystem.GetFiles(Path.Combine(localModFolder, CAMPAIGN_CONTENT_RELATIVE_PATH), "*.vs",
                                          MySearchOption.TopDirectoryOnly));
            }

            // Gather campaign files from workshop zips
            foreach (var modFile in modFiles)
            {
                try
                {
                    modCampaignFiles.AddRange(MyFileSystem.GetFiles(Path.Combine(modFile, CAMPAIGN_CONTENT_RELATIVE_PATH),
                                                                    "*.vs", MySearchOption.TopDirectoryOnly));
                }
                catch (Exception e)
                {
                    MySandboxGame.Log.WriteLine("ERROR: Reading mod file: " + modFile + "\n" + e);
                }
            }

            // Load vanilla files
            foreach (var vanillaFile in vanillaFiles)
            {
                MyObjectBuilder_VSFiles ob;
                if (MyObjectBuilderSerializer.DeserializeXML(vanillaFile, out ob))
                {
                    if (ob.Campaign != null)
                    {
                        ob.Campaign.IsVanilla  = true;
                        ob.Campaign.IsLocalMod = false;
                        LoadCampaignData(ob.Campaign);
                    }
                }
            }

            foreach (var localModCampaignFile in localModCampaignFiles)
            {
                MyObjectBuilder_VSFiles ob;
                if (MyObjectBuilderSerializer.DeserializeXML(localModCampaignFile, out ob))
                {
                    if (ob.Campaign != null)
                    {
                        ob.Campaign.IsVanilla     = false;
                        ob.Campaign.IsLocalMod    = true;
                        ob.Campaign.ModFolderPath = GetModFolderPath(localModCampaignFile);
                        LoadCampaignData(ob.Campaign);
                    }
                }
            }

            foreach (var modCampaignFile in modCampaignFiles)
            {
                MyObjectBuilder_VSFiles ob;
                if (MyObjectBuilderSerializer.DeserializeXML(modCampaignFile, out ob))
                {
                    if (ob.Campaign != null)
                    {
                        ob.Campaign.IsVanilla     = false;
                        ob.Campaign.IsLocalMod    = false;
                        ob.Campaign.ModFolderPath = GetModFolderPath(modCampaignFile);
                        LoadCampaignData(ob.Campaign);
                    }
                }
            }

            MySandboxGame.Log.WriteLine("MyCampaignManager.Constructor() - END");
        }