Пример #1
0
 public void CreateDatabase_Test()
 {
     string filename = Path.GetTempFileName();
     IGameDatabase database = new GameDatabase(filename);
     Assert.NotNull(database);
     this.DisposeSqlite();
     File.Delete(filename);
 }
Пример #2
0
        public Chat()
            : base(new Irc("Tomestone", "oauth:npafwpg44j0a5iullxo2dt385n5jeco", new[] { MainChannel }))
        {
            var twitch = new TwitchConnection();

            _userDatabase = new UserDatabase(_db, twitch);
            _gameDatabase = new GameDatabase(_db, twitch);
            _statistics = new Statistics(_userDatabase, _gameDatabase, twitch);
        }
Пример #3
0
 private void changeTexture(GameDatabase.TextureInfo newTexture)
 {
     Material mat = getScreenMaterial();
     if (mat != null)
     {
         mat.mainTexture = newTexture.texture;
     }
     else
     {
         NE_Helper.logError("Transform NOT found: " + SCREEN_PART_NAME);
     }
 }
        public static void Main()
        {
            IGameDatabase gameDatabase = new GameDatabase();
            IInputReader reader = new ConsoleReader();
            IOutputWriter writer = new ConsoleWriter();

            var engine = new GameEngine(
                gameDatabase,
                reader,
                writer);

            engine.Start();
        }
Пример #5
0
 public void GetAllGames_Test()
 {
     string filename = Path.GetTempFileName();
     IGameDatabase database = new GameDatabase(filename);
     var fakeGameInfo = new Mock<IGameInfo>();
     fakeGameInfo.SetupGet(game => game.Name).Returns("TestGame");
     fakeGameInfo.SetupGet(game => game.UUID).Returns("TESTGAME");
     fakeGameInfo.SetupGet(game => game.PlatformID).Returns("TESTPLATFORM");
     database.AddGame(fakeGameInfo.Object);
     Assert.NotEmpty(database.GetAllGames());
     this.DisposeSqlite();
     File.Delete(filename);
 }
Пример #6
0
        public void Update()
        {
            this.enabled = true;
            AvailablePart intakePart = PartLoader.getPartInfoByName("CircularIntake");
            if (intakePart != null)
            {
                if (intakePart.partPrefab.FindModulesImplementing<AtmosphericIntake>().Count <= 0 && PartLoader.Instance.IsReady())
                {
                    plugin_init = false;
                }
            }

            if (!resources_configured)
            {
                // read WarpPluginSettings.cfg
                ConfigNode plugin_settings = GameDatabase.Instance.GetConfigNode("WarpPlugin/WarpPluginSettings/WarpPluginSettings");
                if (plugin_settings != null)
                {
                    if (plugin_settings.HasValue("PartTechUpgrades"))
                    {
                        PartTechUpgrades = new Dictionary<string, string>();

                        string rawstring = plugin_settings.GetValue("PartTechUpgrades");
                        string[] splitValues = rawstring.Split(',').Select(sValue => sValue.Trim()).ToArray();

                        int pairs = splitValues.Length / 2;
                        int totalValues = splitValues.Length / 2 * 2;
                        for (int i = 0; i < totalValues; i += 2)
                            PartTechUpgrades.Add(splitValues[i], splitValues[i + 1]);

                        Debug.Log("[KSP Interstellar] Part Tech Upgrades set to: " + rawstring);
                    }
                    if (plugin_settings.HasValue("OrsResourceMappings"))
                    {
                        OrsResourceMappings = new Dictionary<string, string>();

                        string rawstring = plugin_settings.GetValue("OrsResourceMappings");
                        string[] splitValues = rawstring.Split(',').Select(sValue => sValue.Trim()).ToArray();

                        int pairs = splitValues.Length / 2;
                        int totalValues = pairs * 2;
                        for (int i = 0; i < totalValues; i += 2)
                            OrsResourceMappings.Add(splitValues[i], splitValues[i + 1]);
                    }
                    if (plugin_settings.HasValue("RadiationMechanicsDisabled"))
                    {
                        PluginHelper._radiationMechanicsDisabled = bool.Parse(plugin_settings.GetValue("RadiationMechanicsDisabled"));
                        Debug.Log("[KSP Interstellar] Radiation Mechanics Disabled set to: " + PluginHelper.RadiationMechanicsDisabled.ToString());
                    }
                    if (plugin_settings.HasValue("ThermalMechanicsDisabled"))
                    {
                        PluginHelper._isThermalDissipationDisabled = bool.Parse(plugin_settings.GetValue("ThermalMechanicsDisabled"));
                        Debug.Log("[KSP Interstellar] ThermalMechanics set to : " + (!PluginHelper.IsThermalDissipationDisabled).ToString());
                    }
                    if (plugin_settings.HasValue("SolarPanelClampedHeating"))
                    {
                        PluginHelper._isPanelHeatingClamped = bool.Parse(plugin_settings.GetValue("SolarPanelClampedHeating"));
                        Debug.Log("[KSP Interstellar] Solar panels clamped heating set to enabled: " + PluginHelper.IsSolarPanelHeatingClamped.ToString());
                    }
                    if (plugin_settings.HasValue("RecieverTempTweak"))
                    {
                        PluginHelper._isRecieverTempTweaked = bool.Parse(plugin_settings.GetValue("RecieverTempTweak"));
                        Debug.Log("[KSP Interstellar] Microwave reciever CoreTemp tweak is set to enabled: " + PluginHelper.IsRecieverCoreTempTweaked.ToString());
                    }
                    if (plugin_settings.HasValue("LimitedWarpTravel"))
                    {
                        PluginHelper._limitedWarpTravel = bool.Parse(plugin_settings.GetValue("LimitedWarpTravel"));
                        Debug.Log("[KSP Interstellar] Apply Limited Warp Travel: " + PluginHelper.LimitedWarpTravel.ToString());
                    }
                    if (plugin_settings.HasValue("MatchDemandWithSupply"))
                    {
                        PluginHelper._matchDemandWithSupply = bool.Parse(plugin_settings.GetValue("MatchDemandWithSupply"));
                        Debug.Log("[KSP Interstellar] Match Demand With Supply: " + PluginHelper.MatchDemandWithSupply.ToString());
                    }
                    if (plugin_settings.HasValue("MaxPowerDrawForExoticMatterMult"))
                    {
                        PluginHelper._maxPowerDrawForExoticMatterMult = float.Parse(plugin_settings.GetValue("MaxPowerDrawForExoticMatterMult"));
                        Debug.Log("[KSP Interstellar] Max Power Draw For Exotic Matter Multiplier set to: " + PluginHelper.MaxPowerDrawForExoticMatterMult.ToString("0.000000"));
                    }
                    if (plugin_settings.HasValue("GravityConstant"))
                    {
                        PluginHelper._gravityConstant = Single.Parse(plugin_settings.GetValue("GravityConstant"));
                        Debug.Log("[KSP Interstellar] Gravity constant set to: " + PluginHelper.GravityConstant.ToString("0.000000"));
                    }
                    if (plugin_settings.HasValue("IspCoreTempMult"))
                    {
                        PluginHelper._ispCoreTempMult = double.Parse(plugin_settings.GetValue("IspCoreTempMult"));
                        Debug.Log("[KSP Interstellar] Isp core temperature multiplier set to: " + PluginHelper.IspCoreTempMult.ToString("0.000000"));
                    }
                    if (plugin_settings.HasValue("ElectricEngineIspMult"))
                    {
                        PluginHelper._electricEngineIspMult = double.Parse(plugin_settings.GetValue("ElectricEngineIspMult"));
                        Debug.Log("[KSP Interstellar] Electric EngineIsp Multiplier set to: " + PluginHelper.ElectricEngineIspMult.ToString("0.000000"));
                    }

                    if (plugin_settings.HasValue("GlobalThermalNozzlePowerMaxTrustMult"))
                    {
                        PluginHelper._globalThermalNozzlePowerMaxThrustMult = double.Parse(plugin_settings.GetValue("GlobalThermalNozzlePowerMaxTrustMult"));
                        Debug.Log("[KSP Interstellar] Maximum Global Thermal Power Maximum Thrust Multiplier set to: " + PluginHelper.GlobalThermalNozzlePowerMaxThrustMult.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("GlobalMagneticNozzlePowerMaxTrustMult"))
                    {
                        PluginHelper._globalMagneticNozzlePowerMaxThrustMult = double.Parse(plugin_settings.GetValue("GlobalMagneticNozzlePowerMaxTrustMult"));
                        Debug.Log("[KSP Interstellar] Maximum Global Magnetic Nozzle Power Maximum Thrust Multiplier set to: " + PluginHelper.GlobalMagneticNozzlePowerMaxThrustMult.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("GlobalElectricEnginePowerMaxTrustMult"))
                    {
                        PluginHelper._globalElectricEnginePowerMaxThrustMult = double.Parse(plugin_settings.GetValue("GlobalElectricEnginePowerMaxTrustMult"));
                        Debug.Log("[KSP Interstellar] Maximum Global Electric Engine Power Maximum Thrust Multiplier set to: " + PluginHelper.GlobalElectricEnginePowerMaxThrustMult.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("LfoFuelTrustModifier"))
                    {
                        PluginHelper._lfoFuelThrustModifier = double.Parse(plugin_settings.GetValue("LfoFuelTrustModifier"));
                        Debug.Log("[KSP Interstellar] Maximum Lfo Fuel Thrust Multiplier set to: " + PluginHelper.LfoFuelThrustModifier.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("MaxThermalNozzleIsp"))
                    {
                        PluginHelper._maxThermalNozzleIsp = float.Parse(plugin_settings.GetValue("MaxThermalNozzleIsp"));
                        Debug.Log("[KSP Interstellar] Maximum Thermal Nozzle Isp set to: " + PluginHelper.MaxThermalNozzleIsp.ToString("0.0"));
                    }

                    if (plugin_settings.HasValue("TrustCoreTempThreshold"))
                    {
                        PluginHelper._thrustCoreTempThreshold = double.Parse(plugin_settings.GetValue("TrustCoreTempThreshold"));
                        Debug.Log("[KSP Interstellar] Thrust core temperature threshold set to: " + PluginHelper.ThrustCoreTempThreshold.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("LowCoreTempBaseTrust"))
                    {
                        PluginHelper._lowCoreTempBaseThrust = double.Parse(plugin_settings.GetValue("LowCoreTempBaseTrust"));
                        Debug.Log("[KSP Interstellar] Low core temperature base thrust modifier set to: " + PluginHelper.LowCoreTempBaseThrust.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("HighCoreTempTrustMult"))
                    {
                        PluginHelper._highCoreTempThrustMult = double.Parse(plugin_settings.GetValue("HighCoreTempTrustMult"));
                        Debug.Log("[KSP Interstellar] High core temperature thrust divider set to: " + PluginHelper.HighCoreTempThrustMult.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("BasePowerConsumption"))
                    {
                        PluginHelper._basePowerConsumption = double.Parse(plugin_settings.GetValue("BasePowerConsumption"));
                        Debug.Log("[KSP Interstellar] Base Power Consumption set to: " + PluginHelper.BasePowerConsumption.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("PowerConsumptionMultiplier"))
                    {
                        PluginHelper._powerConsumptionMultiplier = double.Parse(plugin_settings.GetValue("PowerConsumptionMultiplier"));
                        Debug.Log("[KSP Interstellar] Base Power Consumption set to: " + PluginHelper.PowerConsumptionMultiplier.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("IspNtrPropellantModifierBase"))
                    {
                        PluginHelper._ispNtrPropellantModifierBase = float.Parse(plugin_settings.GetValue("IspNtrPropellantModifierBase"));
                        Debug.Log("[KSP Interstellar] Isp Ntr Propellant Modifier Base set to: " + PluginHelper.IspNtrPropellantModifierBase.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("IspElectroPropellantModifierBase"))
                    {
                        PluginHelper._ispElectroPropellantModifierBase = float.Parse(plugin_settings.GetValue("IspNtrPropellantModifierBase"));
                        Debug.Log("[KSP Interstellar] Isp Ntr Propellant Modifier Base set to: " + PluginHelper.IspElectroPropellantModifierBase.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("ElectricEnginePowerPropellantIspMultLimiter"))
                    {
                        PluginHelper._electricEnginePowerPropellantIspMultLimiter = float.Parse(plugin_settings.GetValue("ElectricEnginePowerPropellantIspMultLimiter"));
                        Debug.Log("[KSP Interstellar] Electric Engine Power Propellant IspMultiplier Limiter set to: " + PluginHelper.ElectricEnginePowerPropellantIspMultLimiter.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("ElectricEngineAtmosphericDensityTrustLimiter"))
                    {
                        PluginHelper._electricEngineAtmosphericDensityThrustLimiter = float.Parse(plugin_settings.GetValue("ElectricEngineAtmosphericDensityTrustLimiter"));
                        Debug.Log("[KSP Interstellar] Electric Engine Power Propellant IspMultiplier Limiter set to: " + PluginHelper.ElectricEngineAtmosphericDensityThrustLimiter.ToString("0.0"));
                    }

                    if (plugin_settings.HasValue("MaxAtmosphericAltitudeMult"))
                    {
                        PluginHelper._maxAtmosphericAltitudeMult = double.Parse(plugin_settings.GetValue("MaxAtmosphericAltitudeMult"));
                        Debug.Log("[KSP Interstellar] Maximum Atmospheric Altitude Multiplier set to: " + PluginHelper.MaxAtmosphericAltitudeMult.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("MinAtmosphericAirDensity"))
                    {
                        PluginHelper._minAtmosphericAirDensity = double.Parse(plugin_settings.GetValue("MinAtmosphericAirDensity"));
                        Debug.Log("[KSP Interstellar] Minimum Atmospheric Air Density set to: " + PluginHelper.MinAtmosphericAirDensity.ToString("0.0"));
                    }
                    if (plugin_settings.HasValue("JetUpgradeTech0"))
                    {
                        PluginHelper.JetUpgradeTech0 = plugin_settings.GetValue("JetUpgradeTech0");
                        Debug.Log("[KSP Interstellar] JetUpgradeTech0" + PluginHelper.JetUpgradeTech0);
                    }
                    if (plugin_settings.HasValue("JetUpgradeTech1"))
                    {
                        PluginHelper.JetUpgradeTech1 = plugin_settings.GetValue("JetUpgradeTech1");
                        Debug.Log("[KSP Interstellar] JetUpgradeTech1" + PluginHelper.JetUpgradeTech1);
                    }
                    if (plugin_settings.HasValue("JetUpgradeTech2"))
                    {
                        PluginHelper.JetUpgradeTech2 = plugin_settings.GetValue("JetUpgradeTech2");
                        Debug.Log("[KSP Interstellar] JetUpgradeTech2" + PluginHelper.JetUpgradeTech2);
                    }
                    if (plugin_settings.HasValue("JetUpgradeTech3"))
                    {
                        PluginHelper.JetUpgradeTech3 = plugin_settings.GetValue("JetUpgradeTech3");
                        Debug.Log("[KSP Interstellar] JetUpgradeTech3" + PluginHelper.JetUpgradeTech3);
                    }

                    resources_configured = true;
                }
                else
                {
                    showInstallationErrorMessage();
                }

            }

            if (plugin_init) return;

            gdb = GameDatabase.Instance;
            plugin_init = true;

            List<AvailablePart> available_parts = PartLoader.LoadedPartsList;
            foreach (AvailablePart available_part in available_parts)
            {
                Part prefab_available_part = available_part.partPrefab;
                try
                {
                    if (prefab_available_part.Modules == null) continue;

                    ModuleResourceIntake intake = prefab_available_part.FindModuleImplementing<ModuleResourceIntake>();

                    if (intake != null && intake.resourceName == "IntakeAir")
                    {
                        var pm = prefab_available_part.gameObject.AddComponent<AtmosphericIntake>();
                        prefab_available_part.Modules.Add(pm);
                        pm.area = intake.area;
                        //pm.aoaThreshold = intake.aoaThreshold;
                        pm.intakeTransformName = intake.intakeTransformName;
                        //pm.maxIntakeSpeed = intake.maxIntakeSpeed;
                        pm.unitScalar = intake.unitScalar;
                        //pm.useIntakeCompensation = intake.useIntakeCompensation;
                        //pm.storesResource = intake.storesResource;

                        PartResource intake_air_resource = prefab_available_part.Resources["IntakeAir"];

                        if (intake_air_resource != null && !prefab_available_part.Resources.Contains(InterstellarResourcesConfiguration.Instance.IntakeAtmosphere))
                        {
                            ConfigNode node = new ConfigNode("RESOURCE");
                            node.AddValue("name", InterstellarResourcesConfiguration.Instance.IntakeAtmosphere);
                            node.AddValue("maxAmount", intake_air_resource.maxAmount);
                            node.AddValue("possibleAmount", intake_air_resource.amount);
                            prefab_available_part.AddResource(node);
                        }

                    }

                    if (prefab_available_part.FindModulesImplementing<ModuleDeployableSolarPanel>().Any())
                    {
                        var existingSolarControlModule = prefab_available_part.FindModuleImplementing<FNSolarPanelWasteHeatModule>();
                        if (existingSolarControlModule == null)
                        {
                            ModuleDeployableSolarPanel panel = prefab_available_part.FindModuleImplementing<ModuleDeployableSolarPanel>();
                            if (panel.chargeRate > 0)
                            {
                                //Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "FNSolarPanelWasteHeatModule");
                                Type type = typeof(FNSolarPanelWasteHeatModule);
                                //if (type != null)
                                //{
                                    FNSolarPanelWasteHeatModule pm = prefab_available_part.gameObject.AddComponent(type) as FNSolarPanelWasteHeatModule;
                                    prefab_available_part.Modules.Add(pm);
                                //}
                            }

                            //if (!prefab_available_part.Resources.Contains("WasteHeat") && panel.chargeRate > 0)
                            //{
                            //    ConfigNode node = new ConfigNode("RESOURCE");
                            //    node.AddValue("name", "WasteHeat");
                            //    node.AddValue("maxAmount", panel.chargeRate * 100);
                            //    node.AddValue("possibleAmount", 0);

                            //    PartResource pr = prefab_available_part.AddResource(node);

                            //    if (available_part.resourceInfo != null && pr != null)
                            //    {
                            //        if (available_part.resourceInfo.Length == 0)
                            //            available_part.resourceInfo = pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount;
                            //        else
                            //            available_part.resourceInfo = available_part.resourceInfo + "\n" + pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount;
                            //    }
                            //}
                        }

                    }

                    if (prefab_available_part.FindModulesImplementing<ElectricEngineControllerFX>().Count() > 0)
                    {
                        available_part.moduleInfo = prefab_available_part.FindModulesImplementing<ElectricEngineControllerFX>().First().GetInfo();
                        available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine");
                        AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.FirstOrDefault(modi => modi.moduleName == "Electric Engine Controller");

                        if (mod_info != null)
                             mod_info.moduleName = "Electric Engine";
                    }

                }
                catch (Exception ex)
                {
                    if (prefab_available_part != null)
                        print("[KSP Interstellar] Exception caught adding to: " + prefab_available_part.name + " part: " + ex.ToString());
                    else
                        print("[KSP Interstellar] Exception caught adding to unknown module");
                }
            }
        }
Пример #7
0
 public AIPage(MissionWindowState state, GameDatabase db) : base(state, db)
 {
 }
 private void changeTexture(GameDatabase.TextureInfo newTexture)
 {
     Material mat = getContainerMaterial();
     if (mat != null)
     {
         mat.mainTexture = newTexture.texture;
     }
     else
     {
         NE_Helper.logError("Transform NOT found: " + "Equipment Container");
     }
 }
        private void updateMemoryCount(int originalWidth, int originalHeight, TextureFormat originalFormat, bool originalMipmaps, GameDatabase.TextureInfo Texture, String folder)
        {
            int saved = CacheController.MemorySaved(originalWidth, originalHeight, originalFormat, originalMipmaps, Texture);
            memorySaved += saved;

            if (!folderBytesSaved.ContainsKey(folder))
            {
                folderBytesSaved.Add(folder, 0);
            }
            long folderSaved = folderBytesSaved[folder] + saved;
            folderBytesSaved[folder] = folderSaved;

            Log("Saved " + saved + "B");
            Log("Accumulated Saved " + memorySaved + "B");
        }
 public static int MemorySaved(int originalWidth, int originalHeight, TextureFormat originalFormat, bool originalMipmaps, GameDatabase.TextureInfo Texture)
 {
     int width = Texture.texture.width;
     int height = Texture.texture.height;
     TextureFormat format = Texture.texture.format;
     bool mipmaps = Texture.texture.mipmapCount == 1 ? false : true;
     ActiveTextureManagement.DBGLog("Texture: " + Texture.name);
     ActiveTextureManagement.DBGLog("is normalmap: " + Texture.isNormalMap);
     Texture2D tex = Texture.texture;
     ActiveTextureManagement.DBGLog("originalWidth: " + originalWidth);
     ActiveTextureManagement.DBGLog("originalHeight: " + originalHeight);
     ActiveTextureManagement.DBGLog("originalFormat: " + originalFormat);
     ActiveTextureManagement.DBGLog("originalMipmaps: " + originalMipmaps);
     ActiveTextureManagement.DBGLog("width: " + width);
     ActiveTextureManagement.DBGLog("height: " + height);
     ActiveTextureManagement.DBGLog("format: " + format);
     ActiveTextureManagement.DBGLog("mipmaps: " + mipmaps);
     bool readable = true;
     try { tex.GetPixel(0, 0); }
     catch { readable = false; };
     ActiveTextureManagement.DBGLog("readable: " + readable);
     if (readable != Texture.isReadable)
     { ActiveTextureManagement.DBGLog("Readbility does not match!"); }
     int oldSize = 0;
     int newSize = 0;
     switch (originalFormat)
     {
         case TextureFormat.ARGB32:
         case TextureFormat.RGBA32:
         case TextureFormat.BGRA32:
             oldSize = 4 * (originalWidth * originalHeight);
             break;
         case TextureFormat.RGB24:
             oldSize = 3 * (originalWidth * originalHeight);
             break;
         case TextureFormat.Alpha8:
             oldSize = originalWidth * originalHeight;
             break;
         case TextureFormat.DXT1:
             oldSize = (originalWidth * originalHeight) / 2;
             break;
         case TextureFormat.DXT5:
             oldSize = originalWidth * originalHeight;
             break;
     }
     switch (format)
     {
         case TextureFormat.ARGB32:
         case TextureFormat.RGBA32:
         case TextureFormat.BGRA32:
             newSize = 4 * (width * height);
             break;
         case TextureFormat.RGB24:
             newSize = 3 * (width * height);
             break;
         case TextureFormat.Alpha8:
             newSize = width * height;
             break;
         case TextureFormat.DXT1:
             newSize = (width * height) / 2;
             break;
         case TextureFormat.DXT5:
             newSize = width * height;
             break;
     }
     if (originalMipmaps)
     {
         oldSize += (int)(oldSize * .33f);
     }
     if (mipmaps)
     {
         newSize += (int)(newSize * .33f);
     }
     return (oldSize - newSize);
 }
Пример #11
0
        public void RemoveGame_Test()
        {
            string filename = Path.GetTempFileName();
            IGameDatabase database = new GameDatabase(filename);
            var fakeGameInfo = new Mock<IGameInfo>();
            fakeGameInfo.SetupGet(game => game.Name).Returns("TestGame");
            fakeGameInfo.SetupGet(game => game.UUID).Returns("TESTGAME");
            fakeGameInfo.SetupGet(game => game.PlatformID).Returns("TESTPLATFORM");
            database.AddGame(fakeGameInfo.Object);
            Assert.Equal(fakeGameInfo.Object.UUID, database.GetGameByUUID("TESTGAME").UUID);
            Assert.Equal(fakeGameInfo.Object.Name, database.GetGameByUUID("TESTGAME").Name);
            Assert.Equal(fakeGameInfo.Object.PlatformID, database.GetGameByUUID("TESTGAME").PlatformID);

            database.RemoveGame(fakeGameInfo.Object);
            Assert.Null(database.GetGameByUUID(fakeGameInfo.Object.UUID));
            this.DisposeSqlite();
            File.Delete(filename);
        }
Пример #12
0
 public GenericGameController(GameDatabase db, Game game) : base(game)
 {
     database = db;
 }
        public static void DDSToTexture(GameDatabase.TextureInfo texture, bool inPlace, Vector2 size, string cache = null, bool mipmaps = false)
        {
            /**
             * Kopernicus Planetary System Modifier
             * ====================================
             * Created by: BryceSchroeder and Teknoman117 (aka. Nathaniel R. Lewis)
             * Maintained by: Thomas P., NathanKell and KillAshley
             * Additional Content by: Gravitasi, aftokino, KCreator, Padishar, Kragrathea, OvenProofMars, zengei, MrHappyFace
             * -------------------------------------------------------------
             * This library is free software; you can redistribute it and/or
             * modify it under the terms of the GNU Lesser General Public
             * License as published by the Free Software Foundation; either
             * version 3 of the License, or (at your option) any later version.
             *
             * This library is distributed in the hope that it will be useful,
             * but WITHOUT ANY WARRANTY; without even the implied warranty of
             * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
             * Lesser General Public License for more details.
             *
             * You should have received a copy of the GNU Lesser General Public
             * License along with this library; if not, write to the Free Software
             * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
             * MA 02110-1301  USA
             *
             * This library is intended to be used as a plugin for Kerbal Space Program
             * which is copyright 2011-2015 Squad. Your usage of Kerbal Space Program
             * itself is governed by the terms of its EULA, not the license above.
             *
             * https://kerbalspaceprogram.com
             */
            // Borrowed from stock KSP 1.0 DDS loader (hi Mike!)
            // Also borrowed the extra bits from Sarbian.
            byte[] buffer = System.IO.File.ReadAllBytes(texture.file.fullPath);
            System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(new System.IO.MemoryStream(buffer));
            uint num = binaryReader.ReadUInt32();
            if (num == DDSHeaders.DDSValues.uintMagic)
            {

                DDSHeaders.DDSHeader dDSHeader = new DDSHeaders.DDSHeader(binaryReader);

                if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10)
                {
                    new DDSHeaders.DDSHeaderDX10(binaryReader);
                }
                bool alpha = (dDSHeader.dwFlags & 0x00000002) != 0;
                bool fourcc = (dDSHeader.dwFlags & 0x00000004) != 0;
                bool rgb = (dDSHeader.dwFlags & 0x00000040) != 0;
                bool alphapixel = (dDSHeader.dwFlags & 0x00000001) != 0;
                bool luminance = (dDSHeader.dwFlags & 0x00020000) != 0;
                bool rgb888 = dDSHeader.ddspf.dwRBitMask == 0x000000ff && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x00ff0000;
                //bool bgr888 = dDSHeader.ddspf.dwRBitMask == 0x00ff0000 && dDSHeader.ddspf.dwGBitMask == 0x0000ff00 && dDSHeader.ddspf.dwBBitMask == 0x000000ff;
                bool rgb565 = dDSHeader.ddspf.dwRBitMask == 0x0000F800 && dDSHeader.ddspf.dwGBitMask == 0x000007E0 && dDSHeader.ddspf.dwBBitMask == 0x0000001F;
                bool argb4444 = dDSHeader.ddspf.dwABitMask == 0x0000f000 && dDSHeader.ddspf.dwRBitMask == 0x00000f00 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x0000000f;
                bool rbga4444 = dDSHeader.ddspf.dwABitMask == 0x0000000f && dDSHeader.ddspf.dwRBitMask == 0x0000f000 && dDSHeader.ddspf.dwGBitMask == 0x000000f0 && dDSHeader.ddspf.dwBBitMask == 0x00000f00;

                bool mipmap = (dDSHeader.dwCaps & DDSHeaders.DDSPixelFormatCaps.MIPMAP) != (DDSHeaders.DDSPixelFormatCaps)0u;
                bool isNormalMap = ((dDSHeader.ddspf.dwFlags & 524288u) != 0u || (dDSHeader.ddspf.dwFlags & 2147483648u) != 0u);

                Vector2 newSize = size == default(Vector2) ? new Vector2(dDSHeader.dwWidth, dDSHeader.dwHeight) : size;
                if (fourcc)
                {
                    if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT1)
                    {
                        if (inPlace && !texture.isReadable)
                        {
                            //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                            //we can't control compression, mipmaps, or anything else really, as the texture is still
                            //marked as unreadable. This will update the size and pixel data however.
                            Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap);
                            Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT1, mipmap);
                            tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            Color32[] colors = tmpTexSrc.GetPixels32();
                            colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y);
                            tmpTex.SetPixels32(colors);
                            tmpTex.Apply(false);
                            //size using JPG to force DXT1

                            byte[] file = tmpTex.EncodeToPNG();//tmpTex.EncodeToJPG();
                            if (cache != null)
                            {
                                Directory.GetParent(cache).Create();
                                System.IO.File.WriteAllBytes(cache, file);
                            }
                            texture.texture.LoadImage(file);

                            GameObject.DestroyImmediate(tmpTex);
                            GameDatabase.DestroyImmediate(tmpTexSrc);
                        }
                        else if (inPlace)
                        {
                            texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.RGB24, mipmap);
                            texture.texture.Compress(false);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                        else
                        {
                            GameObject.DestroyImmediate(texture.texture);
                            texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT1, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                    }
                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT3)
                    {
                        if (inPlace && !texture.isReadable)
                        {
                            //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                            //we can't control compression, mipmaps, or anything else really, as the texture is still
                            //marked as unreadable. This will update the size and pixel data however.
                            Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap);
                            Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap);
                            tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            Color32[] colors = tmpTexSrc.GetPixels32();
                            colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y);
                            tmpTex.SetPixels32(colors);
                            tmpTex.Apply(false);
                            //size using JPG to force DXT5
                            byte[] file = tmpTex.EncodeToPNG();
                            if (cache != null)
                            {
                                Directory.GetParent(cache).Create();
                                System.IO.File.WriteAllBytes(cache, file);
                            }
                            texture.texture.LoadImage(file);

                            GameObject.DestroyImmediate(tmpTex);
                            GameDatabase.DestroyImmediate(tmpTexSrc);
                        }
                        else if (inPlace)
                        {
                            texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                        else
                        {
                            GameObject.DestroyImmediate(texture.texture);
                            texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, (TextureFormat)11, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                    }
                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT5)
                    {
                        if (inPlace && !texture.isReadable)
                        {
                            //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                            //we can't control compression, mipmaps, or anything else really, as the texture is still
                            //marked as unreadable. This will update the size and pixel data however.
                            Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap);
                            Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT5, mipmap);
                            tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            Color32[] colors = tmpTexSrc.GetPixels32();
                            colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y);
                            tmpTex.SetPixels32(colors);
                            tmpTex.Apply(false);
                            //size using JPG to force DXT5
                            byte[] file = tmpTex.EncodeToPNG();
                            if (cache != null)
                            {
                                Directory.GetParent(cache).Create();
                                System.IO.File.WriteAllBytes(cache, file);
                            }
                            texture.texture.LoadImage(file);
                            GameObject.DestroyImmediate(tmpTex);
                            GameDatabase.DestroyImmediate(tmpTexSrc);
                        }
                        else if (inPlace)
                        {
                            texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.ARGB32, mipmap);
                            texture.texture.Compress(false);

                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                        else
                        {
                            GameObject.DestroyImmediate(texture.texture);
                            texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, TextureFormat.DXT5, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                    }
                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT2)
                    {
                        Debug.Log("DXT2 not supported");
                    }
                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDXT4)
                    {
                        Debug.Log("DXT4 not supported: ");
                    }
                    else if (dDSHeader.ddspf.dwFourCC == DDSHeaders.DDSValues.uintDX10)
                    {
                        Debug.Log("DX10 dds not supported: ");
                    }
                    else
                        fourcc = false;
                }
                if (!fourcc)
                {
                    TextureFormat textureFormat = TextureFormat.ARGB32;
                    bool ok = true;
                    if (rgb && (rgb888 /*|| bgr888*/))
                    {
                        // RGB or RGBA format
                        textureFormat = alphapixel
                        ? TextureFormat.RGBA32
                        : TextureFormat.RGB24;
                    }
                    else if (rgb && rgb565)
                    {
                        // Nvidia texconv B5G6R5_UNORM
                        textureFormat = TextureFormat.RGB565;
                    }
                    else if (rgb && alphapixel && argb4444)
                    {
                        // Nvidia texconv B4G4R4A4_UNORM
                        textureFormat = TextureFormat.ARGB4444;
                    }
                    else if (rgb && alphapixel && rbga4444)
                    {
                        textureFormat = TextureFormat.RGBA4444;
                    }
                    else if (!rgb && alpha != luminance)
                    {
                        // A8 format or Luminance 8
                        textureFormat = TextureFormat.Alpha8;
                    }
                    else
                    {
                        ok = false;
                        Debug.Log("Only DXT1, DXT5, A8, RGB24, RGBA32, RGB565, ARGB4444 and RGBA4444 are supported");
                    }
                    if (ok)
                    {
                        if (inPlace && !texture.isReadable)
                        {
                            //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                            //we can't control compression, mipmaps, or anything else really, as the texture is still
                            //marked as unreadable. This will update the size and pixel data however.
                            Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmap);
                            Texture2D tmpTexSrc = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap);
                            tmpTexSrc.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            Color32[] colors = tmpTexSrc.GetPixels32();
                            colors = ResizePixels(colors, tmpTexSrc.width, tmpTexSrc.height, (int)newSize.x, (int)newSize.y);
                            tmpTex.SetPixels32(colors);
                            tmpTex.Apply(false);
                            //size using JPG to force alpha-less
                            byte[] file;
                            if (alphapixel)
                            {
                                file = tmpTex.EncodeToPNG();
                            }
                            else
                            {
                                file = tmpTex.EncodeToPNG();//file = tmpTex.EncodeToJPG();
                            }
                            if (cache != null)
                            {
                                Directory.GetParent(cache).Create();
                                System.IO.File.WriteAllBytes(cache, file);
                            }
                            texture.texture.LoadImage(file);
                            GameDatabase.DestroyImmediate(tmpTex);
                            GameDatabase.DestroyImmediate(tmpTexSrc);
                        }
                        else if (inPlace)
                        {
                            texture.texture.Resize((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                        else
                        {
                            GameDatabase.DestroyImmediate(texture.texture);
                            texture.texture = new Texture2D((int)dDSHeader.dwWidth, (int)dDSHeader.dwHeight, textureFormat, mipmap);
                            texture.texture.LoadRawTextureData(binaryReader.ReadBytes((int)(binaryReader.BaseStream.Length - binaryReader.BaseStream.Position)));
                            texture.texture.Apply(false, !texture.isReadable);
                        }
                    }

                }
            }
            else
                Debug.Log("Bad DDS header.");
        }
        public static void TGAToTexture(GameDatabase.TextureInfo texture, bool inPlace, Vector2 size, string cache = null, bool mipmaps = false)
        {
            byte[] imageBuffer = System.IO.File.ReadAllBytes(texture.file.fullPath);

            byte imgType = imageBuffer[2];
            int width = imageBuffer[12] | (imageBuffer[13] << 8);
            int height = imageBuffer[14] | (imageBuffer[15] << 8);

            int depth = imageBuffer[16];
            bool alpha = depth == 32 ? true : false;
            bool hasAlpha = false;
            bool convertToNormalFormat = texture.isNormalMap;

            Color32[] colors = new Color32[width * height];
            int n = 18;
            if (imgType == 2)
            {
                for (int i = 0; i < width * height; i++)
                {
                    colors[i].b = imageBuffer[n++];
                    colors[i].g = imageBuffer[n++];
                    colors[i].r = imageBuffer[n++];
                    if (alpha)
                    {
                        colors[i].a = imageBuffer[n++];
                        if (colors[i].a < byte.MaxValue)
                        {
                            hasAlpha = false;
                        }
                    }
                    else
                    {
                        colors[i].a = 255;
                    }
                    if (convertToNormalFormat)
                    {
                        colors[i].a = colors[i].r;
                        colors[i].r = colors[i].g;
                        colors[i].b = colors[i].g;
                    }
                }
            }
            else if (imgType == 10)
            {
                int i = 0;
                int run = 0;
                while (i < width * height)
                {
                    run = imageBuffer[n++];
                    if ((run & 0x80) != 0)
                    {
                        run = (run ^ 0x80) + 1;
                        colors[i].b = imageBuffer[n++];
                        colors[i].g = imageBuffer[n++];
                        colors[i].r = imageBuffer[n++];
                        if (alpha)
                        {
                            colors[i].a = imageBuffer[n++];
                        }
                        else
                        {
                            colors[i].a = 255;
                        }
                        if (convertToNormalFormat)
                        {
                            colors[i].a = colors[i].r;
                            colors[i].r = colors[i].g;
                            colors[i].b = colors[i].g;
                        }
                        i++;
                        for (int c = 1; c < run; c++, i++)
                        {
                            colors[i] = colors[i - 1];
                        }
                    }
                    else
                    {
                        run += 1;
                        for (int c = 0; c < run; c++, i++)
                        {
                            colors[i].b = imageBuffer[n++];
                            colors[i].g = imageBuffer[n++];
                            colors[i].r = imageBuffer[n++];
                            if (alpha)
                            {
                                colors[i].a = imageBuffer[n++];
                            }
                            else
                            {
                                colors[i].a = 255;
                            }
                            if (convertToNormalFormat)
                            {
                                colors[i].a = colors[i].r;
                                colors[i].r = colors[i].g;
                                colors[i].b = colors[i].g;
                            }
                        }
                    }
                }
            }
            else
            {
                Debug.Log("TGA format is not supported!");
            }

            TextureFormat format = hasAlpha ? TextureFormat.RGBA32 : TextureFormat.RGB24;
            Vector2 newSize = size == default(Vector2) ? new Vector2(width, height) : size;
            if (inPlace)
            {
                //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                //we can't control compression, mipmaps, or anything else really, as the texture is still
                //marked as unreadable. This will update the size and pixel data however.
                colors = ResizePixels(colors, (int)width, (int)height, (int)newSize.x, (int)newSize.y);
                Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmaps);
                tmpTex.SetPixels32(colors);
                tmpTex.Apply(false);
                byte[] file;
                if (hasAlpha)
                {
                    file = tmpTex.EncodeToPNG();
                }
                else
                {
                    file = tmpTex.EncodeToPNG();//file = tmpTex.EncodeToJPG();
                }
                if (cache != null)
                {
                    Directory.GetParent(cache).Create();
                    System.IO.File.WriteAllBytes(cache, file);
                }
                texture.texture.LoadImage(file);
                GameObject.DestroyImmediate(tmpTex);
            }
            else
            {
                colors = ResizePixels(colors, (int)width, (int)height, (int)newSize.x, (int)newSize.y);
                GameObject.DestroyImmediate(texture.texture);
                texture.texture = new Texture2D((int)newSize.x, (int)newSize.y, format, mipmaps);
                texture.texture.SetPixels32(colors);
                if (texture.isCompressed)
                {
                    texture.texture.Compress(true);
                }
                texture.texture.Apply(mipmaps, !texture.isReadable);
            }
        }
        public static bool Reload(GameDatabase.TextureInfo texture, bool inPlace, Vector2 size = default(Vector2), string cache = null, bool mipmaps = true)
        {
            Debug.Log("Getting readable tex from " + texture.file.url + "." + texture.file.fileExtension);

            if (texture.file.fileExtension == "jpg" ||
            texture.file.fileExtension == "jpeg" ||
            texture.file.fileExtension == "png" ||
            texture.file.fileExtension == "truecolor")
            {
                IMGToTexture(texture, inPlace, size, cache, mipmaps);
                return true;
            }
            else if (texture.file.fileExtension == "tga")
            {
                TGAToTexture(texture, inPlace, size, cache, mipmaps);
                return true;
            }
            else if (texture.file.fileExtension == "mbm")
            {
                MBMToTexture(texture, inPlace, size, cache, mipmaps);
                return true;
            }
            else if (texture.file.fileExtension == "dds")
            {
                DDSToTexture(texture, inPlace, size, cache, mipmaps);
                return true;
            }
            return false;
        }
        public static void MBMToTexture(GameDatabase.TextureInfo texture, bool inPlace, Vector2 size, string cache = null, bool mipmaps = false)
        {
            FileStream mbmStream = new FileStream(texture.file.fullPath, FileMode.Open, FileAccess.Read);
            mbmStream.Position = 4;

            uint width = 0, height = 0;
            for (int b = 0; b < 4; b++)
            {
                width >>= 8;
                width |= (uint)(mbmStream.ReadByte() << 24);
            }
            for (int b = 0; b < 4; b++)
            {
                height >>= 8;
                height |= (uint)(mbmStream.ReadByte() << 24);
            }
            mbmStream.Position = 12;
            bool convertToNormalFormat = false;
            if (mbmStream.ReadByte() == 1)
            {
                texture.isNormalMap = true;
            }
            else
            {
                convertToNormalFormat = texture.isNormalMap;
            }

            mbmStream.Position = 16;
            int mbmFormat = mbmStream.ReadByte();
            mbmStream.Position += 3;

            int imageSize = (int)(width * height * 3);
            bool alpha = false;
            bool hasAlpha = false;
            if (mbmFormat == 32)
            {
                imageSize += (int)(width * height);
                alpha = true;
            }

            byte[] imageBuffer = new byte[mbmStream.Length];
            mbmStream.Read(imageBuffer, 0, imageBuffer.Length);

            mbmStream.Close();

            Color32[] colors = new Color32[width * height];
            int n = 0;
            for (int i = 0; i < width * height; i++)
            {
                colors[i].r = imageBuffer[n++];
                colors[i].g = imageBuffer[n++];
                colors[i].b = imageBuffer[n++];
                if (alpha)
                {
                    colors[i].a = imageBuffer[n++];
                    if (colors[i].a < Byte.MaxValue)
                    {
                        hasAlpha = true;
                    }
                }
                else
                {
                    colors[i].a = 255;
                }
                if (convertToNormalFormat)
                {
                    colors[i].a = colors[i].r;
                    colors[i].r = colors[i].g;
                    colors[i].b = colors[i].g;
                }
            }

            TextureFormat format = hasAlpha ? TextureFormat.RGBA32 : TextureFormat.RGB24;
            Vector2 newSize = size == default(Vector2) ? new Vector2(width, height) : size;
            if (inPlace)
            {
                //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                //we can't control compression, mipmaps, or anything else really, as the texture is still
                //marked as unreadable. This will update the size and pixel data however.
                colors = ResizePixels(colors, (int)width, (int)height, (int)newSize.x, (int)newSize.y);
                Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmaps);
                tmpTex.SetPixels32(colors);
                tmpTex.Apply(false);
                byte[] file;
                if (hasAlpha)
                {
                    file = tmpTex.EncodeToPNG();
                }
                else
                {
                    file = tmpTex.EncodeToPNG();//file = tmpTex.EncodeToJPG();
                }
                if (cache != null)
                {
                    Directory.GetParent(cache).Create();
                    System.IO.File.WriteAllBytes(cache, file);
                }
                texture.texture.LoadImage(file);
                GameObject.DestroyImmediate(tmpTex);
            }
            else
            {
                colors = ResizePixels(colors, (int)width, (int)height, (int)newSize.x, (int)newSize.y);
                GameObject.DestroyImmediate(texture.texture);
                texture.texture = new Texture2D((int)newSize.x, (int)newSize.y, format, mipmaps);
                texture.texture.SetPixels32(colors);
                if (texture.isCompressed)
                {
                    texture.texture.Compress(true);
                }
                texture.texture.Apply(mipmaps, !texture.isReadable);
            }
        }
        public static void IMGToTexture(GameDatabase.TextureInfo texture, bool inPlace, Vector2 size, string cache = null, bool mipmaps = false)
        {
            byte[] imageBuffer = System.IO.File.ReadAllBytes(texture.file.fullPath);

            Texture2D tex = new Texture2D(2, 2);
            bool convertToNormalFormat = texture.isNormalMap;

            tex.LoadImage(imageBuffer);

            Color32[] colors = tex.GetPixels32();

            if (convertToNormalFormat)
            {
                for (int i = 0; i < colors.Length; i++)
                {
                    colors[i].a = colors[i].r;
                    colors[i].r = colors[i].g;
                    colors[i].b = colors[i].g;
                }
            }

            bool hasAlpha = HasAlpha(colors);

            TextureFormat format = hasAlpha ? TextureFormat.RGBA32 : TextureFormat.RGB24;
            Vector2 newSize = size == default(Vector2) ? new Vector2(tex.width, tex.height) : size;
            if (inPlace)
            {
                //This is a small hack to re-load the texture, even when it isn't readable. Unfortnately,
                //we can't control compression, mipmaps, or anything else really, as the texture is still
                //marked as unreadable. This will update the size and pixel data however.
                colors = ResizePixels(colors, tex.width, tex.height, (int)newSize.x, (int)newSize.y);
                Texture2D tmpTex = new Texture2D((int)newSize.x, (int)newSize.y, TextureFormat.ARGB32, mipmaps);
                tmpTex.SetPixels32(colors);
                tmpTex.Apply(false);
                //TODO: this could be optimized when not resizing to use the encoding above.
                byte[] file;
                if (hasAlpha)
                {
                    file = tmpTex.EncodeToPNG();
                }
                else
                {
                    file = tmpTex.EncodeToPNG();//file = tmpTex.EncodeToJPG();
                }
                if (cache != null)
                {
                    Directory.GetParent(cache).Create();
                    System.IO.File.WriteAllBytes(cache, file);
                }
                texture.texture.LoadImage(file);
                GameObject.DestroyImmediate(tmpTex);
            }
            else
            {
                colors = ResizePixels(colors, tex.width, tex.height, (int)newSize.x, (int)newSize.y);
                GameObject.DestroyImmediate(texture.texture);
                texture.texture = new Texture2D((int)newSize.x, (int)newSize.y, format, mipmaps);
                texture.texture.SetPixels32(colors);
                if (texture.isCompressed)
                {
                    texture.texture.Compress(true);
                }
                texture.texture.Apply(mipmaps, !texture.isReadable);
            }

            GameObject.DestroyImmediate(tex);
        }
Пример #18
0
        public static void DebugDesign(AssetDatabase assetDatabase, GameDatabase gameDatabase, DesignInfo designIn)
        {
            try
            {

            }
            catch (Exception ex)
            {
                SotsosLog("exception: {0}",ex.Message);
            }
        }
Пример #19
0
 = Path.GetFullPath(Path.Combine(GameDatabase.Instance.PluginDataFolder, "GameData"));
Пример #20
0
		public void Update() {
            this.enabled = true;
            AvailablePart intakePart = PartLoader.getPartInfoByName("CircularIntake");
            if (intakePart != null) {
                if (intakePart.partPrefab.FindModulesImplementing<AtmosphericIntake>().Count <= 0 && PartLoader.Instance.IsReady()) {
                    plugin_init = false;
                }
            }

            if (!resources_configured) {
                ConfigNode plugin_settings = GameDatabase.Instance.GetConfigNode("Interstellar/InterstellarSettings/InterstellarSettings");
                if (plugin_settings != null) {
                    if (plugin_settings.HasValue("HydrogenResourceName")) {
                        PluginHelper.hydrogen_resource_name = plugin_settings.GetValue("HydrogenResourceName");
                        Debug.Log("[KSP Interstellar] Hydrogen resource name set to " + PluginHelper.hydrogen_resource_name);
                    }
                    if (plugin_settings.HasValue("OxygenResourceName")) {
                        PluginHelper.oxygen_resource_name = plugin_settings.GetValue("OxygenResourceName");
                        Debug.Log("[KSP Interstellar] Oxygen resource name set to " + PluginHelper.oxygen_resource_name);
                    }
                    if (plugin_settings.HasValue("AluminiumResourceName")) {
                        PluginHelper.aluminium_resource_name = plugin_settings.GetValue("AluminiumResourceName");
                        Debug.Log("[KSP Interstellar] Aluminium resource name set to " + PluginHelper.aluminium_resource_name);
                    }
                    if (plugin_settings.HasValue("MethaneResourceName")) {
                        PluginHelper.methane_resource_name = plugin_settings.GetValue("MethaneResourceName");
                        Debug.Log("[KSP Interstellar] Methane resource name set to " + PluginHelper.methane_resource_name);
                    }
                    if (plugin_settings.HasValue("ArgonResourceName")) {
                        PluginHelper.argon_resource_name = plugin_settings.GetValue("ArgonResourceName");
                        Debug.Log("[KSP Interstellar] Argon resource name set to " + PluginHelper.argon_resource_name);
                    }
                    if (plugin_settings.HasValue("WaterResourceName")) {
                        PluginHelper.water_resource_name = plugin_settings.GetValue("WaterResourceName");
                        Debug.Log("[KSP Interstellar] Water resource name set to " + PluginHelper.water_resource_name);
                    }
                    if (plugin_settings.HasValue("HydrogenPeroxideResourceName")) {
                        PluginHelper.hydrogen_peroxide_resource_name = plugin_settings.GetValue("HydrogenPeroxideResourceName");
                        Debug.Log("[KSP Interstellar] Hydrogen Peroxide resource name set to " + PluginHelper.hydrogen_peroxide_resource_name);
                    }
                    if (plugin_settings.HasValue("AmmoniaResourceName")) {
                        PluginHelper.ammonia_resource_name = plugin_settings.GetValue("AmmoniaResourceName");
                        Debug.Log("[KSP Interstellar] Ammonia resource name set to " + PluginHelper.ammonia_resource_name);
                    }
                    if (plugin_settings.HasValue("ThermalMechanicsDisabled")) {
                        PluginHelper.is_thermal_dissip_disabled = bool.Parse(plugin_settings.GetValue("ThermalMechanicsDisabled"));
                        Debug.Log("[KSP Interstellar] ThermalMechanics set to enabled: " + !PluginHelper.is_thermal_dissip_disabled);
                    }
                    if (plugin_settings.HasValue("RadiatorEmissiveGlowDisabled"))
                    {
                        PluginHelper.is_radiator_emissive_glow_disabled = bool.Parse(plugin_settings.GetValue("RadiatorEmissiveGlowDisabled"));
                        Debug.Log("[KSP Interstellar] Radiator Glow set to enabled: " + !PluginHelper.is_radiator_emissive_glow_disabled);
                    }
                    resources_configured = true;
                } else {
                    showInstallationErrorMessage();
                }
                
            }

            

			if (!plugin_init) {
                gdb = GameDatabase.Instance;
				plugin_init = true;

                AvailablePart kerbalRadiationPart = PartLoader.getPartInfoByName("kerbalEVA");
                if (kerbalRadiationPart.partPrefab.Modules != null) {
                    if (kerbalRadiationPart.partPrefab.FindModulesImplementing<FNModuleRadiation>().Count == 0) {
                        kerbalRadiationPart.partPrefab.gameObject.AddComponent<FNModuleRadiation>();
                    }
                } else {
                    kerbalRadiationPart.partPrefab.gameObject.AddComponent<FNModuleRadiation>();
                }

				List<AvailablePart> available_parts = PartLoader.LoadedPartsList;
				foreach (AvailablePart available_part in available_parts) {
					Part prefab_available_part = available_part.partPrefab;
					try {
						if(prefab_available_part.Modules != null) {
														
							if(prefab_available_part.FindModulesImplementing<ModuleResourceIntake>().Count > 0) {
								ModuleResourceIntake intake = prefab_available_part.Modules["ModuleResourceIntake"] as ModuleResourceIntake;
								if(intake.resourceName == "IntakeAir") {
									Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "AtmosphericIntake");
									AtmosphericIntake pm = null;
									if(type != null) {
										pm = prefab_available_part.gameObject.AddComponent(type) as AtmosphericIntake;
										prefab_available_part.Modules.Add(pm);
										pm.area = intake.area*intake.unitScalar*intake.maxIntakeSpeed/20;
									}

									PartResource intake_air_resource = prefab_available_part.Resources["IntakeAir"];

                                    if (intake_air_resource != null && !prefab_available_part.Resources.Contains("IntakeAtm")) {
										ConfigNode node = new ConfigNode("RESOURCE");
										node.AddValue("name", "IntakeAtm");
										node.AddValue("maxAmount", intake_air_resource.maxAmount);
										node.AddValue("amount", intake_air_resource.amount);
										prefab_available_part.AddResource(node);
									}
								}

							}

                            if (prefab_available_part.FindModulesImplementing<ModuleDeployableSolarPanel>().Count > 0) {
                                ModuleDeployableSolarPanel panel = prefab_available_part.Modules["ModuleDeployableSolarPanel"] as ModuleDeployableSolarPanel;
                                if (panel.chargeRate > 0) {
                                    Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "FNSolarPanelWasteHeatModule");
                                    FNSolarPanelWasteHeatModule pm = null;
                                    if (type != null) {
                                        pm = prefab_available_part.gameObject.AddComponent(type) as FNSolarPanelWasteHeatModule;
                                        prefab_available_part.Modules.Add(pm);
                                    }
                                }
                                
                                                                
                                if (!prefab_available_part.Resources.Contains("WasteHeat") && panel.chargeRate > 0) {
                                    ConfigNode node = new ConfigNode("RESOURCE");
                                    node.AddValue("name", "WasteHeat");
                                    node.AddValue("maxAmount", panel.chargeRate * 100);
                                    node.AddValue("amount", 0);
                                    PartResource pr = prefab_available_part.AddResource(node);

                                    if (available_part.resourceInfo != null && pr != null) {
                                        if (available_part.resourceInfo.Length == 0) {
                                            available_part.resourceInfo = pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount;
                                        } else {
                                            available_part.resourceInfo = available_part.resourceInfo + "\n" + pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount;
                                        }
                                    }
                                }

                                if (!prefab_available_part.Resources.Contains("Megajoules") && panel.chargeRate > 0)
                                {
                                    ConfigNode node = new ConfigNode("RESOURCE");
                                    node.AddValue("name", "Megajoules");
                                    node.AddValue("maxAmount", panel.chargeRate);
                                    node.AddValue("amount", 0);
                                    PartResource pr = prefab_available_part.AddResource(node);

                                    if (available_part.resourceInfo != null && pr != null)
                                    {
                                        if (available_part.resourceInfo.Length == 0)
                                        {
                                            available_part.resourceInfo = pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount;
                                        }
                                        else
                                        {
                                            available_part.resourceInfo = available_part.resourceInfo + "\n" + pr.resourceName + ":" + pr.amount + " / " + pr.maxAmount;
                                        }
                                    }
                                }
                            }

							if(prefab_available_part.FindModulesImplementing<ElectricEngineController>().Count() > 0) {
								available_part.moduleInfo = prefab_available_part.FindModulesImplementing<ElectricEngineController>().First().GetInfo();
                                available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine");
                                AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.Where(modi => modi.moduleName == "Electric Engine Controller").First();
                                mod_info.moduleName = "Electric Engine";
							}

							if(prefab_available_part.FindModulesImplementing<FNNozzleController>().Count() > 0) {
								available_part.moduleInfo = prefab_available_part.FindModulesImplementing<FNNozzleController>().First().GetInfo();
                                available_part.moduleInfos.RemoveAll(modi => modi.moduleName == "Engine");
                                AvailablePart.ModuleInfo mod_info = available_part.moduleInfos.Where(modi => modi.moduleName == "FNNozzle Controller").First();
                                mod_info.moduleName = "Thermal Nozzle";
							}
                            
							if(prefab_available_part.CrewCapacity > 0 || prefab_available_part.FindModulesImplementing<ModuleCommand>().Count > 0) {
								Type type = AssemblyLoader.GetClassByName(typeof(PartModule), "FNModuleRadiation");
								FNModuleRadiation pm = null;
								if(type != null) {
									pm = prefab_available_part.gameObject.AddComponent(type) as FNModuleRadiation;
									prefab_available_part.Modules.Add(pm);
									double rad_hardness = prefab_available_part.mass /(Math.Max(prefab_available_part.CrewCapacity,0.1))*7.5;
									pm.rad_hardness = rad_hardness;
                                    AvailablePart.ModuleInfo minfo = new AvailablePart.ModuleInfo();
                                    minfo.moduleName = "Radiation Status";
                                    minfo.info = pm.GetInfo();
                                    available_part.moduleInfos.Add(minfo);
								}
                                print("Adding ModuleRadiation to " + prefab_available_part.name);
							}
						}
					}catch(Exception ex) {
                        if (prefab_available_part != null) {
                            print("[KSP Interstellar] Exception caught adding to: " + prefab_available_part.name + " part: " + ex.ToString());
                        } else {
                            print("[KSP Interstellar] Exception caught adding to unknown module");
                        }
					}


				}
			}

			//Destroy (this);
		}
Пример #21
0
    /*
     * NETWORK-SPECIFIC
     */
    public override void Attached()
    {
        // SETUP
        db = GameObject.FindGameObjectWithTag("Database").GetComponent <GameDatabase>();

        renderer  = GetComponent <Renderer> ();
        stats     = GetComponent <ActorStats> ();
        inventory = GetComponent <Inventory> ();
        skillset  = GetComponent <PlayerSkillset>();

        // CUSTOMISATION TOKEN
        // Loads the player's inventory, chosen faction and race etc.,
        // which were selected in the character creation screen.
        var customisation = (CustomisationToken)entity.attachToken;

        stats.LoadCustomisation(customisation);
        //stats.LoadInterface();
        inventory.LoadInventory();
        inventory.LoadInterface();


        if (entity.isOwner)
        {
            // Sync customisation data to server...
            // BACKGROUND DATA (faction, race)
            state.BackgroundData.StartingFaction = stats.actorStartingFaction;
            state.BackgroundData.CharacterRace   = stats.actorRaceName;


            // STATS
            // Gets each property in the actor's stats component.
            // For each one, sync with the player's stats on the server.
            BindingFlags     flags      = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
            PropertyInfo[]   properties = stats.GetType().GetProperties(flags);
            BoltActorStatset statset    = state.BoltActorStatset;
            for (int h = 0; h < properties.Length; h++)
            {
                try
                {
                    statset.Statset[h].StatName  = properties[h].Name;
                    statset.Statset[h].StatValue = (System.Int32)properties[h].GetValue(stats, null);
                }
                catch (System.InvalidCastException cast)
                {
                    Debug.LogWarning(cast.Message);
                    Debug.LogWarning(properties[h].Name);
                }
            }

            // SKILLSET
            for (int i = 0; i < skillset.PlayerSkills.Count; i++)
            {
                state.BoltPlayerSkillset.Skillset[i].SkillName  = skillset.PlayerSkills[i].GetSkill().SkillName;
                state.BoltPlayerSkillset.Skillset[i].SkillLevel = skillset.PlayerSkills[i].GetLevel();
            }

            SyncInventory();
            AddRacePerks(stats.actorRaceName);  // adds the perks related to the player's race.

            // debug: give the player a random colour.
            state.DebugColour = new Color(Random.value, Random.value, Random.value);
        }

        state.AddCallback("BoltActorStatset", StatsChanged);
        state.AddCallback("BoltPlayerSkillset", SkillsetChanged);
        state.AddCallback("DebugColour", ColourChanged);
        state.AddCallback("BackgroundData", BackgroundDataChanged);
    }