Пример #1
0
        public void CommonPaletteTest()
        {
            var pal = Test(assets => assets.LoadPalette(Palette.Common));

            Assert.Equal(AssetId.From(Palette.Common), AssetId.FromUInt32(pal.Id));
            Assert.False(pal.IsAnimated);
            Assert.Equal(1, pal.Period);
            Assert.Equal("Palette.Common", pal.Name);
            var at0 = pal.GetPaletteAtTime(0);

            for (int i = 0; i < 192; i++)
            {
                Assert.Equal(0u, at0[i]);
            }
        }
Пример #2
0
    private void CreateLateResources(IList <UnityEngine.Object> objects)
    {
        const string lateResourcesDirectory = "Assets/Resources/Late";

        BuildUtils.PrepareCleanDirectory(lateResourcesDirectory);

        foreach (var obj in ScanningUtils.ItemsProcessor(objects,
                                                         "Creating late resources",
                                                         p => AssetDatabase.GetAssetPath(p)))
        {
            var lateResource = ScriptableObject.CreateInstance <LateResource>();
            lateResource.Target = obj;
            AssetDatabase.CreateAsset(lateResource, lateResourcesDirectory + "/" + AssetId.FromObject(obj) + ".asset");
        }
    }
Пример #3
0
    public AlbionPalette LoadPalette(PaletteId id)
    {
        var palette = (AlbionPalette)_modApplier.LoadAsset(id);

        if (palette == null)
        {
            return(null);
        }

        var commonPalette = (AlbionPalette)_modApplier.LoadAssetCached(AssetId.From(Base.Palette.Common));

        palette.SetCommonPalette(commonPalette);

        return(palette);
    }
Пример #4
0
        private AssetBalanceChange GetAsset(AssetId assetId, bool createIfNotExists)
        {
            AssetBalanceChange change = null;

            if (_ColoredAssets.TryGetValue(assetId, out change))
            {
                return(change);
            }
            if (createIfNotExists)
            {
                change = new AssetBalanceChange(assetId);
                _ColoredAssets.Add(assetId, change);
            }
            return(change);
        }
Пример #5
0
        public void ParseTextualTest()
        {
            var m = AssetMapping.Global.Clear();

            Assert.Equal(AssetId.None, m.Parse("", null));
            m.RegisterAssetType(typeof(ZeroBasedByte), AssetType.Portrait);

            Assert.Equal(AssetId.None, m.Parse("", null));
            Assert.Equal(AssetId.From(ZeroBasedByte.Zero), m.Parse("Zero", null));
            Assert.Equal(AssetId.From(ZeroBasedByte.One), m.Parse("One", null));
            Assert.Equal(AssetId.From(ZeroBasedByte.Zero), m.Parse("Portrait.Zero", null));
            Assert.Equal(AssetId.From(ZeroBasedByte.One), m.Parse("Portrait.One", null));
            Assert.Throws <FormatException>(() => m.Parse("Npc.Zero", null));
            Assert.Throws <FormatException>(() => m.Parse("Npc.One", null));
        }
Пример #6
0
        private static bool TryParseAsset(DateTime date, string[] args, out IFixing asset)
        {
            Currency currency   = null;
            bool     validAsset = args.Length == 2 && Currency.TryParse(args[1], out currency);

            if (!validAsset)
            {
                asset = null;
                return(false);
            }

            var assetId = new AssetId(args[0], currency);

            asset = new EquitySpot(date, assetId);
            return(true);
        }
        public void SetUp()
        {
            _temporaryDirectory = new TemporaryDirectory();

            _assetId   = AssetId.CreateUnique();
            _assetType = new AssetType("AssetType");
            _buffer    = new byte[1000];
            Utils.Random.NextBytes(_buffer);
            _binaryContent = new MemoryStream(_buffer);
            _jsonContent   = new JsonContent
            {
                IntProperty    = 123,
                DoubleProperty = 123.456,
                StringProperty = "String 123"
            };
        }
Пример #8
0
        private void UnTrackAsset(AssetId assetId)
        {
            lock (ThisLock)
            {
                TrackedAsset trackedAsset;
                if (!trackedAssets.TryGetValue(assetId, out trackedAsset))
                {
                    return;
                }

                trackedAsset.Dispose();

                // Remove from global list
                trackedAssets.Remove(assetId);
            }
        }
Пример #9
0
 internal void UnTrackAssetImportInput(AssetId assetId, string inputPath)
 {
     lock (ThisLock)
     {
         HashSet <AssetId> assetsTrackedByPath;
         if (mapSourceFilesToAssets.TryGetValue(inputPath, out assetsTrackedByPath))
         {
             assetsTrackedByPath.Remove(assetId);
             if (assetsTrackedByPath.Count == 0)
             {
                 mapSourceFilesToAssets.Remove(inputPath);
                 DirectoryWatcher?.UnTrack(inputPath);
             }
         }
     }
 }
Пример #10
0
        /// <inheritdoc />
        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = (int)Action;
                hashCode = (hashCode * 397) ^ AppId;
                hashCode = (hashCode * 397) ^ AssetId.GetHashCode();
                hashCode = (hashCode * 397) ^ CurrencyId.GetHashCode();
                hashCode = (hashCode * 397) ^ ContextId.GetHashCode();
                hashCode = (hashCode * 397) ^ SteamId.GetHashCode();
                hashCode = (hashCode * 397) ^ (Text != null ? Text.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ Timestamp.GetHashCode();

                return(hashCode);
            }
        }
Пример #11
0
        public void IdToEnumStringTest()
        {
            var m = AssetMapping.Global.Clear();

            m.RegisterAssetType(typeof(ZeroBasedByte), AssetType.Portrait);
            m.RegisterAssetType(typeof(OneBasedByte), AssetType.Npc);

            var zbb = "UAlbion.Config.Tests.AssetMappingTests+ZeroBasedByte, UAlbion.Config.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
            var obb = "UAlbion.Config.Tests.AssetMappingTests+OneBasedByte, UAlbion.Config.Tests, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";

            Assert.Equal((zbb, 0), m.IdToEnumString(AssetId.From(ZeroBasedByte.Zero)));
            Assert.Equal((zbb, 1), m.IdToEnumString(AssetId.From(ZeroBasedByte.One)));
            Assert.Equal((zbb, 2), m.IdToEnumString(AssetId.From(ZeroBasedByte.Two)));
            Assert.Equal((obb, 1), m.IdToEnumString(AssetId.From(OneBasedByte.One)));
            Assert.Equal((obb, 2), m.IdToEnumString(AssetId.From(OneBasedByte.Two)));
            Assert.Equal((obb, 3), m.IdToEnumString(AssetId.From(OneBasedByte.Three)));
        }
Пример #12
0
        public void CanSplitAssetMoney()
        {
            var gold = new AssetId(new Key());

            CanSplitAssetMoneyCore(gold, 1234, 3);
            CanSplitAssetMoneyCore(gold, 1234, 2);
            CanSplitAssetMoneyCore(gold, 1234, 10);
            CanSplitAssetMoneyCore(gold, 1, 3);
            Assert.Throws <ArgumentOutOfRangeException>(() => CanSplitAssetMoneyCore(gold, 1000, 0));
            CanSplitAssetMoneyCore(gold, 0, 10);

            AssetMoney[] result = new AssetMoney(gold, 20).Split(3).ToArray();
            Assert.True(result[0].Quantity == 7);
            Assert.True(result[1].Quantity == 7);
            Assert.True(result[2].Quantity == 6);
            Assert.True(result[0].Id == gold);
        }
Пример #13
0
        internal void TrackAssetImportInput(AssetId assetId, string inputPath)
        {
            lock (ThisLock)
            {
                HashSet <AssetId> assetsTrackedByPath;
                if (!mapSourceFilesToAssets.TryGetValue(inputPath, out assetsTrackedByPath))
                {
                    assetsTrackedByPath = new HashSet <AssetId>();
                    mapSourceFilesToAssets.Add(inputPath, assetsTrackedByPath);
                    DirectoryWatcher?.Track(inputPath);
                }
                assetsTrackedByPath.Add(assetId);
            }

            // We will always issue a compute of the hash in order to verify SourceHash haven't changed
            FileVersionManager.Instance.ComputeFileHashAsync(inputPath, SourceImportFileHashCallback, tokenSourceForImportHash.Token);
        }
Пример #14
0
    void Test <T>(AssetId id,
                  AssetId[] prerequisites,
                  Func <T, ISerializer, T> serdes,
                  Func <T, T> canonicalize = null) where T : class
    {
        prerequisites ??= Array.Empty <AssetId>();
        var allIds = prerequisites.Append(id);

        var resultsDir = Path.Combine(_baseDir, "re", "ConversionTests");

        var baseAsset = (T)_baseApplier.LoadAsset(id);

        if (canonicalize != null)
        {
            baseAsset = canonicalize(baseAsset);
        }

        var(baseBytes, baseNotes) = Asset.Save(baseAsset, serdes);
        var baseJson = Asset.SaveJson(baseAsset, JsonUtil);

        var idStrings  = allIds.Select(x => $"{x.Type}.{x.Id}").ToArray();
        var assetTypes = allIds.Select(x => x.Type).Distinct().ToHashSet();

        var mapping = AssetMapping.Global;

        using (var unpacker = new AssetConverter(
                   mapping,
                   _disk,
                   JsonUtil,
                   new[] { BaseAssetMod },
                   UnpackedAssetMod))
        {
            unpacker.Convert(idStrings, assetTypes, null);
        }

        var unpackedAsset = (T)BuildApplier(UnpackedAssetMod, AssetMapping.Global).LoadAsset(id);

        Assert.NotNull(unpackedAsset);
        var(unpackedBytes, unpackedNotes) = Asset.Save(unpackedAsset, serdes);
        var unpackedJson = Asset.SaveJson(unpackedAsset, JsonUtil);

        Asset.Compare(resultsDir,
                      id.ToString(),
                      baseBytes,
                      unpackedBytes,
                      new[]
Пример #15
0
    public static ActionEvent Serdes(ActionEvent e, AssetMapping mapping, ISerializer s)
    {
        if (s == null)
        {
            throw new ArgumentNullException(nameof(s));
        }
        var actionType = s.EnumU8(nameof(ActionType), e?.ActionType ?? 0);

        e ??= new ActionEvent();
        var assetType = actionType switch
        {
            ActionType.AskAboutItem
            or ActionType.UseItem
            or ActionType.EquipItem
            or ActionType.UnequipItem
            or ActionType.PickupItem => AssetType.Item,
            ActionType.Word => AssetType.Word,
            ActionType.DialogueLine => AssetType.Unknown,
            _ => AssetType.Unknown
        };

        e.ActionType = actionType;
        e.Unk2       = s.UInt8(nameof(Unk2), e.Unk2);
        e.Block      = s.UInt8(nameof(Block), e.Block);
        e.Unk4       = s.UInt8(nameof(Unk4), e.Unk4);
        e.Unk5       = s.UInt8(nameof(Unk5), e.Unk5);
        e.Argument   = AssetId.SerdesU16(nameof(Argument), e.Argument, assetType, mapping, s);
        e.Unk8       = s.UInt16(nameof(Unk8), e.Unk8);

        ApiUtil.Assert(e.Unk2 == 1 || ((int)e.ActionType == 14 && e.Unk2 == 2));
        ApiUtil.Assert(e.Unk4 == 0);
        ApiUtil.Assert(e.Unk5 == 0);
        ApiUtil.Assert(e.Unk8 == 0);
        return(e);
    }

    byte Unk4 {
        get; set;
    }
    byte Unk5 {
        get; set;
    }
    ushort Unk8 {
        get; set;
    }
Пример #16
0
        public static EventNode Serdes(ushort id, EventNode node, ISerializer s, AssetId chainSource, TextId textAssetId, AssetMapping mapping)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }
            var initialPosition = s.Offset;
            var mapEvent        = node?.Event as MapEvent;
            var @event          = MapEvent.Serdes(mapEvent, s, chainSource, textAssetId, mapping);

            if (@event is IBranchingEvent be)
            {
                node ??= new BranchNode(id, be);
                var    branch       = (BranchNode)node;
                ushort?falseEventId = s.Transform <ushort, ushort?>(
                    nameof(branch.NextIfFalse),
                    branch.NextIfFalse?.Id,
                    S.UInt16,
                    MaxToNullConverter.Instance);

                if (falseEventId != null && branch.NextIfFalse == null)
                {
                    branch.NextIfFalse = new DummyEventNode(falseEventId.Value);
                }
            }
            else
            {
                node ??= new EventNode(id, @event);
            }

            ushort?nextEventId = s.Transform <ushort, ushort?>(nameof(node.Next), node.Next?.Id, S.UInt16, MaxToNullConverter.Instance);

            if (nextEventId != null && node.Next == null)
            {
                node.Next = new DummyEventNode(nextEventId.Value);
            }

            long expectedPosition = initialPosition + 12;
            long actualPosition   = s.Offset;

            ApiUtil.Assert(expectedPosition == actualPosition,
                           $"Expected to have read {expectedPosition - initialPosition} bytes, but {actualPosition - initialPosition} have been read.");

            return(node);
        }
Пример #17
0
            public Entity CreateSprite(Scene scene, AssetId spriteAssetId, Vector2?translation = null, double rotation = 0, Vector2?scale = null)
            {
                var entity = new Entity();

                entity.AddComponent(new Transform2DComponent
                {
                    Translation = translation ?? Vector2.Zero,
                    Rotation    = rotation,
                    Scale       = scale ?? Vector2.One
                });
                entity.AddComponent(new SpriteRendererComponent
                {
                    Sprite = _assetStore.GetAsset <Sprite>(spriteAssetId)
                });
                scene.AddEntity(entity);

                return(entity);
            }
Пример #18
0
        public void BuildAndReloadAsset(AssetId assetId)
        {
            var assetToRebuild = Session.GetAssetById(assetId)?.AssetItem;

            if (assetToRebuild == null)
            {
                return;
            }

            if (assetToRebuild.Asset is SceneAsset)
            {
                // We never build the SceneAsset directly. Its content is build separately.
                // Note that the only case where this could happen is if a script or component references a scene directly, which is a bad design (should use scene streaming or prefabs instead).
                return;
            }

            Session.Dispatcher.InvokeAsync(() => BuildAndReloadAssets(assetToRebuild.Yield()));
        }
Пример #19
0
        public object LoadAsset(AssetId id)
        {
            try
            {
                var asset = LoadAssetInternal(id);
                return(asset is Exception ? null : asset);
            }
            catch (Exception e)
            {
                if (CoreUtil.IsCriticalException(e))
                {
                    throw;
                }

                Raise(new LogEvent(LogEvent.Level.Error, $"Could not load asset {id}: {e}"));
                return(null);
            }
        }
Пример #20
0
        public object LoadAsset(AssetId key, SerializationContext context, Func <AssetId, SerializationContext, object> loaderFunc)
        {
            if (loaderFunc == null)
            {
                throw new ArgumentNullException(nameof(loaderFunc));
            }
            var generalConfig = (IGeneralConfig)loaderFunc(new AssetId(AssetType.GeneralConfig), context);
            var filename      = Path.Combine(generalConfig.BasePath, generalConfig.SavePath, $"SAVE.{key.Id:D3}");

            var loader = _assetLoaderRegistry.GetLoader <SavedGame>(FileFormat.SavedGame);

            using var stream = disk.OpenRead(filename);
            using var br     = new BinaryReader(stream);
            return(loader.Serdes(
                       null,
                       context.Mapping,
                       new AlbionReader(br, stream.Length), key, null));
        }
Пример #21
0
        /// <summary>
        /// This method is called when an asset needs to be tracked
        /// </summary>
        /// <returns>AssetDependencies.</returns>
        private AssetDependencies TrackAsset(AssetId assetId)
        {
            lock (ThisLock)
            {
                AssetDependencies dependencies;
                if (Dependencies.TryGetValue(assetId, out dependencies))
                {
                    return(dependencies);
                }

                // TODO provide an optimized version of TrackAsset method
                // taking directly a well known asset (loaded from a Package...etc.)
                // to avoid session.FindAsset
                var assetItem = session.FindAsset(assetId);
                if (assetItem == null)
                {
                    return(null);
                }

                // Clone the asset before using it in this instance to make sure that
                // we have some kind of immutable state
                // TODO: This is not handling shadow registry

                // No need to clone assets from readonly package
                var assetItemCloned = assetItem.Package.IsSystem
                    ? assetItem
                    : new AssetItem(assetItem.Location, AssetCloner.Clone(assetItem.Asset), assetItem.Package)
                {
                    SourceFolder    = assetItem.SourceFolder,
                    AlternativePath = assetItem.AlternativePath,
                };

                dependencies = new AssetDependencies(assetItemCloned);

                // Adds to global list
                Dependencies.Add(assetId, dependencies);

                // Update dependencies
                UpdateAssetDependencies(dependencies);
                CheckAllDependencies();

                return(dependencies);
            }
        }
Пример #22
0
        public async Task PushContentReference(AbsoluteId referencerId, AssetId contentId, IGraphNode contentNode, NodeIndex index)
        {
            gameDispatcher.EnsureAccess();
            using (await loader.LockDatabaseAsynchronously())
            {
                if (!references.ContainsKey(referencerId))
                {
                    throw new InvalidOperationException("The given referencer is not registered.");
                }

                var referencer = references[referencerId];
                List <ReferenceAccessor> accessors;
                if (!referencer.TryGetValue(contentId, out accessors))
                {
                    accessors             = new List <ReferenceAccessor>();
                    referencer[contentId] = accessors;
                }
                var accessor = new ReferenceAccessor(contentNode, index);
                if (accessors.Contains(accessor))
                {
                    // If the reference already exists, clear it and re-enter
                    await ClearContentReference(referencerId, contentId, contentNode, index);
                    await PushContentReference(referencerId, contentId, contentNode, index);

                    return;
                }

                accessors.Add(accessor);

                object value;
                if (contents.TryGetValue(contentId, out value))
                {
                    accessor.Update(value);
                }
                else
                {
                    // Build only if not requested yet (otherwise we just need to wait for ReplaceContent() to be called, it will also replace this reference since it was added just before)
                    if (buildPending.Add(contentId))
                    {
                        loader.BuildAndReloadAsset(contentId);
                    }
                }
            }
        }
Пример #23
0
        public object Get(AssetId key)
        {
            lock (_syncRoot)
            {
                if (_assetCache.TryGetValue(key, out var cachedAsset))
                {
                    return(cachedAsset);
                }

                // Check old cache
                if (_oldAssetCache.TryGetValue(key, out var oldCachedAsset) && !(oldCachedAsset is Exception))
                {
                    _assetCache[key] = oldCachedAsset;
                    return(oldCachedAsset);
                }
            }

            return(null);
        }
Пример #24
0
        public AlbionPalette LoadPalette(PaletteId id)
        {
            var palette = (AlbionPalette)_modApplier.LoadAssetCached(id);

            if (palette == null)
            {
                return(null);
            }

            var commonId = AssetId.From(Base.Palette.CommonPalette);

            if (palette.Id != commonId.ToUInt32())
            {
                var commonPalette = (AlbionPalette)_modApplier.LoadAssetCached(commonId);
                palette.SetCommonPalette(commonPalette);
            }

            return(palette);
        }
Пример #25
0
        public static MapNpc Serdes(int _, MapNpc existing, MapType mapType, AssetMapping mapping, ISerializer s)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }
            var npc = existing ?? new MapNpc();

            byte id = (byte)npc.Id.ToDisk(mapping);

            id = s.UInt8(nameof(Id), id);
            // npc.Sound = (SampleId?)Tweak.Serdes(nameof(Sound), (byte?)npc.Sound, s.UInt8);
            npc.Sound = s.UInt8(nameof(Sound), npc.Sound);

            ushort?eventNumber = MaxToNullConverter.Serdes(nameof(npc.Node), npc.Node?.Id, s.UInt16);

            if (eventNumber != null && npc.Node == null)
            {
                npc.Node = new DummyEventNode(eventNumber.Value);
            }

            switch (mapType)
            {
            case MapType.ThreeD: npc.SpriteOrGroup = AssetId.SerdesU16(nameof(SpriteOrGroup), npc.SpriteOrGroup, AssetType.ObjectGroup, mapping, s); break;

            case MapType.TwoD: npc.SpriteOrGroup = SpriteId.SerdesU16(nameof(SpriteOrGroup), npc.SpriteOrGroup, AssetType.BigNpcGraphics, mapping, s); break;

            case MapType.TwoDOutdoors: npc.SpriteOrGroup = SpriteId.SerdesU16(nameof(SpriteOrGroup), npc.SpriteOrGroup, AssetType.SmallNpcGraphics, mapping, s); break;

            default: throw new ArgumentOutOfRangeException(nameof(mapType), mapType, null);
            }

            npc.Flags    = s.EnumU8(nameof(Flags), npc.Flags);
            npc.Movement = s.EnumU8(nameof(Movement), npc.Movement);
            npc.Unk8     = s.UInt8(nameof(Unk8), npc.Unk8);
            npc.Unk9     = s.UInt8(nameof(Unk9), npc.Unk9);

            var assetType = (npc.Flags & NpcFlags.IsMonster) != 0 ? AssetType.MonsterGroup : AssetType.Npc;

            npc.Id = AssetId.FromDisk(assetType, id, mapping);

            return(npc);
        }
Пример #26
0
        public object Process(ICoreFactory factory, AssetId key, object asset)
        {
            if (asset == null)
            {
                throw new ArgumentNullException(nameof(asset));
            }
            var dict     = (IDictionary <(int, GameLanguage), string>)asset;
            var result   = new Dictionary <int, string>();
            var settings = Resolve <IGameplaySettings>();

            foreach (var kvp in dict)
            {
                if (kvp.Key.Item2 == settings.Language)
                {
                    result[kvp.Key.Item1] = kvp.Value;
                }
            }
            return(result);
        }
Пример #27
0
        public async Task UnloadAsset(AssetId id)
        {
            GameDispatcher.EnsureAccess();

            // Unload this object if it has already been loaded.
            using (await database.LockAsync())
            {
                string url;
                if (AssetLoadingTimeUrls.TryGetValue(id, out url))
                {
                    UnloadContent(url);
                    // Remove assets that were previously loaded but are not anymore from the assetLoadingTimeUrls map.
                    foreach (var loadedUrls in AssetLoadingTimeUrls.Where(x => !Game.Content.IsLoaded(x.Value)).ToList())
                    {
                        AssetLoadingTimeUrls.Remove(loadedUrls.Key);
                    }
                }
            }
        }
Пример #28
0
        public static IList <ExportedImageInfo> ExportImage(AssetId assetId, IAssetManager assets, string directory, DumpFormats formats, Func <int, int, bool> frameFilter = null)
        {
            var filenames = new List <ExportedImageInfo>();
            var config    = assets.GetAssetInfo(assetId);
            var palette   = assets.LoadPalette((Base.Palette)(config?.Get <int?>("PaletteHint", null) ?? (int)Base.Palette.Inventory));
            var texture   = assets.LoadTexture(assetId);

            if (texture == null)
            {
                return(filenames);
            }

            if (texture is TrueColorTexture trueColor)
            {
                var path  = Path.Combine(directory, $"{assetId.Id}_{assetId}");
                var image = trueColor.ToImage();
                Save(image, path, formats, filenames);
            }
            else if (texture is VeldridEightBitTexture tilemap && (
                         assetId.Type == AssetType.Font ||
                         assetId.Type == AssetType.TilesetGraphics ||
                         assetId.Type == AssetType.AutomapGraphics))
            {
                if (palette == null)
                {
                    CoreUtil.LogError($"Could not load palette for {assetId}");
                    return(filenames);
                }

                var colors        = tilemap.DistinctColors(null);
                int palettePeriod = palette.CalculatePeriod(colors);

                for (int palFrame = 0; palFrame < palettePeriod; palFrame++)
                {
                    if (frameFilter != null && !frameFilter(0, palFrame))
                    {
                        continue;
                    }
                    var path  = Path.Combine(directory, $"{assetId.Id}_{palFrame}_{assetId}");
                    var image = tilemap.ToImage(palette.GetPaletteAtTime(palFrame));
                    Save(image, path, formats, filenames);
                }
            }
Пример #29
0
        private static AssetMarket[] ProcessAssetMkt(object[,] bag, DateTime refDate, DiscountCurve[] discountCurves)
        {
            var eqtyTime      = TimeMeasure.Act365(refDate);
            var assetRawDatas = bag.ProcessLabelledMatrix("Asset", o => o.ToString(), o => o.ToString(), o => o);

            TimeMatrixDatas repoRawDatas = bag.ProcessTimeMatrixDatas("Repo");
            var             repoPillars  = repoRawDatas.RowLabels
                                           .Select(dOrDur => dOrDur.ToDate(refDate)).ToArray();

            var assetMkts = new List <AssetMarket>();

            for (int i = 0; i < assetRawDatas.RowLabels.Length; i++)
            {
                var    assetName   = assetRawDatas.RowLabels[i];
                var    rawCurrency = assetRawDatas.GetColFromLabel("Currency")[i].ToString();
                object rawSpot     = assetRawDatas.GetColFromLabel("Spot")[i];

                var currency = Currency.Parse(rawCurrency);
                var assetId  = new AssetId(assetName, currency);

                double spot;
                if (!NumberConverter.TryConvertDouble(rawSpot, out spot))
                {
                    throw new ArgumentException(String.Format("AssetMarketFactory, invalid {0} spot : {1}", assetName, rawSpot));
                }

                double[] repoRates = repoRawDatas.GetColFromLabel(assetName);
                var      repoZcs   = repoRates.Select((r, idx) => Math.Exp(-eqtyTime[repoPillars[idx]] * r)).ToArray();
                var      repoCurve = DiscountCurve.LinearRateInterpol(FinancingId.AssetCollat(assetId), repoPillars, repoZcs, eqtyTime);

                var divQuotes = ProcessDiv(bag, refDate, assetName);
                var volMatrix = AssetVolMatrix(bag, eqtyTime, assetName);

                var riskFreeDiscount = discountCurves.Single(curve => curve.Financing.Equals(FinancingId.RiskFree(currency)));

                var mkt = new AssetMarket(assetId, refDate, eqtyTime,
                                          spot, riskFreeDiscount, repoCurve,
                                          divQuotes, volMatrix);
                assetMkts.Add(mkt);
            }

            return(assetMkts.ToArray());
        }
Пример #30
0
        public void TestHash()
        {
            var obj1 = new TestAssetClonerObject
            {
                Name      = "Test1",
                SubObject = new TestAssetClonerObject()
                {
                    Name = "Test2"
                },
                ObjectWithAttachedReference = new TestObjectReference()
            };

            // Create a fake reference to make sure that the attached reference will not be serialized
            var attachedReference = AttachedReferenceManager.GetOrCreateAttachedReference(obj1.ObjectWithAttachedReference);

            attachedReference.Url = "just_for_test";
            attachedReference.Id  = AssetId.New();

            var obj2 = AssetCloner.Clone(obj1);

            var hash1 = AssetHash.Compute(obj1);
            var hash2 = AssetHash.Compute(obj2);

            Assert.AreEqual(hash1, hash2);

            obj1.Name = "Yes";
            var hash11 = AssetHash.Compute(obj1);

            Assert.AreNotEqual(hash11, hash2);
            obj1.Name = "Test1";

            var hash12 = AssetHash.Compute(obj1);

            Assert.AreEqual(hash12, hash2);

            obj2 = AssetCloner.Clone(obj1);

            var hash1WithOverrides = AssetHash.Compute(obj1);
            var hash2WithOverrides = AssetHash.Compute(obj2);

            Assert.AreEqual(hash1WithOverrides, hash2WithOverrides);
        }
Пример #31
0
 /// <summary>
 /// Removes the broken link to the provided element.
 /// </summary>
 /// <param name="id">The id to the missing element</param>
 /// <exception cref="ArgumentNullException">toItem</exception>
 /// <returns>The removed link</returns>
 public IContentLink RemoveBrokenLinkOut(AssetId id)
 {
     return RemoveLink(ref missingChildren, id, ContentLinkType.All);
 }
Пример #32
0
        private AssetLink RemoveLink(ref Dictionary<AssetId, AssetLink> dictionary, AssetId id, ContentLinkType type)
        {
            if (dictionary == null || !dictionary.ContainsKey(id))
                throw new ArgumentException("There is currently no link between elements '{0}' and '{1}'".ToFormat(item.Id, id));

            var oldLink = dictionary[id];
            var newLink = oldLink;

            newLink.Type &= ~type;
            oldLink.Type &= type;

            if(newLink.Type == 0)
                dictionary.Remove(id);

            if (dictionary.Count == 0)
                dictionary = null;

            return oldLink;
        }
Пример #33
0
        private AssetLink GetLink(ref Dictionary<AssetId, AssetLink> dictionary, AssetId id)
        {
            if(dictionary == null || !dictionary.ContainsKey(id))
                throw new ArgumentException("There is currently no link between elements '{0}' and '{1}'".ToFormat(item.Id, id));

            return dictionary[id];
        }
 public AssetSerializableLogMessage(AssetId assetId, UFile assetUrl, LogMessageType type, string text, ExceptionInfo exceptionInfo = null)
     : base("", type, text, exceptionInfo)
 {
     AssetId = assetId;
     AssetUrl = assetUrl;
 }
        private void CollectInputReferences(AssetDependencies dependencyRoot, AssetId assetId, HashSet<AssetId> visited, bool recursive, ContentLinkType linkTypes, ref int count)
        {
            if (visited != null)
            {
                if (visited.Contains(assetId))
                    return;

                visited.Add(assetId);
            }

            count++;

            AssetDependencies dependencies;
            Dependencies.TryGetValue(assetId, out dependencies);
            if (dependencies != null)
            {
                foreach (var pair in dependencies.LinksIn)
                {
                    if ((linkTypes & pair.Type) != 0)
                    {
                        dependencyRoot.AddLinkIn(pair);

                        if (visited != null && recursive)
                        {
                            CollectInputReferences(dependencyRoot, pair.Item.Id, visited, true, linkTypes, ref count);
                        }
                    }
                }
            }
        }
 private AssetItem FindAssetFromDependencyOrSession(AssetId assetId)
 {
     // We cannot return the item from the session but we can only return assets currently tracked by the dependency 
     // manager
     var item = session.FindAsset(assetId);
     if (item != null)
     {
         var dependencies = TrackAsset(assetId);
         return dependencies.Item;
     }
     return null;
 }
Пример #37
0
        public void TestMovingAssets()
        {
            var basePath = Path.Combine(DirectoryTestBase, @"TestPackage");
            var projectPath = Path.Combine(basePath, "TestPackageLoadingWithAssets.xkpkg");

            var rootPackageId = new Guid("4102BF96-796D-4800-9983-9C227FAB7BBD");
            var testAssetId = new AssetId("C2D80EF9-2160-43B2-9FEE-A19A903A0BE0");

            // Load the project from the original location
            var sessionResult1 = PackageSession.Load(projectPath);
            {
                AssertResult(sessionResult1);
                var session = sessionResult1.Session;
                var project = session.Packages.Find(rootPackageId);
                Assert.IsNotNull(project);

                Assert.AreEqual(3, project.Assets.Count, "Invalid number of assets loaded");

                // Find the second asset that was referencing the changed asset
                var testAssetItem = session.FindAsset(testAssetId);
                Assert.NotNull(testAssetItem);

                var testAsset = (AssetObjectTest)testAssetItem.Asset;
                Assert.AreEqual(new UFile(Path.Combine(basePath, "SubFolder/TestAsset.xktest")), testAsset.RawAsset);

                // First save a copy of the project to TestPackageMovingAssets1
                project.FullPath = Path.Combine(DirectoryTestBase, @"TestPackageMovingAssets1\TestPackage2.xkpkg");
                var subPackage = session.Packages.Find(Guid.Parse("281321F0-7664-4523-B1DC-3CFC26F80F77"));
                subPackage.FullPath = Path.Combine(DirectoryTestBase, @"TestPackageMovingAssets1\SubPackage\SubPackage.xkpkg");
                session.Save();
            }

            // Reload the project from the location TestPackageMovingAssets1
            var sessionResult2 = PackageSession.Load(DirectoryTestBase + @"TestPackageMovingAssets1\TestPackage2.xkpkg");
            {
                AssertResult(sessionResult2);
                var session = sessionResult2.Session;
                var project = session.Packages.Find(rootPackageId);
                Assert.IsNotNull(project);
                Assert.AreEqual(3, project.Assets.Count, "Invalid number of assets loaded");

                // Move asset into a different directory
                var assetItem = project.Assets.Find(new AssetId("28D0DE9C-8913-41B1-B50E-848DD8A7AF65"));
                Assert.NotNull(assetItem);
                project.Assets.Remove(assetItem);

                var newAssetItem = new AssetItem("subTest/TestAsset2", assetItem.Asset);
                project.Assets.Add(newAssetItem);

                // Save the whole project to a different location
                project.FullPath = Path.Combine(DirectoryTestBase, @"TestPackageMovingAssets2\TestPackage2.xkpkg");
                var subPackage = session.Packages.Find(Guid.Parse("281321F0-7664-4523-B1DC-3CFC26F80F77"));
                subPackage.FullPath = Path.Combine(DirectoryTestBase, @"TestPackageMovingAssets2\SubPackage\SubPackage.xkpkg");
                session.Save();
            }

            // Reload the project from location TestPackageMovingAssets2
            var sessionResult3 = PackageSession.Load(DirectoryTestBase + @"TestPackageMovingAssets2\TestPackage2.xkpkg");
            {
                AssertResult(sessionResult3);
                var session = sessionResult3.Session;
                var project = session.Packages.Find(rootPackageId);
                Assert.IsNotNull(project);
                Assert.AreEqual(3, project.Assets.Count, "Invalid number of assets loaded");

                // Find the second asset that was referencing the changed asset
                var assetItemChanged = session.FindAsset(testAssetId);
                Assert.NotNull(assetItemChanged);

                // Check that references were correctly updated
                var assetChanged = (AssetObjectTest)assetItemChanged.Asset;
                Assert.AreEqual(new UFile(Path.Combine(Environment.CurrentDirectory, DirectoryTestBase) + "/TestPackage/SubFolder/TestAsset.xktest"), assetChanged.RawAsset);
                var text = File.ReadAllText(assetItemChanged.FullPath);
                Assert.True(text.Contains("../../TestPackage/SubFolder/TestAsset.xktest"));

                Assert.AreEqual("subTest/TestAsset2", assetChanged.Reference.Location);
            }
        }
        /// <summary>
        /// This method is called when an asset needs to be tracked
        /// </summary>
        /// <returns>AssetDependencies.</returns>
        private AssetDependencies TrackAsset(AssetId assetId)
        {
            lock (ThisLock)
            {
                AssetDependencies dependencies;
                if (Dependencies.TryGetValue(assetId, out dependencies))
                    return dependencies;

                // TODO provide an optimized version of TrackAsset method
                // taking directly a well known asset (loaded from a Package...etc.)
                // to avoid session.FindAsset 
                var assetItem = session.FindAsset(assetId);
                if (assetItem == null)
                {
                    return null;
                }

                // Clone the asset before using it in this instance to make sure that
                // we have some kind of immutable state
                // TODO: This is not handling shadow registry

                // No need to clone assets from readonly package 
                var assetItemCloned = assetItem.Package.IsSystem
                    ? assetItem
                    : new AssetItem(assetItem.Location, AssetCloner.Clone(assetItem.Asset), assetItem.Package)
                        {
                            SourceFolder = assetItem.SourceFolder,
                            SourceProject = assetItem.SourceProject
                        };
                
                dependencies = new AssetDependencies(assetItemCloned);

                // Adds to global list
                Dependencies.Add(assetId, dependencies);

                // Update dependencies
                UpdateAssetDependencies(dependencies);
                CheckAllDependencies();

                return dependencies;
            }
        }
        /// <summary>
        /// Finds the missing references for a particular asset.
        /// </summary>
        /// <param name="assetId">The asset identifier.</param>
        /// <returns>IEnumerable{IReference}.</returns>
        /// <exception cref="System.ArgumentNullException">item</exception>
        public IEnumerable<IReference> FindMissingReferences(AssetId assetId)
        {
            lock (Initialize())
            {
                AssetDependencies dependencies;
                if (AssetsWithMissingReferences.TryGetValue(assetId, out dependencies))
                {
                    return dependencies.BrokenLinksOut.Select(x => x.Element).ToList();
                }
            }

            return Enumerable.Empty<IReference>();
        }
        private void CollectOutputReferences(AssetDependencies dependencyRoot, AssetId assetId, HashSet<AssetId> visited, bool recursive, ContentLinkType linkTypes, ref int count)
        {
            if (visited != null)
            {
                if (visited.Contains(assetId))
                    return;

                visited.Add(assetId);
            }

            count++;

            var dependencies = CalculateDependencies(assetId);
            if (dependencies == null)
                return;

            // Add missing references
            foreach (var missingRef in dependencies.BrokenLinksOut)
            {
                dependencyRoot.AddBrokenLinkOut(missingRef);
            }

            // Add output references
            foreach (var child in dependencies.LinksOut)
            {
                if ((linkTypes & child.Type) != 0)
                {
                    dependencyRoot.AddLinkOut(child);

                    if (visited != null && recursive)
                    {
                        CollectOutputReferences(dependencyRoot, child.Item.Id, visited, true, linkTypes, ref count);
                    }
                }
            }
        }
Пример #41
0
 /// <summary>
 /// Registers an asset identifier for usage.
 /// </summary>
 /// <param name="assetId">The asset identifier.</param>
 /// <param name="newGuid">The new unique identifier if an asset has already been registered with the same id.</param>
 /// <returns><c>true</c> if the asset id is already in used. <paramref name="newGuid" /> contains a new guid, <c>false</c> otherwise.</returns>
 public bool RegisterId(AssetId assetId, out AssetId newGuid)
 {
     newGuid = assetId;
     var result = AlwaysCreateNewId || IsContainingId(assetId);
     if (result)
     {
         newGuid = AssetId.New();
     }
     ExistingIds.Add(newGuid);
     return result;
 }
 /// <summary>
 /// Finds an asset from all the packages by its id.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="assetId">The assetId of the asset.</param>
 /// <returns>An <see cref="AssetItem" /> or <c>null</c> if not found.</returns>
 public static AssetItem FindAsset(this PackageSession session, AssetId assetId)
 {
     var packages = session.Packages;
     return packages.Select(packageItem => packageItem.Assets.Find(assetId)).FirstOrDefault(asset => asset != null);
 }
Пример #43
0
 /// <summary>
 /// Determines whether the specified packages contains an asset by its guid.
 /// </summary>
 /// <param name="packages">The packages.</param>
 /// <param name="assetId">The asset unique identifier.</param>
 /// <returns><c>true</c> if the specified packages contains asset; otherwise, <c>false</c>.</returns>
 public static bool ContainsAsset(this IEnumerable<Package> packages, AssetId assetId)
 {
     return packages.Any(package => package.Assets.ContainsById(assetId));
 }
 /// <summary>
 /// Calculate the dependencies for the specified asset either by using the internal cache if the asset is already in the session
 /// or by calculating 
 /// </summary>
 /// <param name="assetId">The asset id.</param>
 /// <returns>The dependencies.</returns>
 private AssetDependencies CalculateDependencies(AssetId assetId)
 {
     AssetDependencies dependencies;
     Dependencies.TryGetValue(assetId, out dependencies);
     return dependencies;
 }
Пример #45
0
 /// <summary>
 /// Gets the broken link out to the provided element.
 /// </summary>
 /// <param name="id">The id of the element the link is going to</param>
 /// <returns>The link</returns>
 /// <exception cref="ArgumentException">There is not link to the provided element</exception>
 /// <exception cref="ArgumentNullException">toItem</exception>
 public IContentLink GetBrokenLinkOut(AssetId id)
 {
     return GetLink(ref missingChildren, id);
 }
        /// <summary>
        /// Computes the dependencies for the specified asset.
        /// </summary>
        /// <param name="assetId">The asset id.</param>
        /// <param name="dependenciesOptions">The dependencies options.</param>
        /// <param name="linkTypes">The type of links to visit while computing the dependencies</param>
        /// <param name="visited">The list of element already visited.</param>
        /// <returns>The dependencies, or null if the object is not tracked.</returns>
        public AssetDependencies ComputeDependencies(AssetId assetId, AssetDependencySearchOptions dependenciesOptions = AssetDependencySearchOptions.All, ContentLinkType linkTypes = ContentLinkType.All, HashSet<AssetId> visited = null)
        {
            bool recursive = (dependenciesOptions & AssetDependencySearchOptions.Recursive) != 0;
            if (visited == null && recursive)
                visited = new HashSet<AssetId>();

            //var clock = Stopwatch.StartNew();

            lock (Initialize())
            {
                AssetDependencies dependencies;
                if (!Dependencies.TryGetValue(assetId, out dependencies))
                    return null;

                dependencies = new AssetDependencies(dependencies.Item);

                int inCount = 0, outCount = 0;

                if ((dependenciesOptions & AssetDependencySearchOptions.In) != 0)
                {
                    CollectInputReferences(dependencies, assetId, visited, recursive, linkTypes, ref inCount);
                }

                if ((dependenciesOptions & AssetDependencySearchOptions.Out) != 0)
                {
                    visited?.Clear();
                    CollectOutputReferences(dependencies, assetId, visited, recursive, linkTypes, ref outCount);
                }

                //Console.WriteLine("Time to compute dependencies: {0}ms in: {1} out:{2}", clock.ElapsedMilliseconds, inCount, outCount);

                return dependencies;
            }

        }
Пример #47
0
 /// <summary>
 /// Finds an asset from all the packages by its id.
 /// </summary>
 /// <param name="package">The package.</param>
 /// <param name="assetId">The assetId of the asset.</param>
 /// <returns>An <see cref="AssetItem" /> or <c>null</c> if not found.</returns>
 public static AssetItem FindAsset(this Package package, AssetId assetId)
 {
     var packages = package.GetPackagesWithDependencies();
     return packages.Select(packageItem => packageItem.Assets.Find(assetId)).FirstOrDefault(asset => asset != null);
 }
 /// <summary>
 /// Updates the reference.
 /// </summary>
 /// <param name="guid">The unique identifier.</param>
 /// <param name="location">The location.</param>
 public void UpdateReference(AssetId? guid, string location)
 {
     reference = updateReference(guid, location);
 }
Пример #49
0
 /// <summary>
 /// Checks whether the <paramref name="id"/> is already contained.
 /// </summary>
 private bool IsContainingId(AssetId id)
 {
     if (ExistingIds.Contains(id))
     {
         return true;
     }
     return ContainsAssetWithId?.Invoke(id) ?? false;
 }
        /// <summary>
        /// Finds the assets the specified asset id inherits from (this is a direct inheritance, not indirect)..
        /// </summary>
        /// <param name="assetId">The asset identifier.</param>
        /// <param name="searchOptions">The types of inheritance to search for</param>
        /// <returns>A list of asset the specified asset id is inheriting from.</returns>
        public List<AssetItem> FindAssetInheritances(AssetId assetId, AssetInheritanceSearchOptions searchOptions = AssetInheritanceSearchOptions.All)
        {
            var list = new List<AssetItem>();
            lock (Initialize())
            {
                ContentLinkType searchType = 0;
                if ((searchOptions & AssetInheritanceSearchOptions.Base) != 0)
                    searchType |= ContentLinkType.Inheritance;
                if ((searchOptions & AssetInheritanceSearchOptions.Composition) != 0)
                    searchType |= ContentLinkType.CompositionInheritance;

                AssetDependencies dependencies;
                if (Dependencies.TryGetValue(assetId, out dependencies))
                {
                    list.AddRange(dependencies.LinksOut.Where(p => (p.Type & searchType) != 0).Select(p => p.Item.Clone(true)));
                }
            }
            return list;
        }