Exemple #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ex"></param>
        public static void OnExceptionForwarded(Exception ex)
        {
            try
            {
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableExceptionReporting))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("Exception Reporting telemetry disabled.");
                    }
                    return;
                }

                if (ex != null)
                {
                    TelemetryKH telemetry = new TelemetryKH();
                    telemetry.AddEvent("error", new Telemetry.Pair[]
                    {
                        new Telemetry.Pair("type", ex.GetType().Name),
                        new Telemetry.Pair("message", ex.Message)
                    });
                    telemetry.Push();
                }
            }
            catch (Exception ex2)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex2.GetType() + ": Telemetry event failed " + ex2.Message);
            }
        }
Exemple #2
0
        public static void MilestoneUnlocked(MilestoneInfo info)
        {
            try
            {
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableMilestoneUnlock))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("Milestone telemetry disabled.");
                    }
                    return;
                }

                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent("unlocking", new Telemetry.Pair[]
                {
                    new Telemetry.Pair("name", (!(info != null)) ? "Name unavailable" : info.name),
                    new Telemetry.Pair("gameTime", (!Singleton <SimulationManager> .exists) ? "Similation not running o_O" : Singleton <SimulationManager> .instance.m_currentGameTime.ToString("dd/MM/yyyy H:mm:ss"))
                });
                telemetry.Push();
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
Exemple #3
0
        public static void OnStoreClicked()
        {
            try
            {
                if (Mod.DEBUG_LOG_ON)
                {
                    Helper.dbgLog("Store Click!");
                }

                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableOnStoreClick))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("Store Click telemetry disabled.");
                    }
                    return;
                }

                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent("store_clicked", new Telemetry.Pair[0]);
                telemetry.Push();
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
Exemple #4
0
        public static void OnFeedClicked(string url)
        {
            try
            {
                if (Mod.DEBUG_LOG_ON)
                {
                    Helper.dbgLog("Clicked url!");
                }
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableOnClicks))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("Feed Click telemetry disabled.");
                    }
                    return;
                }

                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent("newsfeed_clicked", new Telemetry.Pair[]
                {
                    new Telemetry.Pair("target", url)
                });
                telemetry.Push();
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
Exemple #5
0
        public static void ParadoxLogin(bool autoLogin)
        {
            try
            {
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableParadoxLogin))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("PDX Login telemetry disabled.");
                    }
                    return;
                }

                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent(Telemetry.Event.Login, new Telemetry.Pair[]
                {
                    new Telemetry.Pair("autologin", autoLogin)
                });
                telemetry.Push();
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
Exemple #6
0
        void SetupAssetDistrictStyle(Package.Asset asset)
        {
            int i;

            try
            {
                if (asset != null && asset.isEnabled)
                {
                    DistrictStyleMetaData districtStyleMetaData = asset.Instantiate <DistrictStyleMetaData>();

                    if (districtStyleMetaData != null && !districtStyleMetaData.builtin)
                    {
                        districtStyleMetaDatas.Add(districtStyleMetaData);
                        districtStylePackages.Add(asset.package);

                        if (districtStyleMetaData.assets != null)
                        {
                            for (i = 0; i < districtStyleMetaData.assets.Length; i++)
                            {
                                styleBuildings.Add(districtStyleMetaData.assets[i]);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.Modding, string.Concat(new object[] { ex.GetType(), ": Loading custom district style failed[", asset, "]\n", ex.Message }));
            }
        }
Exemple #7
0
        public static void EndSession(ItemClass.Availability availability)
        {
            try
            {
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableEndSession))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("End Session telemetry disabled.");
                    }
                    return;
                }

                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent("end_session", new Telemetry.Pair[]
                {
                    new Telemetry.Pair("type", availability.ToString())
                });
                telemetry.Push();
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
Exemple #8
0
        public static void SessionLoaded(long mainTime, long scenesTime, long simulationTime)
        {
            try
            {
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableSessionLoaded))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("Session Loaded telemetry disabled.");
                    }
                    return;
                }

                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent("session_loaded", new Telemetry.Pair[]
                {
                    new Telemetry.Pair("totalTime", Math.Max(mainTime, Math.Max(scenesTime, simulationTime))),
                    new Telemetry.Pair("main", mainTime),
                    new Telemetry.Pair("scenes", scenesTime),
                    new Telemetry.Pair("simulationTime", simulationTime),
                    new Telemetry.Pair("gameTime", (!Singleton <SimulationManager> .exists) ? "Similation not running o_O" : Singleton <SimulationManager> .instance.m_currentGameTime.ToString("dd/MM/yyyy H:mm:ss"))
                });
                telemetry.Push();
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
Exemple #9
0
        private void WorkshopAdPanelOnQueryCompleted(UGCDetails result, bool ioError)
        {
            try
            {
                var workshopAdPanel = GameObject.Find("WorkshopAdPanel").GetComponent <WorkshopAdPanel>();

                if (result.result == Result.OK)
                {
                    UIComponent uIComponent = Util.GetPrivate <UIScrollablePanel>(workshopAdPanel, "m_ScrollContainer").AttachUIComponent
                                                  (UITemplateManager.GetAsGameObject("WorkshopAdTemplate"));

                    string price = String.Format(CultureInfo.CurrentCulture, "{0:C}", 0.99f);
                    if (UnityEngine.Random.Range(0, 2) == 0)
                    {
                        price = String.Format(CultureInfo.CurrentCulture, "{0:C}", 2.49f);
                    }
                    else if (UnityEngine.Random.Range(0, 7) == 0)
                    {
                        price = String.Format(CultureInfo.CurrentCulture, "{0:C}", 4.99f);
                    }
                    else if (UnityEngine.Random.Range(0, 25) == 0)
                    {
                        price = String.Format(CultureInfo.CurrentCulture, "{0:C}", 8.49f);
                    }

                    uIComponent.Find <UILabel>("Title").text = String.Format("{0} - {1}\n{2}", result.title, price, result.tags);

                    if (result.image != null)
                    {
                        result.image.wrapMode = TextureWrapMode.Clamp;
                    }
                    uIComponent.Find <UITextureSprite>("Image").texture = result.image;
                    UIProgressBar uIProgressBar = uIComponent.Find <UIProgressBar>("Rating");
                    uIProgressBar.isVisible = (result.score >= 0f);
                    uIProgressBar.value     = result.score;
                    uIComponent.Find <UIButton>("ClickableArea").eventClick += delegate(UIComponent c, UIMouseEventParameter p)
                    {
                        if (Steam.IsOverlayEnabled())
                        {
                            Steam.ActivateGameOverlayToWorkshopItem(result.publishedFileId);
                        }
                    };
                }
                else
                {
                    CODebugBase <LogChannel> .Warn(LogChannel.Core, string.Concat(new object[]
                    {
                        "Workshop item: ",
                        result.publishedFileId,
                        " error: ",
                        result.result
                    }));
                }
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Error(LogChannel.Core, ex.ToString());
            }
        }
Exemple #10
0
        static string ResolveLegacyType(string type)
        {
            string text = PackageHelper.ResolveLegacyTypeHandler(type);

            CODebugBase <InternalLogChannel> .Warn(InternalLogChannel.Packer, string.Concat("Unkown type detected. Attempting to resolve from '", type, "' to '", text, "'"));

            return(text);
        }
Exemple #11
0
        static string ResolveLegacyMember(Type fieldType, Type classType, string member)
        {
            string text = PackageHelper.ResolveLegacyMemberHandler(classType, member);

            CODebugBase <InternalLogChannel> .Warn(InternalLogChannel.Packer, string.Concat("Unkown member detected of type ", fieldType.FullName, " in ", classType.FullName,
                                                                                            ". Attempting to resolve from '", member, "' to '", text, "'"));

            return(text);
        }
Exemple #12
0
        void PostprocessDistricStyles()
        {
            int i, j;

            for (i = 0; i < districtStyleMetaDatas.m_size; i++)
            {
                try
                {
                    DistrictStyleMetaData districtStyleMetaData = districtStyleMetaDatas.m_buffer[i];
                    DistrictStyle         districtStyle         = new DistrictStyle(districtStyleMetaData.name, false);

                    if (districtStylePackages.m_buffer[i].GetPublishedFileID() != PublishedFileId.invalid)
                    {
                        districtStyle.PackageName = districtStylePackages.m_buffer[i].packageName;
                    }

                    if (districtStyleMetaData.assets != null)
                    {
                        for (j = 0; j < districtStyleMetaData.assets.Length; j++)
                        {
                            BuildingInfo bi = PrefabCollection <BuildingInfo> .FindLoaded(districtStyleMetaData.assets[j] + "_Data");

                            if (bi != null)
                            {
                                districtStyle.Add(bi);

                                if (districtStyleMetaData.builtin) // this is always false
                                {
                                    bi.m_dontSpawnNormally = !districtStyleMetaData.assetRef.isEnabled;
                                }
                            }
                            else
                            {
                                CODebugBase <LogChannel> .Warn(LogChannel.Modding, "Warning: Missing asset (" + districtStyleMetaData.assets[i] + ") in style " + districtStyleMetaData.name);
                            }
                        }

                        districtStyles.Add(districtStyle);
                    }
                }
                catch (Exception ex)
                {
                    CODebugBase <LogChannel> .Warn(LogChannel.Modding, ex.GetType() + ": Loading district style failed\n" + ex.Message);
                }
            }

            Singleton <DistrictManager> .instance.m_Styles = districtStyles.ToArray();

            if (Singleton <BuildingManager> .exists)
            {
                Singleton <BuildingManager> .instance.InitializeStyleArray(districtStyles.Count);
            }
        }
Exemple #13
0
        int HandleUnknownType(string type)
        {
            int num = PackageHelper.UnknownTypeHandler(type);

            CODebugBase <InternalLogChannel> .Warn(InternalLogChannel.Packer, string.Concat("Unexpected type '", type, "' detected. No resolver handled this type. Skipping ", num, " bytes."));

            if (num > 0)
            {
                reader.ReadBytes(num);
                return(num);
            }
            return(-1);
        }
 public override void InitializePrefab()
 {
     Logger.LogLineNumber();
     base.InitializePrefab();
     Logger.LogLineNumber();
     if (this.m_class == null)
     {
         Logger.LogLineNumber();
         throw new PrefabException(this, "Class missing");
     }
     if (this.m_skinRenderer != null)
     {
         Logger.LogLineNumber();
         Material sharedMaterial = this.m_skinRenderer.sharedMaterial;
         this.m_color0 = sharedMaterial.GetColor("_ColorV0");
         this.m_color1 = sharedMaterial.GetColor("_ColorV1");
         this.m_color2 = sharedMaterial.GetColor("_ColorV2");
         this.m_color3 = sharedMaterial.GetColor("_ColorV3");
     }
     else
     {
         this.m_color0 = Color.white;
         this.m_color1 = Color.white;
         this.m_color2 = Color.white;
         this.m_color3 = Color.white;
     }
     if (this.m_lodObject != null)
     {
         Logger.LogLineNumber();
         MeshFilter component = this.m_lodObject.GetComponent <MeshFilter>();
         this.m_lodMesh     = component.sharedMesh;
         this.m_lodMaterial = this.m_lodObject.GetComponent <Renderer>().sharedMaterial;
         this.GenerateCombinedLodMesh();
     }
     else
     {
         CODebugBase <LogChannel> .Warn(LogChannel.Core, "LOD missing: " + base.gameObject.name, base.gameObject);
     }
     this.RefreshLevelOfDetail();
     if (this.m_zombieAI == null)
     {
         this.m_zombieAI        = base.GetComponent <ZombieAI>();
         this.m_zombieAI.m_info = this;
         this.m_zombieAI.InitializeAI();
     }
     this.m_lodLocations = new Matrix4x4[16];
     this.m_lodColors    = new Color[16];
     this.m_lodCount     = 0;
     this.m_lodMin       = new Vector3(100000f, 100000f, 100000f);
     this.m_lodMax       = new Vector3(-100000f, -100000f, -100000f);
 }
Exemple #15
0
        public static void CustomContentInfo(int buildingsCount, int propsCount, int treeCount, int vehicleCount)
        {
            try
            {
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableCustomContent))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("Custom Content telemetry disabled.");
                    }
                    return;
                }


                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent("custom_content", new Telemetry.Pair[]
                {
                    new Telemetry.Pair("buildings", buildingsCount),
                    new Telemetry.Pair("props", propsCount),
                    new Telemetry.Pair("trees", treeCount),
                    new Telemetry.Pair("vehicles", vehicleCount)
                });
                telemetry.AddEvent("custom_mods", new Telemetry.Pair[]
                {
                    new Telemetry.Pair("enabledModCount", Singleton <PluginManager> .instance.enabledModCount),
                    new Telemetry.Pair("modCount", Singleton <PluginManager> .instance.modCount)
                });
                telemetry.Push();
                foreach (PluginManager.PluginInfo current in Singleton <PluginManager> .instance.GetPluginsInfo())
                {
                    if (current.isEnabled)
                    {
                        TelemetryKH telemetry2 = new TelemetryKH();
                        telemetry2.AddEvent("mod_used", new Telemetry.Pair[]
                        {
                            new Telemetry.Pair("modName", current.name),
                            new Telemetry.Pair("modWorkshopID", (!(current.publishedFileID != PublishedFileId.invalid)) ? "none" : current.publishedFileID.ToString()),
                            new Telemetry.Pair("assemblyInfo", current.assembliesString)
                        });
                        telemetry2.Push();
                    }
                }
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
Exemple #16
0
 public static void ParadoxAccountCreated()
 {
     try
     {
         if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll))
         {
             if (Mod.DEBUG_LOG_ON)
             {
                 Helper.dbgLog("PDX account creation event telemetry disabled.");
             }
             return;
         }
         TelemetryKH telemetry = new TelemetryKH();
         telemetry.AddEvent(Telemetry.Event.AccountCreated, new Telemetry.Pair[0]);
         telemetry.Push();
     }
     catch (Exception ex)
     {
         CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
     }
 }
Exemple #17
0
        private static void OnApplicationQuit()
        {
            try
            {
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableOnQuit))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("OnApplicationQuit telemetry disabled.");
                    }
                    return;
                }

                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent(Telemetry.Event.ExitGame, new Telemetry.Pair[0]);
                telemetry.Push();
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
Exemple #18
0
        public static void StartSession(string mapName, string playerMap, SimulationManager.UpdateMode mode, SimulationMetaData ngs)
        {
            try
            {
                if (Mod.IsEnabled && Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) ||
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableStartSession))
                {
                    if (Mod.DEBUG_LOG_ON)
                    {
                        Helper.dbgLog("Start Session telemetry disabled.");
                    }
                    return;
                }

                TelemetryKH telemetry = new TelemetryKH();
                telemetry.AddEvent("start_session", new Telemetry.Pair[]
                {
                    new Telemetry.Pair("type", playerMap),
                    new Telemetry.Pair("start_flag", mode.ToString()),
                    new Telemetry.Pair("map_name", Path.GetFileName(mapName))
                });
                if (ngs != null)
                {
                    telemetry.AddEvent("start_session", new Telemetry.Pair[]
                    {
                        new Telemetry.Pair("environment", ngs.m_environment),
                        new Telemetry.Pair("invert_traffic", ngs.m_invertTraffic),
                        new Telemetry.Pair("guid", ngs.m_gameInstanceIdentifier)
                    });
                }
                telemetry.Push();
            }
            catch (Exception ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Telemetry event failed " + ex.Message);
            }
        }
Exemple #19
0
        public static void RenderSpriteLine(DynamicFontRenderer renderer, UIMarkupToken token, Vector3 position, UIRenderData destination)
        {
            string[] args = token.GetAttribute(0)?.m_Value?.value?.Split(new char[] { ',' }, 3);
            if (args == null || args.Length != 3)
            {
                LogUtils.DoErrorLog($"INVALID ARGUMENT: {token.GetAttribute(0)?.m_Value?.value ?? "<NULL>"}");
                return;
            }

            UITextureAtlas.SpriteInfo spriteInfo = renderer.spriteAtlas[args[0]];
            if (spriteInfo == null)
            {
                CODebugBase <InternalLogChannel> .Warn(InternalLogChannel.UI, "Missing sprite " + args[0] + " in " + renderer.spriteAtlas.name);
            }
            else
            {
                var midLine = new Vector3(position.x, position.y - (((UIDynamicFont)renderer.font).baseline * renderer.textScale / 2));

                Texture2D texture        = renderer.spriteAtlas.texture;
                float     calcHeight     = ((UIDynamicFont)renderer.font).baseline * renderer.textScale * 2f;
                float     calcProportion = spriteInfo.region.width * texture.width / (spriteInfo.region.height * texture.height);
                float     calcWidth      = Mathf.CeilToInt(calcHeight * calcProportion);

                int height = Mathf.CeilToInt(calcHeight);
                int width  = Mathf.CeilToInt(calcWidth);

                Color32 bgColor        = ColorExtensions.FromRGB(args[1]);
                Color32 color2         = ApplyOpacity(renderer, bgColor);
                var     size           = new Vector3(width, height);
                Vector2 textDimensions = MeasureTextWidth(renderer, args[2], renderer.textScale, out Vector2 yBounds);

                float imageProportions = width / spriteInfo.width;

                float borderWidth = renderer.textScale * 2;

                float textBoundHeight = height - (spriteInfo.border.vertical * imageProportions) - borderWidth;
                float textBoundWidth  = width - (spriteInfo.border.horizontal * imageProportions) - borderWidth;

                var textAreaSize = new Vector4((spriteInfo.border.left * imageProportions) + (borderWidth / 2), (-spriteInfo.border.top + spriteInfo.border.bottom) * imageProportions / 2, textBoundWidth, textBoundHeight);

                float textScale = renderer.textScale;
                float multipler = Mathf.Min(Mathf.Min(3.5f, textAreaSize.z / textDimensions.x), Mathf.Min(3.5f, textAreaSize.w / textDimensions.y));
                if (multipler > 1)
                {
                    textScale     *= 1 + ((multipler - 1) / 2.1f);
                    multipler      = 1;
                    textDimensions = MeasureTextWidth(renderer, args[2], textScale, out yBounds);
                }
                float midLineOffset = (((UIDynamicFont)renderer.font).baseline / 2 * renderer.textScale);

                Color contrastColor = KlyteMonoUtils.ContrastColor(bgColor);

                RenderSprite(renderer.spriteBuffer, new RenderOptions
                {
                    atlas         = renderer.spriteAtlas,
                    color         = contrastColor,
                    fillAmount    = 1f,
                    flip          = UISpriteFlip.None,
                    offset        = position - new Vector3(0, -(height / 2) + midLineOffset),
                    pixelsToUnits = renderer.pixelRatio,
                    size          = size,
                    spriteInfo    = spriteInfo
                });

                RenderSprite(renderer.spriteBuffer, new RenderOptions
                {
                    atlas         = renderer.spriteAtlas,
                    color         = color2,
                    fillAmount    = 1f,
                    flip          = UISpriteFlip.None,
                    offset        = position - new Vector3(0, -(height / 2) + midLineOffset) + (new Vector3(borderWidth, -borderWidth) / 2),
                    pixelsToUnits = renderer.pixelRatio,
                    size          = size - new Vector3(borderWidth, borderWidth),
                    spriteInfo    = spriteInfo
                });
                midLineOffset = ((UIDynamicFont)renderer.font).baseline * textScale;
                Vector3 targetTextPos = midLine + VectorUtils.XY_(textAreaSize) + (new Vector3(textAreaSize.z - (textDimensions.x * multipler), -textDimensions.y) / 2);
                RenderText(renderer, args[2], targetTextPos, multipler, destination, textScale, contrastColor, bgColor);
            }
        }
        public IEnumerator LoadCustomContent()
        {
            LoadingManager.instance.m_loadingProfilerMain.BeginLoading("LoadCustomContent");
            LoadingManager.instance.m_loadingProfilerCustomContent.Reset();
            LoadingManager.instance.m_loadingProfilerCustomAsset.Reset();
            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("District Styles");
            LoadingManager.instance.m_loadingProfilerCustomAsset.PauseLoading();
            hasStarted = true;

            int                              i, j;
            DistrictStyle                    districtStyle;
            DistrictStyleMetaData            districtStyleMetaData;
            List <DistrictStyle>             districtStyles         = new List <DistrictStyle>();
            HashSet <string>                 styleBuildings         = new HashSet <string>();
            FastList <DistrictStyleMetaData> districtStyleMetaDatas = new FastList <DistrictStyleMetaData>();
            FastList <Package>               districtStylePackages  = new FastList <Package>();

            Package.Asset europeanStyles = PackageManager.FindAssetByName("System." + DistrictStyle.kEuropeanStyleName);

            if (europeanStyles != null && europeanStyles.isEnabled)
            {
                districtStyle = new DistrictStyle(DistrictStyle.kEuropeanStyleName, true);
                Util.InvokeVoid(LoadingManager.instance, "AddChildrenToBuiltinStyle", GameObject.Find("European Style new"), districtStyle, false);
                Util.InvokeVoid(LoadingManager.instance, "AddChildrenToBuiltinStyle", GameObject.Find("European Style others"), districtStyle, true);
                districtStyles.Add(districtStyle);
            }

            foreach (Package.Asset asset in PackageManager.FilterAssets(UserAssetType.DistrictStyleMetaData))
            {
                try
                {
                    if (asset != null && asset.isEnabled)
                    {
                        districtStyleMetaData = asset.Instantiate <DistrictStyleMetaData>();

                        if (districtStyleMetaData != null && !districtStyleMetaData.builtin)
                        {
                            districtStyleMetaDatas.Add(districtStyleMetaData);
                            districtStylePackages.Add(asset.package);

                            if (districtStyleMetaData.assets != null)
                            {
                                for (i = 0; i < districtStyleMetaData.assets.Length; i++)
                                {
                                    styleBuildings.Add(districtStyleMetaData.assets[i]);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    CODebugBase <LogChannel> .Warn(LogChannel.Modding, string.Concat(new object[] { ex.GetType(), ": Loading custom district style failed[", asset, "]\n", ex.Message }));
                }
            }

            LoadingManager.instance.m_loadingProfilerCustomAsset.ContinueLoading();
            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();

            if (loadUsed)
            {
                //while (!Profiling.SimulationPaused())
                //    yield return null;

                refs = new UsedAssets();
                refs.Setup();
            }

            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("Loading Assets First Pass");
            notMask    = ~SteamHelper.GetOwnedDLCMask();
            lastMillis = Profiling.Millis;

            // Load custom assets: props, trees, trailers
            foreach (Package.Asset asset in PackageManager.FilterAssets(UserAssetType.CustomAssetMetaData))
            {
                if (asset != null && PropTreeTrailer(asset) && Profiling.Millis - lastMillis > yieldInterval)
                {
                    lastMillis = Profiling.Millis;
                    yield return(null);
                }
            }

            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();
            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("Loading Assets Second Pass");

            // Load custom assets: buildings and vehicles
            foreach (Package.Asset asset in PackageManager.FilterAssets(UserAssetType.CustomAssetMetaData))
            {
                if (asset != null && BuildingVehicle(asset, styleBuildings.Contains(asset.fullName)) && Profiling.Millis - lastMillis > yieldInterval)
                {
                    lastMillis = Profiling.Millis;
                    yield return(null);
                }
            }

            if (loadUsed)
            {
                refs.ReportMissingAssets();
            }

            if (reportAssets)
            {
                AssetReport.instance.Save();
            }

            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();
            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("Finalizing District Styles");
            LoadingManager.instance.m_loadingProfilerCustomAsset.PauseLoading();

            for (i = 0; i < districtStyleMetaDatas.m_size; i++)
            {
                try
                {
                    districtStyleMetaData = districtStyleMetaDatas.m_buffer[i];
                    districtStyle         = new DistrictStyle(districtStyleMetaData.name, false);

                    if (districtStylePackages.m_buffer[i].GetPublishedFileID() != PublishedFileId.invalid)
                    {
                        districtStyle.PackageName = districtStylePackages.m_buffer[i].packageName;
                    }

                    if (districtStyleMetaData.assets != null)
                    {
                        for (j = 0; j < districtStyleMetaData.assets.Length; j++)
                        {
                            BuildingInfo bi = PrefabCollection <BuildingInfo> .FindLoaded(districtStyleMetaData.assets[j] + "_Data");

                            if (bi != null)
                            {
                                districtStyle.Add(bi);

                                if (districtStyleMetaData.builtin) // this is always false
                                {
                                    bi.m_dontSpawnNormally = !districtStyleMetaData.assetRef.isEnabled;
                                }
                            }
                            else
                            {
                                CODebugBase <LogChannel> .Warn(LogChannel.Modding, "Warning: Missing asset (" + districtStyleMetaData.assets[i] + ") in style " + districtStyleMetaData.name);
                            }
                        }

                        districtStyles.Add(districtStyle);
                    }
                }
                catch (Exception ex)
                {
                    CODebugBase <LogChannel> .Warn(LogChannel.Modding, ex.GetType() + ": Loading district style failed\n" + ex.Message);
                }
            }

            Singleton <DistrictManager> .instance.m_Styles = districtStyles.ToArray();

            if (Singleton <BuildingManager> .exists)
            {
                Singleton <BuildingManager> .instance.InitializeStyleArray(districtStyles.Count);
            }

            LoadingManager.instance.m_loadingProfilerCustomAsset.ContinueLoading();
            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();

            if (Singleton <TelemetryManager> .exists)
            {
                Singleton <TelemetryManager> .instance.CustomContentInfo(buildingsCount, propsCount, treeCount, vehicleCount);
            }

            LoadingManager.instance.m_loadingProfilerMain.EndLoading();
            hasFinished = true;
        }
Exemple #21
0
        public static Texture2D RenderSpriteLine(UIDynamicFont font, UITextureAtlas atlas, string spriteName, Color bgColor, string text, float textScale = 1)
        {
            UITextureAtlas.SpriteInfo spriteInfo = atlas[spriteName];
            if (spriteInfo == null)
            {
                CODebugBase <InternalLogChannel> .Warn(InternalLogChannel.UI, "Missing sprite " + spriteName + " in " + atlas.name);

                return(null);
            }
            else
            {
                textScale *= 2;

                Texture2D texture        = atlas.texture;
                float     calcHeight     = font.size * textScale * 2;
                float     calcProportion = spriteInfo.region.width * texture.width / (spriteInfo.region.height * texture.height);
                float     calcWidth      = Mathf.CeilToInt(calcHeight * calcProportion);

                int height = Mathf.CeilToInt(calcHeight);
                int width  = Mathf.CeilToInt(calcWidth);

                float textureScale = height / (spriteInfo.region.height * texture.height);

                LogUtils.DoLog($"height = {height} - width = {width} -  renderer.pixelRatio = 1 - textureScale = {height} / {(spriteInfo.region.height * texture.height)}");

                var   size        = new Vector3(width, height);
                float borderWidth = textScale * 3;

                Vector2 textDimensions = MeasureTextWidth(font, text, textScale, out Vector2 yBounds);
                float   borderBottom   = Mathf.Max(0, (spriteInfo.border.bottom * textScale * 2) + Mathf.Min(0, yBounds.x));
                var     textAreaSize   = new Vector4((spriteInfo.border.left * textScale * 2) + borderWidth, borderBottom + borderWidth, width - (spriteInfo.border.horizontal * textScale * 2) - borderWidth, height - (spriteInfo.border.top * textScale * 2) - borderBottom - borderWidth);

                float multipler = Mathf.Min(Mathf.Min(3.5f, textAreaSize.z / textDimensions.x), Mathf.Min(3.5f, textAreaSize.w / textDimensions.y));
                if (multipler > 1)
                {
                    textScale     *= 1 + ((multipler - 1) / 2.1f);
                    multipler      = 1;
                    textDimensions = MeasureTextWidth(font, text, textScale, out yBounds);
                }

                var imageSize = new Vector2(Mathf.NextPowerOfTwo((int)Mathf.Max(textDimensions.x * multipler, width)), Mathf.NextPowerOfTwo((int)Mathf.Max(textDimensions.y, height)));


                var tex = new Texture2D((int)imageSize.x, (int)imageSize.y, TextureFormat.ARGB32, false);
                tex.SetPixels(new Color[(int)(imageSize.x * imageSize.y)]);


                var texText = new Texture2D((int)textDimensions.x, (int)textDimensions.y, TextureFormat.ARGB32, false);
                texText.SetPixels(new Color[(int)(textDimensions.x * textDimensions.y)]);

                Color contrastColor = KlyteMonoUtils.ContrastColor(bgColor);

                Vector2 position = RenderSprite(atlas, spriteName, contrastColor, tex, textureScale);
                RenderSprite(atlas, spriteName, bgColor, tex, null, tex.height - (int)(borderWidth * 2), null, new Vector2((textScale / 2) - 0.5f, (textScale / 2) - 0.5f), (a, b) =>
                {
                    if (b.a == 1)
                    {
                        return(b);
                    }

                    if (b.a == 0)
                    {
                        return(a);
                    }

                    float totalAlpha = a.a + b.a;
                    return((a * (1 - b.a)) + (b * b.a));
                });
                Vector2 posText = position + VectorUtils.XY(textAreaSize) + new Vector2((textAreaSize.z / 2) - (textDimensions.x * multipler / 2) + 1, (textAreaSize.w / 2) - (textDimensions.y / 2) - (yBounds.x / 2));

                RenderText(font, text, new Vector3(0, -yBounds.x), textScale, contrastColor, bgColor, texText);

                if (multipler < 1)
                {
                    TextureScaler.scale(texText, (int)(texText.width * multipler), texText.height);
                }
                MergeTextures(tex, texText.GetPixels(), (int)posText.x, (int)posText.y, texText.width, texText.height, false);
                UnityEngine.Object.Destroy(texText);
                tex.Apply();

                return(tex);
            }
        }
Exemple #22
0
        internal void LoadImpl(Package.Asset assetRef)
        {
            try
            {
                stack.Push(assetRef);
                LoadingManager.instance.m_loadingProfilerCustomAsset.BeginLoading(ShortName(assetRef.name));
                CustomAssetMetaData.Type type = GetMetaType(assetRef);

                GameObject go          = AssetDeserializer.Instantiate(assetRef) as GameObject;
                string     packageName = assetRef.package.packageName;
                string     fullName    = type < CustomAssetMetaData.Type.RoadElevation ? packageName + "." + go.name : PillarOrElevationName(packageName, go.name);
                go.name = fullName;
                go.SetActive(false);
                PrefabInfo info = go.GetComponent <PrefabInfo>();
                info.m_isCustomContent = true;

                if (info.m_Atlas != null && !string.IsNullOrEmpty(info.m_InfoTooltipThumbnail) && info.m_Atlas[info.m_InfoTooltipThumbnail] != null)
                {
                    info.m_InfoTooltipAtlas = info.m_Atlas;
                }

                PropInfo     pi;
                TreeInfo     ti;
                BuildingInfo bi;
                VehicleInfo  vi;
                CitizenInfo  ci;
                NetInfo      ni;

                if ((pi = go.GetComponent <PropInfo>()) != null)
                {
                    if (pi.m_lodObject != null)
                    {
                        pi.m_lodObject.SetActive(false);
                    }

                    Initialize(pi);
                }
                else if ((ti = go.GetComponent <TreeInfo>()) != null)
                {
                    Initialize(ti);
                }
                else if ((bi = go.GetComponent <BuildingInfo>()) != null)
                {
                    if (bi.m_lodObject != null)
                    {
                        bi.m_lodObject.SetActive(false);
                    }

                    bi.m_dontSpawnNormally = dontSpawnNormally.Remove(fullName);
                    Initialize(bi);

                    if (bi.GetAI() is IntersectionAI)
                    {
                        loadedIntersections.Add(fullName);
                    }
                }
                else if ((vi = go.GetComponent <VehicleInfo>()) != null)
                {
                    if (vi.m_lodObject != null)
                    {
                        vi.m_lodObject.SetActive(false);
                    }

                    Initialize(vi);
                }
                else if ((ci = go.GetComponent <CitizenInfo>()) != null)
                {
                    if (ci.m_lodObject != null)
                    {
                        ci.m_lodObject.SetActive(false);
                    }

                    if (ci.InitializeCustomPrefab(citizenMetaDatas[assetRef.fullName]))
                    {
                        citizenMetaDatas.Remove(assetRef.fullName);
                        ci.gameObject.SetActive(true);
                        Initialize(ci);
                    }
                    else
                    {
                        info = null;
                        CODebugBase <LogChannel> .Warn(LogChannel.Modding, "Custom citizen [" + assetRef.fullName + "] template not available in selected theme. Asset not added in game.");
                    }
                }
                else if ((ni = go.GetComponent <NetInfo>()) != null)
                {
                    Initialize(ni);
                }
                else
                {
                    info = null;
                }

                if (info != null)
                {
                    string path = Path.GetDirectoryName(assetRef.package.packagePath);

                    if (!string.IsNullOrEmpty(path) && plugins.TryGetValue(path, out PluginInfo plugin))
                    {
                        IAssetDataExtension[] extensions = plugin.GetInstances <IAssetDataExtension>();

                        if (extensions.Length > 0)
                        {
                            UserAssetData uad = GetUserAssetData(assetRef, out string name);

                            if (uad != null)
                            {
                                for (int i = 0; i < extensions.Length; i++)
                                {
                                    try
                                    {
                                        extensions[i].OnAssetLoaded(name, info, uad.Data);
                                    }
                                    catch (Exception e)
                                    {
                                        ModException ex = new ModException("The Mod " + plugin.ToString() + " has caused an error when loading " + fullName, e);
                                        UIView.ForwardException(ex);
                                        Debug.LogException(ex);
                                    }
                                }
                            }
                            else
                            {
                                Util.DebugPrint("UserAssetData is null for", fullName);
                            }
                        }
                    }
                }
            }
            finally
            {
                stack.Pop();
                assetCount++;
                LoadingManager.instance.m_loadingProfilerCustomAsset.EndLoading();
            }
        }
Exemple #23
0
        internal void LoadImpl(Package.Asset assetRef)
        {
            try
            {
                stack.Push(assetRef);
                LoadingManager.instance.m_loadingProfilerCustomAsset.BeginLoading(AssetName(assetRef.name));
                GameObject go = AssetDeserializer.Instantiate(assetRef) as GameObject;
                CustomAssetMetaData.Type type = GetMetaType(assetRef);
                string packageName            = assetRef.package.packageName;
                string fullName = type < CustomAssetMetaData.Type.RoadElevation ? packageName + "." + go.name : PillarOrElevationName(packageName, go.name);
                go.name = fullName;
                go.SetActive(false);
                PrefabInfo info = go.GetComponent <PrefabInfo>();
                info.m_isCustomContent = true;

                if (info.m_Atlas != null && !string.IsNullOrEmpty(info.m_InfoTooltipThumbnail) && info.m_Atlas[info.m_InfoTooltipThumbnail] != null)
                {
                    info.m_InfoTooltipAtlas = info.m_Atlas;
                }

                PropInfo pi = go.GetComponent <PropInfo>();

                if (pi != null)
                {
                    if (pi.m_lodObject != null)
                    {
                        pi.m_lodObject.SetActive(false);
                    }

                    Initialize(pi);
                    loadedProps.Add(fullName);
                }

                TreeInfo ti = go.GetComponent <TreeInfo>();

                if (ti != null)
                {
                    Initialize(ti);
                    loadedTrees.Add(fullName);
                }

                BuildingInfo bi = go.GetComponent <BuildingInfo>();

                if (bi != null)
                {
                    if (bi.m_lodObject != null)
                    {
                        bi.m_lodObject.SetActive(false);
                    }

                    bi.m_dontSpawnNormally = dontSpawnNormally.Remove(fullName);
                    Initialize(bi);
                    loadedBuildings.Add(fullName);

                    if (bi.GetAI() is IntersectionAI)
                    {
                        loadedIntersections.Add(fullName);
                    }
                }

                VehicleInfo vi = go.GetComponent <VehicleInfo>();

                if (vi != null)
                {
                    if (vi.m_lodObject != null)
                    {
                        vi.m_lodObject.SetActive(false);
                    }

                    Initialize(vi);
                    loadedVehicles.Add(fullName);
                }

                CitizenInfo ci = go.GetComponent <CitizenInfo>();

                if (ci != null)
                {
                    if (ci.m_lodObject != null)
                    {
                        ci.m_lodObject.SetActive(false);
                    }

                    if (ci.InitializeCustomPrefab(citizenMetaDatas[assetRef.fullName]))
                    {
                        citizenMetaDatas.Remove(assetRef.fullName);
                        ci.gameObject.SetActive(true);
                        Initialize(ci);
                        loadedCitizens.Add(fullName);
                    }
                    else
                    {
                        CODebugBase <LogChannel> .Warn(LogChannel.Modding, "Custom citizen [" + assetRef.fullName + "] template not available in selected theme. Asset not added in game.");
                    }
                }

                NetInfo ni = go.GetComponent <NetInfo>();

                if (ni != null)
                {
                    loadedNets.Add(fullName);
                    Initialize(ni);
                }
            }
            finally
            {
                stack.Pop();
                assetCount++;
                LoadingManager.instance.m_loadingProfilerCustomAsset.EndLoading();
            }
        }
Exemple #24
0
        private static void Awake()
        {
            if (Mod.DEBUG_LOG_ON)
            {
                Helper.dbgLog("I never ever fire. " + DateTime.Now.ToString());
            }
            UIView.eventExceptionForwarded += new UIView.ForwardExceptionHandler(OnExceptionForwarded);
            try
            {
                string sc = "colossal";
                string ft = "firstTime";
                sc = (string)typeof(Settings).GetField("colossal", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).GetValue(sc);
                ft = (string)typeof(Settings).GetField("firstTime", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static).GetValue(ft);
                GameSettings.AddSettingsFile(new SettingsFile[]
                {
                    new SettingsFile
                    {
                        systemFileName = sc
                    }
                });
                SavedBool savedBool = new SavedBool(ft, sc, true);
                CODebugBase <LogChannel> .Log(LogChannel.Core, "Telemetry enabled");

                TelemetryKH telemetry = new TelemetryKH();
                if (savedBool)
                {
                    telemetry.AddEvent(Telemetry.Event.FirstLaunch, new Telemetry.Pair[0]);
                    savedBool.value = false;
                }

                if (Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) == false |
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableOnAppStart) == false)
                {
                    telemetry.AddEvent(Telemetry.Event.StartGame, new Telemetry.Pair[0]);
                }


                if (Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableAll) == false |
                    Helper.HasTelemFlag(Mod.config.TelemetryLevel, Helper.TelemOption.DisableMachineInfo) == false)
                {
                    telemetry.AddEvent(Telemetry.Event.Meta, new Telemetry.Pair[]
                    {
                        new Telemetry.Pair("machineid", SystemInfo.deviceUniqueIdentifier),
                        new Telemetry.Pair("machinemodel", SystemInfo.deviceModel),
                        new Telemetry.Pair("gfxdevice", SystemInfo.graphicsDeviceName),
                        new Telemetry.Pair("gfxversion", SystemInfo.graphicsDeviceVersion),
                        new Telemetry.Pair("gfxmemory", SystemInfo.graphicsMemorySize),
                        new Telemetry.Pair("gfxshadermodel", SystemInfo.graphicsShaderLevel),
                        new Telemetry.Pair("os", SystemInfo.operatingSystem),
                        new Telemetry.Pair("oslanguage", Application.systemLanguage),
                        new Telemetry.Pair("cpu", SystemInfo.processorType),
                        new Telemetry.Pair("cpucount", SystemInfo.processorCount),
                        new Telemetry.Pair("sysmemory", SystemInfo.systemMemorySize)
                    });
                }
                if (Mod.DEBUG_LOG_ON)
                {
                    Helper.dbgLog("TMKH Awake doing startup push");
                }
                telemetry.Push();
            }
            catch (GameSettingsException ex)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex.GetType() + ": Game Settings error " + ex.Message);
            }
            catch (Exception ex2)
            {
                CODebugBase <LogChannel> .Warn(LogChannel.HTTP, ex2.GetType() + ": Telemetry event failed " + ex2.Message);
            }
        }
Exemple #25
0
        public IEnumerator LoadCustomContent()
        {
            LoadingManager.instance.m_loadingProfilerMain.BeginLoading("LoadCustomContent");
            LoadingManager.instance.m_loadingProfilerCustomContent.Reset();
            LoadingManager.instance.m_loadingProfilerCustomAsset.Reset();
            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("District Styles");
            LoadingManager.instance.m_loadingProfilerCustomAsset.PauseLoading();
            hasStarted = true;

            int                              i, j;
            DistrictStyle                    districtStyle;
            DistrictStyleMetaData            districtStyleMetaData;
            List <DistrictStyle>             districtStyles         = new List <DistrictStyle>();
            HashSet <string>                 styleBuildings         = new HashSet <string>();
            FastList <DistrictStyleMetaData> districtStyleMetaDatas = new FastList <DistrictStyleMetaData>();
            FastList <Package>               districtStylePackages  = new FastList <Package>();

            Package.Asset europeanStyles = PackageManager.FindAssetByName("System." + DistrictStyle.kEuropeanStyleName);

            if (europeanStyles != null && europeanStyles.isEnabled)
            {
                districtStyle = new DistrictStyle(DistrictStyle.kEuropeanStyleName, true);
                Util.InvokeVoid(LoadingManager.instance, "AddChildrenToBuiltinStyle", GameObject.Find("European Style new"), districtStyle, false);
                Util.InvokeVoid(LoadingManager.instance, "AddChildrenToBuiltinStyle", GameObject.Find("European Style others"), districtStyle, true);
                districtStyles.Add(districtStyle);
            }

            if ((bool)typeof(LoadingManager).GetMethod("DLC", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(LoadingManager.instance, new object[] { 715190u }))
            {
                Package.Asset asset = PackageManager.FindAssetByName("System." + DistrictStyle.kEuropeanSuburbiaStyleName);

                if (asset != null && asset.isEnabled)
                {
                    districtStyle = new DistrictStyle(DistrictStyle.kEuropeanSuburbiaStyleName, true);
                    Util.InvokeVoid(LoadingManager.instance, "AddChildrenToBuiltinStyle", GameObject.Find("Modder Pack 3"), districtStyle, false);
                    districtStyles.Add(districtStyle);
                }
            }

            foreach (Package.Asset asset in PackageManager.FilterAssets(UserAssetType.DistrictStyleMetaData))
            {
                try
                {
                    if (asset != null && asset.isEnabled)
                    {
                        districtStyleMetaData = asset.Instantiate <DistrictStyleMetaData>();

                        if (districtStyleMetaData != null && !districtStyleMetaData.builtin)
                        {
                            districtStyleMetaDatas.Add(districtStyleMetaData);
                            districtStylePackages.Add(asset.package);

                            if (districtStyleMetaData.assets != null)
                            {
                                for (i = 0; i < districtStyleMetaData.assets.Length; i++)
                                {
                                    styleBuildings.Add(districtStyleMetaData.assets[i]);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    CODebugBase <LogChannel> .Warn(LogChannel.Modding, string.Concat(new object[] { ex.GetType(), ": Loading custom district style failed[", asset, "]\n", ex.Message }));
                }
            }

            LoadingManager.instance.m_loadingProfilerCustomAsset.ContinueLoading();
            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();

            if (Settings.settings.loadUsed)
            {
                UsedAssets.Create();
            }

            lastMillis = Profiling.Millis;
            LoadingScreen.instance.DualSource.Add("Custom Assets");
            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("Calculating asset load order");
            Package.Asset[] queue = GetLoadQueue(styleBuildings);
            Util.DebugPrint("LoadQueue", queue.Length, Profiling.Millis);
            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();

            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("Loading Custom Assets");
            Sharing.instance.Start(queue);
            beginMillis = Profiling.Millis;

            for (i = 0; i < queue.Length; i++)
            {
                Package.Asset assetRef = queue[i];

                if ((i & 63) == 0)
                {
                    PrintMem(i);
                }

                Sharing.instance.WaitForWorkers();

                try
                {
                    stack.Clear();
                    LoadImpl(assetRef);
                }
                catch (Exception e)
                {
                    AssetFailed(assetRef.fullName, e);
                }

                Sharing.instance.ManageLoadQueue(i);

                if (Profiling.Millis - lastMillis > yieldInterval)
                {
                    lastMillis = Profiling.Millis;
                    progress   = 0.15f + (i + 1) * 0.7f / queue.Length;
                    LoadingScreen.instance.SetProgress(progress, progress, assetCount, assetCount - i - 1 + queue.Length, beginMillis, lastMillis);
                    yield return(null);
                }
            }

            lastMillis = Profiling.Millis;
            LoadingScreen.instance.SetProgress(0.85f, 1f, assetCount, assetCount, beginMillis, lastMillis);
            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();
            Util.DebugPrint("Custom assets loaded in", lastMillis - beginMillis);
            PrintMem();
            queue = null;
            stack.Clear();
            Report();

            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("Finalizing District Styles");
            LoadingManager.instance.m_loadingProfilerCustomAsset.PauseLoading();

            for (i = 0; i < districtStyleMetaDatas.m_size; i++)
            {
                try
                {
                    districtStyleMetaData = districtStyleMetaDatas.m_buffer[i];
                    districtStyle         = new DistrictStyle(districtStyleMetaData.name, false);

                    if (districtStylePackages.m_buffer[i].GetPublishedFileID() != PublishedFileId.invalid)
                    {
                        districtStyle.PackageName = districtStylePackages.m_buffer[i].packageName;
                    }

                    if (districtStyleMetaData.assets != null)
                    {
                        for (j = 0; j < districtStyleMetaData.assets.Length; j++)
                        {
                            BuildingInfo bi = CustomDeserializer.FindLoaded <BuildingInfo>(districtStyleMetaData.assets[j] + "_Data");

                            if (bi != null)
                            {
                                districtStyle.Add(bi);

                                if (districtStyleMetaData.builtin) // this is always false
                                {
                                    bi.m_dontSpawnNormally = !districtStyleMetaData.assetRef.isEnabled;
                                }
                            }
                            else
                            {
                                CODebugBase <LogChannel> .Warn(LogChannel.Modding, "Warning: Missing asset (" + districtStyleMetaData.assets[j] + ") in style " + districtStyleMetaData.name);
                            }
                        }

                        districtStyles.Add(districtStyle);
                    }
                }
                catch (Exception ex)
                {
                    CODebugBase <LogChannel> .Warn(LogChannel.Modding, ex.GetType() + ": Loading district style failed\n" + ex.Message);
                }
            }

            Singleton <DistrictManager> .instance.m_Styles = districtStyles.ToArray();

            if (Singleton <BuildingManager> .exists)
            {
                Singleton <BuildingManager> .instance.InitializeStyleArray(districtStyles.Count);
            }

            LoadingManager.instance.m_loadingProfilerCustomAsset.ContinueLoading();
            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();
            LoadingManager.instance.m_loadingProfilerMain.EndLoading();
            hasFinished = true;
        }
Exemple #26
0
        public IEnumerator LoadCustomContent()
        {
            LoadingManager.instance.m_loadingProfilerMain.BeginLoading("LoadCustomContent");
            LoadingManager.instance.m_loadingProfilerCustomContent.Reset();
            LoadingManager.instance.m_loadingProfilerCustomAsset.Reset();
            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("District Styles");
            LoadingManager.instance.m_loadingProfilerCustomAsset.PauseLoading();
            hasStarted = true;

            int                              i, j;
            DistrictStyle                    districtStyle;
            DistrictStyleMetaData            districtStyleMetaData;
            List <DistrictStyle>             districtStyles         = new List <DistrictStyle>();
            HashSet <string>                 styleBuildings         = new HashSet <string>();
            FastList <DistrictStyleMetaData> districtStyleMetaDatas = new FastList <DistrictStyleMetaData>();
            FastList <Package>               districtStylePackages  = new FastList <Package>();

            Package.Asset europeanStyles = PackageManager.FindAssetByName("System." + DistrictStyle.kEuropeanStyleName);

            if (europeanStyles != null && europeanStyles.isEnabled)
            {
                districtStyle = new DistrictStyle(DistrictStyle.kEuropeanStyleName, true);
                Util.InvokeVoid(LoadingManager.instance, "AddChildrenToBuiltinStyle", GameObject.Find("European Style new"), districtStyle, false);
                Util.InvokeVoid(LoadingManager.instance, "AddChildrenToBuiltinStyle", GameObject.Find("European Style others"), districtStyle, true);

                // If skipping of standard prefabs is enabled, we must ensure that there are no skipped prefabs in the default district syle.
                if (Settings.settings.SkipAny)
                {
                    RemoveSkipped(districtStyle);
                }

                districtStyles.Add(districtStyle);
            }

            foreach (Package.Asset asset in PackageManager.FilterAssets(UserAssetType.DistrictStyleMetaData))
            {
                try
                {
                    if (asset != null && asset.isEnabled)
                    {
                        districtStyleMetaData = asset.Instantiate <DistrictStyleMetaData>();

                        if (districtStyleMetaData != null && !districtStyleMetaData.builtin)
                        {
                            districtStyleMetaDatas.Add(districtStyleMetaData);
                            districtStylePackages.Add(asset.package);

                            if (districtStyleMetaData.assets != null)
                            {
                                for (i = 0; i < districtStyleMetaData.assets.Length; i++)
                                {
                                    styleBuildings.Add(districtStyleMetaData.assets[i]);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    CODebugBase <LogChannel> .Warn(LogChannel.Modding, string.Concat(new object[] { ex.GetType(), ": Loading custom district style failed[", asset, "]\n", ex.Message }));
                }
            }

            LoadingManager.instance.m_loadingProfilerCustomAsset.ContinueLoading();
            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();

            if (loadUsed)
            {
                UsedAssets.Create().Hook();
            }

            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("Calculating asset load order");
            List <Package.Asset>[] queues = GetLoadQueues(styleBuildings);
            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();
            lastMillis = Profiling.Millis;
            Sharing.instance?.Start();

            // Load custom assets.
            for (i = 0; i < queues.Length; i++)
            {
                LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("Loading Custom Assets Pass " + i);

                foreach (Package.Asset asset in queues[i])
                {
                    Load(asset);

                    if (Profiling.Millis - lastMillis > yieldInterval)
                    {
                        lastMillis = Profiling.Millis;
                        yield return(null);
                    }
                }

                LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();
            }

            stack.Clear();
            Report();

            LoadingManager.instance.m_loadingProfilerCustomContent.BeginLoading("Finalizing District Styles");
            LoadingManager.instance.m_loadingProfilerCustomAsset.PauseLoading();

            for (i = 0; i < districtStyleMetaDatas.m_size; i++)
            {
                try
                {
                    districtStyleMetaData = districtStyleMetaDatas.m_buffer[i];
                    districtStyle         = new DistrictStyle(districtStyleMetaData.name, false);

                    if (districtStylePackages.m_buffer[i].GetPublishedFileID() != PublishedFileId.invalid)
                    {
                        districtStyle.PackageName = districtStylePackages.m_buffer[i].packageName;
                    }

                    if (districtStyleMetaData.assets != null)
                    {
                        for (j = 0; j < districtStyleMetaData.assets.Length; j++)
                        {
                            BuildingInfo bi = PrefabCollection <BuildingInfo> .FindLoaded(districtStyleMetaData.assets[j] + "_Data");

                            if (bi != null)
                            {
                                districtStyle.Add(bi);

                                if (districtStyleMetaData.builtin) // this is always false
                                {
                                    bi.m_dontSpawnNormally = !districtStyleMetaData.assetRef.isEnabled;
                                }
                            }
                            else
                            {
                                CODebugBase <LogChannel> .Warn(LogChannel.Modding, "Warning: Missing asset (" + districtStyleMetaData.assets[i] + ") in style " + districtStyleMetaData.name);
                            }
                        }

                        districtStyles.Add(districtStyle);
                    }
                }
                catch (Exception ex)
                {
                    CODebugBase <LogChannel> .Warn(LogChannel.Modding, ex.GetType() + ": Loading district style failed\n" + ex.Message);
                }
            }

            Singleton <DistrictManager> .instance.m_Styles = districtStyles.ToArray();

            if (Singleton <BuildingManager> .exists)
            {
                Singleton <BuildingManager> .instance.InitializeStyleArray(districtStyles.Count);
            }

            LoadingManager.instance.m_loadingProfilerCustomAsset.ContinueLoading();
            LoadingManager.instance.m_loadingProfilerCustomContent.EndLoading();

            if (Singleton <TelemetryManager> .exists)
            {
                Singleton <TelemetryManager> .instance.CustomContentInfo(buildingCount, propCount, treeCount, vehicleCount);
            }

            LoadingManager.instance.m_loadingProfilerMain.EndLoading();
            hasFinished = true;
        }