/// <summary>
 /// Initializes a new instance of the <see cref="AssetToImportMerge"/> class.
 /// </summary>
 /// <param name="previousItem">The previous item.</param>
 /// <param name="diff">The difference.</param>
 /// <param name="mergePreviewResult">The merge preview result.</param>
 internal AssetToImportMerge(AssetItem previousItem, AssetDiff diff, MergeResult mergePreviewResult)
 {
     PreviousItem = previousItem;
     this.Diff = diff;
     this.MergePreviewResult = mergePreviewResult;
     DependencyGroups = new List<AssetToImportMergeGroup>();
 }
 protected override void Compile(AssetCompilerContext context, AssetItem assetItem, string targetUrlInStorage, AssetCompilerResult result)
 {
     var asset = (EffectLogAsset)assetItem.Asset;
     var originalSourcePath = assetItem.FullPath;
     result.ShouldWaitForPreviousBuilds = true;
     result.BuildSteps = new AssetBuildStep(assetItem) { new EffectLogBuildStep(context, originalSourcePath, assetItem) };
 }
        public override void SaveGeneratedAsset(AssetItem assetItem)
        {
            //generate the .cs files
            // Always output a result into the file
            string result;
            try
            {
                var parsingResult = XenkoShaderParser.TryPreProcessAndParse(Text, assetItem.FullPath);

                if (parsingResult.HasErrors)
                {
                    result = "// Failed to parse the shader:\n" + parsingResult;
                }
                else
                {
                    // Try to generate a mixin code.
                    var shaderKeyGenerator = new ShaderMixinCodeGen(parsingResult.Shader, parsingResult);

                    shaderKeyGenerator.Run();
                    result = shaderKeyGenerator.Text ?? string.Empty;
                }
            }
            catch (Exception ex)
            {
                result = "// Unexpected exceptions occurred while generating the file\n" + ex;
            }

            // We force the UTF8 to include the BOM to match VS default
            var data = Encoding.UTF8.GetBytes(result);
           
            File.WriteAllBytes(assetItem.GetGeneratedAbsolutePath(), data);
        }
 public AssetItemMutable(AssetItem item)
 {
     Location = item.Location;
     SourceFolder = item.SourceFolder;
     Asset = item.Asset;
     ProjectFile = item.SourceProject;
 }
        /// <summary>
        /// Ensures that the sources of an <see cref="Asset"/> exist.
        /// </summary>
        /// <param name="result">The <see cref="AssetCompilerResult"/> in which to output log of potential errors.</param>
        /// <param name="assetItem">The asset to check.</param>
        /// <returns><c>true</c> if the source file exists, <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentNullException">Any of the argument is <c>null</c>.</exception>
        private static bool EnsureSourcesExist(AssetCompilerResult result, AssetItem assetItem)
        {
            if (result == null) throw new ArgumentNullException(nameof(result));
            if (assetItem == null) throw new ArgumentNullException(nameof(assetItem));

            var collector = new SourceFilesCollector();
            var sourceMembers = collector.GetSourceMembers(assetItem.Asset);

            foreach (var member in sourceMembers)
            {
                if (string.IsNullOrEmpty(member.Value))
                {
                    result.Error($"Source is null for Asset [{assetItem}] in property [{member.Key}]");
                    return false;
                }

                // Get absolute path of asset source on disk
                var assetDirectory = assetItem.FullPath.GetParent();
                var assetSource = UPath.Combine(assetDirectory, member.Value);

                // Ensure the file exists
                if (!File.Exists(assetSource))
                {
                    result.Error($"Unable to find the source file '{assetSource}' for Asset [{assetItem}]");
                    return false;
                }
            }

            return true;
        }
        protected override void Compile(AssetCompilerContext context, AssetItem assetItem, string targetUrlInStorage, AssetCompilerResult result)
        {
            var asset = (SkeletonAsset)assetItem.Asset;
            var assetSource = GetAbsolutePath(assetItem, asset.Source);
            var extension = assetSource.GetFileExtension();
            var buildStep = new AssetBuildStep(assetItem);

            var importModelCommand = ImportModelCommand.Create(extension);
            if (importModelCommand == null)
            {
                result.Error("No importer found for model extension '{0}. The model '{1}' can't be imported.", extension, assetSource);
                return;
            }

            importModelCommand.SourcePath = assetSource;
            importModelCommand.Location = targetUrlInStorage;
            importModelCommand.Mode = ImportModelCommand.ExportMode.Skeleton;
            importModelCommand.ScaleImport = asset.ScaleImport;
            importModelCommand.PivotPosition = asset.PivotPosition;
            importModelCommand.SkeletonNodesWithPreserveInfo = asset.NodesWithPreserveInfo;

            buildStep.Add(importModelCommand);

            result.BuildSteps = buildStep;
        }
        public AssetCompilerResult Compile(CompilerContext context, AssetItem assetItem)
        {
            if (context == null) throw new ArgumentNullException(nameof(context));
            if (assetItem == null) throw new ArgumentNullException(nameof(assetItem));

            var result = new AssetCompilerResult(GetType().Name)
            {
                BuildSteps = new AssetBuildStep(assetItem)
            };

            // Only use the path to the asset without its extension
            var fullPath = assetItem.FullPath;
            if (!fullPath.IsAbsolute)
            {
                throw new InvalidOperationException("assetItem must be an absolute path");
            }

            // Try to compile only if we're sure that the sources exist.
            if (EnsureSourcesExist(result, assetItem))
            {
                Compile((AssetCompilerContext)context, assetItem, assetItem.Location.GetDirectoryAndFileName(), result);
            }

            return result;
        }
        /// <inheritdoc/>
        public AssetCompilerResult Compile(CompilerContext context, AssetItem assetItem)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (assetItem == null) throw new ArgumentNullException("assetItem");

            var compilerResult = new AssetCompilerResult();

            if (assetItem.Package == null)
            {
                compilerResult.Warning("Asset [{0}] is not attached to a package", assetItem);
                return compilerResult;
            }

            var assetCompilerContext = (AssetCompilerContext)context;

            // create the a package that contains only the asset and its the dependencies
            var dependenciesCompilePackage = assetItem.Package.Session.CreateCompilePackageFromAsset(assetItem);
            var clonedAsset = dependenciesCompilePackage.FindAsset(assetItem.Id);

            CompileWithDependencies(assetCompilerContext, clonedAsset, assetItem, compilerResult);

            // Check unloadable items
            foreach (var currentAssetItem in dependenciesCompilePackage.Assets)
            {
                var unloadableItems = UnloadableObjectRemover.Run(currentAssetItem.Asset);
                foreach (var unloadableItem in unloadableItems)
                {
                    compilerResult.Log(new AssetLogMessage(dependenciesCompilePackage, currentAssetItem.ToReference(), LogMessageType.Warning, $"Unable to load the object of type {unloadableItem.UnloadableObject.TypeName} which is located at [{unloadableItem.MemberPath}] in the asset"));
                }
            }

            // Find AssetBuildStep
            var assetBuildSteps = new Dictionary<AssetId, AssetBuildStep>();
            foreach (var step in compilerResult.BuildSteps.EnumerateRecursively())
            {
                var assetStep = step as AssetBuildStep;
                if (assetStep != null)
                {
                    assetBuildSteps[assetStep.AssetItem.Id] = assetStep;
                }
            }

            // TODO: Refactor logging of CompilerApp and BuildEngine
            // Copy log top-level to proper asset build steps
            foreach (var message in compilerResult.Messages)
            {
                var assetMessage = message as AssetLogMessage;

                // Find asset (if nothing found, default to main asset)
                var assetId = assetMessage?.AssetReference.Id ?? assetItem.Id;
                AssetBuildStep assetBuildStep;
                if (assetBuildSteps.TryGetValue(assetId, out assetBuildStep))
                {
                    // Log to AssetBuildStep
                    assetBuildStep.Logger?.Log(message);
                }
            }

            return compilerResult;
        }
	static void LoadAssets()
	{
		// Get all assets that contained in different Resources folders
		var rootPaths = AssetDatabase.FindAssets("Resources").Select(item => AssetDatabase.GUIDToAssetPath(item));
		_assets = new List<AssetItem>();
		
		foreach(var path in rootPaths)
		{
			var dirInfo = new DirectoryInfo(path);
			// Exclude temporary folder if it contains "Resources" word
			if (!string.Equals(dirInfo.Name, _tempFolderName))
			{
				var rootItem = new AssetItem();
				
				rootItem.path = path;
				rootItem.name = dirInfo.Name;
				rootItem.isFolder = true;
				rootItem.AddChild(GetSubAssets(rootItem.path));
				
				_assets.Add(rootItem);
			}
		}
		
		if (File.Exists(GetAbsolutePath(_saveDataPath)))
		{
			if (!cleared)
			{
				LoadData();
			}
		}
		
		init = true;
	}
Exemple #10
0
 /// <summary>
 /// Constructs an <see cref="AssetCompiledArgs"/> instance.
 /// </summary>
 /// <param name="asset">The asset that has been compiled. Cannot be null.</param>
 /// <param name="result">The result of the asset compilation. Cannot be null.</param>
 public AssetCompiledArgs(AssetItem asset, AssetCompilerResult result)
 {
     if (asset == null) throw new ArgumentNullException("asset");
     if (result == null) throw new ArgumentNullException("result");
     Asset = asset;
     Result = result;
 }
        /// <inheritdoc/>
        public AssetCompilerResult Compile(CompilerContext context, AssetItem assetItem)
        {
            if (context == null) throw new ArgumentNullException("context");
            if (assetItem == null) throw new ArgumentNullException("assetItem");

            assetItem = assetItem.Package.Session.DependencyManager.FindDependencySet(assetItem.Id).Item;

            var compilerResult = new AssetCompilerResult();

            if (assetItem.Package == null)
            {
                compilerResult.Warning("Asset [{0}] is not attached to a package", assetItem);
                return compilerResult;
            }

            var assetCompilerContext = (AssetCompilerContext)context;

            // create the a package that contains only the asset and its the dependencies
            var dependenciesCompilePackage = assetItem.Package.Session.CreateCompilePackageFromAsset(assetItem);
            assetCompilerContext.Package = dependenciesCompilePackage.LocalPackages.FirstOrDefault();
            var clonedAsset = dependenciesCompilePackage.FindAsset(assetItem.Id);

            CompileWithDependencies(assetCompilerContext, clonedAsset, assetItem, compilerResult);

            return compilerResult;
        }
        public void TestUpdateAssetUrl()
        {
            var projectDir = new UFile(Path.Combine(Environment.CurrentDirectory, "testxk"));
            
            // Create a project with an asset reference a raw file
            var project = new Package { FullPath = projectDir };
            var assetItem = new AssetItem("test", new AssetObjectTest() { Reference =  new AssetReference<AssetObjectTest>(Guid.Empty, "good/location")});
            project.Assets.Add(assetItem);
            var goodAsset = new AssetObjectTest();
            project.Assets.Add(new AssetItem("good/location", goodAsset));

            // Add the project to the session to make sure analysis will run correctly
            var session = new PackageSession(project);

            // Create a session with this project
            var analysis = new PackageAnalysis(project,
                new PackageAnalysisParameters()
                    {
                        IsProcessingAssetReferences = true,
                        ConvertUPathTo = UPathType.Absolute,
                        IsProcessingUPaths = true
                    });
            var result = analysis.Run();
            Assert.IsFalse(result.HasErrors);
            Assert.AreEqual(1, result.Messages.Count);
            Assert.IsTrue(result.Messages[0].ToString().Contains("changed"));

            var asset = (AssetObjectTest)assetItem.Asset;
            Assert.AreEqual(goodAsset.Id, asset.Reference.Id);
            Assert.AreEqual("good/location", asset.Reference.Location);
        }
 /// <summary>
 /// Returns the absolute path on the disk of an <see cref="UFile"/> that is relative to the asset location.
 /// </summary>
 /// <param name="assetItem">The asset on which is based the relative path.</param>
 /// <param name="relativePath">The path relative to the asset path that must be converted to an absolute path.</param>
 /// <returns>The absolute path on the disk of the <see cref="relativePath"/> argument.</returns>
 /// <exception cref="ArgumentException">The <see cref="relativePath"/> argument is a null or empty <see cref="UFile"/>.</exception>
 protected static UFile GetAbsolutePath(AssetItem assetItem, UFile relativePath)
 {
     if (string.IsNullOrEmpty(relativePath)) throw new ArgumentException("The relativePath argument is null or empty");
     var assetDirectory = assetItem.FullPath.GetParent();
     var assetSource = UPath.Combine(assetDirectory, relativePath);
     return assetSource;
 }
        public void TestInheritance()
        {
            // -----------------------------------------------------------
            // Tests inheritance
            // -----------------------------------------------------------
            // 4 assets
            // [asset1] is referencing [asset2]
            // [asset2]
            // [asset3] is inheriting  [asset1]
            // We create a [project1] with [asset1, asset2, asset3]
            // Check direct inherit dependencies for [asset3]: [asset1]
            // -----------------------------------------------------------

            var asset1 = new AssetObjectTest();
            var asset2 = new AssetObjectTest();
            var assetItem1 = new AssetItem("asset-1", asset1);
            var assetItem2 = new AssetItem("asset-2", asset2);

            var asset3 = assetItem1.CreateChildAsset();
            var assetItem3 = new AssetItem("asset-3", asset3);

            asset1.Reference = new AssetReference<AssetObjectTest>(assetItem2.Id, assetItem2.Location);

            var project = new Package();
            project.Assets.Add(assetItem1);
            project.Assets.Add(assetItem2);
            project.Assets.Add(assetItem3);

            // Create a session with this project
            using (var session = new PackageSession(project))
            {
                var dependencyManager = session.DependencyManager;

                // Verify inheritance
                {
                    var assets = dependencyManager.FindAssetsInheritingFrom(asset1.Id);
                    Assert.AreEqual(1, assets.Count);
                    Assert.AreEqual(asset3.Id, assets[0].Id);
                }

                // Remove the inheritance
                var copyBase = asset3.Base;
                asset3.Base = null;
                assetItem3.IsDirty = true;
                {
                    var assets = dependencyManager.FindAssetsInheritingFrom(asset1.Id);
                    Assert.AreEqual(0, assets.Count);
                }

                // Add back the inheritance
                asset3.Base = copyBase;
                assetItem3.IsDirty = true;
                {
                    var assets = dependencyManager.FindAssetsInheritingFrom(asset1.Id);
                    Assert.AreEqual(1, assets.Count);
                    Assert.AreEqual(asset3.Id, assets[0].Id);
                }
            }
        }
Exemple #15
0
        /// <summary>
        /// Create an asset dependency of type <paramref name="type"/> and pointing to <paramref name="item"/>
        /// </summary>
        /// <param name="item">The item the dependency is pointing to</param>
        /// <param name="type">The type of the dependency between the items</param>
        public AssetLink(AssetItem item, ContentLinkType type)
        {
            if (item == null) throw new ArgumentNullException("item");

            Item = item;
            this.type = type;
            reference = item.ToReference();
        }
Exemple #16
0
        // This constructor exists for better factorization of code in AssetDependencies. 
        // It should not be turned into public as AssetItem is not valid.
        internal AssetLink(IContentReference reference, ContentLinkType type)
        {
            if (reference == null) throw new ArgumentNullException("reference");

            Item = null;
            this.type = type;
            this.reference = reference;
        }
 public void TestSimpleConstruction()
 {
     var container = new AssetPropertyGraphContainer(new PackageSession(), new AssetNodeContainer());
     var asset = new Types.MyAsset1 { MyString = "String" };
     var assetItem = new AssetItem("MyAsset", asset);
     var graph = AssetQuantumRegistry.ConstructPropertyGraph(container, assetItem, null);
     Assert.IsAssignableFrom<AssetNode>(graph.RootNode);
 }
 public void TestSimpleCollectionUpdate()
 {
     var container = new AssetPropertyGraphContainer(new PackageSession(), new AssetNodeContainer());
     var asset = new Types.MyAsset2 { MyStrings = { "aaa", "bbb", "ccc" } };
     var assetItem = new AssetItem("MyAsset", asset);
     var graph = AssetQuantumRegistry.ConstructPropertyGraph(container, assetItem, null);
     var node = ((IGraphNode)graph.RootNode).TryGetChild(nameof(Types.MyAsset2.MyStrings));
     //var ids = CollectionItemIdHelper.TryGetCollectionItemIds(asset.MyStrings, out itemIds);
 }
        private bool ProcessMergeAssetItem(AssetItem assetItem, HashSet<Guid> beingProcessed)
        {
            if (beingProcessed.Contains(assetItem.Id))
            {
                log.Error(package, assetItem.Asset.Base, AssetMessageCode.AssetNotFound, assetItem.Asset.Base);
                return false;
            }
            beingProcessed.Add(assetItem.Id);

            AssetItem existingAssetBase = null;
            List<AssetBasePart> existingBaseParts = null;

            // Process asset base
            if (assetItem.Asset.Base != null)
            {
                if (!ProcessMergeAssetBase(assetItem.Asset.Base, beingProcessed, out existingAssetBase))
                {
                    return false;
                }
            }

            // Process asset base parts
            if (assetItem.Asset.BaseParts != null && assetItem.Asset.BaseParts.Count > 0)
            {
                existingBaseParts = new List<AssetBasePart>();

                foreach (var basePart in assetItem.Asset.BaseParts)
                {
                    AssetItem existingAssetBasePart;
                    if (!ProcessMergeAssetBase(basePart.Base, beingProcessed, out existingAssetBasePart))
                    {
                        return false;
                    }

                    // Replicate the group with the list of ids
                    var newBasePart = new AssetBasePart(new AssetBase(existingAssetBasePart.Location, existingAssetBasePart.Asset));

                    // Instancing ids are copied from existing base part
                    newBasePart.InstanceIds.AddRange(basePart.InstanceIds);
                     
                    existingBaseParts.Add(newBasePart);
                }
            }

            // For simple merge (base, newAsset, newBase) => newObject
            // For multi-part prefabs merge (base, newAsset, newBase) + baseParts + newBaseParts => newObject
            if (!MergeAsset(assetItem, existingAssetBase, existingBaseParts))
            {
                return false;
            }

            assetsProcessed.Add(assetItem.Id, assetItem);
            assetsToProcess.Remove(assetItem.Id);

            return true;
        }
        /// <summary>
        /// Create a <see cref="Package"/> that can be used to compile an <see cref="AssetItem"/> by analyzing and resolving its dependencies.
        /// </summary>
        /// <returns>The package packageSession that can be used to compile the asset item.</returns>
        public static Package CreateCompilePackageFromAsset(this PackageSession session, AssetItem originalAssetItem)
        {
            // create the compile root package and package session
            var assetPackageCloned = new Package();
            var compilePackageSession = new PackageSession(assetPackageCloned);

            AddAssetToCompilePackage(session, originalAssetItem, assetPackageCloned);

            return assetPackageCloned;
        }
 internal AssetToImportMergeGroup(AssetToImportByImporter parent, AssetItem item)
 {
     if (parent == null) throw new ArgumentNullException("parent");
     if (item == null) throw new ArgumentNullException("item");
     this.Parent = parent;
     Item = item;
     Merges = new List<AssetToImportMerge>();
     Enabled = true;
     var assetDescription = DisplayAttribute.GetDisplay(item.Asset.GetType());
     Log = new LoggerResult(string.Format("Import {0} {1}", assetDescription != null ? assetDescription.Name : "Asset" , item));
 }
        public static void Run(AssetItem assetItem, ILogger log, AssetAnalysisParameters parameters)
        {
            if (assetItem == null) throw new ArgumentNullException(nameof(assetItem));
            if (log == null) throw new ArgumentNullException(nameof(log));
            if (parameters == null) throw new ArgumentNullException(nameof(parameters));

            if (assetItem.Package == null)
            {
                throw new InvalidOperationException("AssetItem must belong to an existing package");
            }

            var package = assetItem.Package;

            // Check that there is no duplicate in assets
            if (package.Session != null)
            {
                var packages = package.FindDependencies();

                foreach (var otherPackage in packages)
                {
                    var existingAsset = otherPackage.Assets.Find(assetItem.Id);

                    if (existingAsset != null)
                    {
                        log.Error("Assets [{0}] with id [{1}] from Package [{2}] is already loaded from package [{3}]", existingAsset.FullPath, existingAsset.Id, package.FullPath, existingAsset.Package.FullPath);
                    }
                    else
                    {
                        existingAsset = otherPackage.Assets.Find(assetItem.Location);
                        if (existingAsset != null)
                        {
                            log.Error("Assets [{0}] with location [{1}] from Package [{2}] is already loaded from package [{3}]", existingAsset.FullPath, existingAsset.Location, package.FullPath, existingAsset.Package.FullPath);
                        }
                    }
                }
            }

            var assetReferences = AssetReferenceAnalysis.Visit(assetItem.Asset);

            if (package.Session != null && parameters.IsProcessingAssetReferences)
            {
                UpdateAssetReferences(assetItem, assetReferences, log, parameters);
            }
            // Update paths for asset items

            if (parameters.IsProcessingUPaths)
            {
                // Find where this asset item was previously stored (in a different package for example)
                CommonAnalysis.UpdatePaths(assetItem, assetReferences.Where(link => link.Reference is UPath), parameters);
                // Source hashes are not processed by analysis, we need to manually indicate them to update
                SourceHashesHelper.UpdateUPaths(assetItem.Asset, assetItem.FullPath.GetParent(), parameters.ConvertUPathTo);
            }
        }
        protected override void Compile(AssetCompilerContext context, AssetItem assetItem, string targetUrlInStorage, AssetCompilerResult result)
        {
            var url = EffectCompilerBase.DefaultSourceShaderFolder + "/" + Path.GetFileName(assetItem.FullPath);
            var asset = (EffectShaderAsset)assetItem.Asset;

            var originalSourcePath = assetItem.FullPath;
            result.BuildSteps = new AssetBuildStep(assetItem) { new ImportStreamCommand { SourcePath = originalSourcePath, Location = url, SaveSourcePath = true } };
            var shaderLocations = (ConcurrentDictionary<string, string>)context.Properties.GetOrAdd(ShaderLocationsKey, key => new ConcurrentDictionary<string, string>());

            // Store directly this into the context TODO this this temporary
            shaderLocations[url] = originalSourcePath;
        }
 internal AssetToImportByImporter(AssetToImport parent, IAssetImporter importer, AssetItem previousItem = null)
 {
     if (parent == null) throw new ArgumentNullException("parent");
     if (importer == null) throw new ArgumentNullException("importer");
     this.Parent = parent;
     this.importer = importer;
     this.Items = new List<AssetToImportMergeGroup>();
     Enabled = true;
     Log = new LoggerResult(string.Format("{0} Importer", importer.Name));
     ImporterParameters = importer.GetDefaultParameters(previousItem != null);
     ImporterParameters.Logger = Log;
     PreviousItem = previousItem;
 }
 private static void SerializeAndCompare(AssetItem assetItem, AssetPropertyGraph graph, string expectedYaml, bool isDerived)
 {
     assetItem.Asset.Id = isDerived ? DerivedId : BaseId;
     Assert.AreEqual(isDerived, assetItem.Asset.Archetype != null);
     if (isDerived)
         assetItem.Asset.Archetype = new AssetReference(BaseId, assetItem.Asset.Archetype?.Location);
     graph.PrepareForSave(null, assetItem);
     var stream = new MemoryStream();
     AssetFileSerializer.Save(stream, assetItem.Asset, null, (Dictionary<YamlAssetPath, OverrideType>)assetItem.Overrides);
     stream.Position = 0;
     var streamReader = new StreamReader(stream);
     var yaml = streamReader.ReadToEnd();
     Assert.AreEqual(expectedYaml, yaml);
 }
Exemple #26
0
        public void TestPackageAndAssetIdChange()
        {
            var project = new Package();
            var assetItem = new AssetItem("test", new AssetObjectTest());
            var asset = assetItem.Asset;
            project.Assets.Add(assetItem);

            // Can't change an asset id once it is loaded into a project
            Assert.Throws<InvalidOperationException>(() => asset.Id = Guid.Empty);

            project.Assets.Remove(assetItem);

            // Can change Id once the asset was removed from the project
            Assert.DoesNotThrow(() => asset.Id = Guid.Empty);
        }
 public static AssetPropertyGraph ConstructPropertyGraph(AssetPropertyGraphContainer container, AssetItem assetItem, ILogger logger)
 {
     var assetType = assetItem.Asset.GetType();
     while (assetType != null)
     {
         Type propertyGraphType;
         var typeToTest = assetType.IsGenericType ? assetType.GetGenericTypeDefinition() : assetType;
         if (NodeGraphTypes.TryGetValue(typeToTest, out propertyGraphType))
         {
             return (AssetPropertyGraph)Activator.CreateInstance(propertyGraphType, container, assetItem, logger);
         }
         assetType = assetType.BaseType;
     }
     throw new InvalidOperationException("No AssetPropertyGraph type matching the given asset type has been found");
 }
 public void TestNestedCollectionConstruction()
 {
     var container = new AssetPropertyGraphContainer(new PackageSession(), new AssetNodeContainer());
     var asset = new Types.MyAsset7 { MyAsset2 = new Types.MyAsset2 { MyStrings = { "aaa", "bbb", "ccc" } } };
     var assetItem = new AssetItem("MyAsset", asset);
     var graph = AssetQuantumRegistry.ConstructPropertyGraph(container, assetItem, null);
     Assert.IsAssignableFrom<AssetNode>(graph.RootNode);
     CollectionItemIdentifiers ids;
     Assert.True(CollectionItemIdHelper.TryGetCollectionItemIds(asset.MyAsset2.MyStrings, out ids));
     Assert.AreEqual(3, ids.KeyCount);
     Assert.AreEqual(0, ids.DeletedCount);
     Assert.True(ids.ContainsKey(0));
     Assert.True(ids.ContainsKey(1));
     Assert.True(ids.ContainsKey(2));
 }
        public AssetPropertyGraph(AssetPropertyGraphContainer container, AssetItem assetItem, ILogger logger)
        {
            if (container == null) throw new ArgumentNullException(nameof(container));
            if (assetItem == null) throw new ArgumentNullException(nameof(assetItem));
            Container = container;
            AssetCollectionItemIdHelper.GenerateMissingItemIds(assetItem.Asset);
            CollectionItemIdsAnalysis.FixupItemIds(assetItem, logger);
            Asset = assetItem.Asset;
            RootNode = (AssetNode)Container.NodeContainer.GetOrCreateNode(assetItem.Asset);
            ApplyOverrides(RootNode, assetItem.Overrides);
            nodeListener = new GraphNodeChangeListener(RootNode, ShouldListenToTargetNode);
            nodeListener.Changing += AssetContentChanging;
            nodeListener.Changed += AssetContentChanged;

            baseLinker = new AssetToBaseNodeLinker(this) { LinkAction = LinkBaseNode };
        }
        public void TestCreateChildAsset()
        {
            // Create an Entity child asset

            // base: EA, EB, EC
            // newAsset: EA'(base: EA), EB'(base: EB), EC'(base: EC)

            var entityA = new Entity() { Name = "A" };
            var entityB = new Entity() { Name = "B" };
            var entityC = new Entity() { Name = "C" };

            // Create Base Asset
            var baseAsset = new EntityGroupAsset();
            baseAsset.Hierarchy.Entities.Add(new EntityDesign(entityA, new EntityDesignData()));
            baseAsset.Hierarchy.Entities.Add(new EntityDesign(entityB, new EntityDesignData()));
            baseAsset.Hierarchy.Entities.Add(new EntityDesign(entityC, new EntityDesignData()));
            baseAsset.Hierarchy.RootEntities.Add(entityA.Id);
            baseAsset.Hierarchy.RootEntities.Add(entityB.Id);
            baseAsset.Hierarchy.RootEntities.Add(entityC.Id);

            var baseAssetItem = new AssetItem("base", baseAsset);

            // Create new Asset (from base)
            var newAsset = (EntityGroupAsset)baseAssetItem.CreateChildAsset();

            // On a derive asset all entities must have a base value and base must come from baseAsset
            Assert.True(newAsset.Hierarchy.Entities.All(item => item.Design.BaseId.HasValue && baseAsset.Hierarchy.Entities.ContainsKey(item.Design.BaseId.Value)));

            // Verify that we have exactly the same number of entities
            Assert.AreEqual(baseAsset.Hierarchy.RootEntities.Count, newAsset.Hierarchy.RootEntities.Count);
            Assert.AreEqual(baseAsset.Hierarchy.Entities.Count, newAsset.Hierarchy.Entities.Count);

            // Verify that baseId and newId is correctly setup
            var entityAInNew = newAsset.Hierarchy.Entities.FirstOrDefault(item => item.Design.BaseId.Value == entityA.Id && item.Entity.Id != item.Design.BaseId.Value);
            Assert.NotNull(entityAInNew);

            var entityBInNew = newAsset.Hierarchy.Entities.FirstOrDefault(item => item.Design.BaseId.Value == entityB.Id && item.Entity.Id != item.Design.BaseId.Value);
            Assert.NotNull(entityBInNew);

            var entityCInNew = newAsset.Hierarchy.Entities.FirstOrDefault(item => item.Design.BaseId.Value == entityC.Id && item.Entity.Id != item.Design.BaseId.Value);
            Assert.NotNull(entityCInNew);

            // Verify that RootEntities are also correctly mapped
            Assert.AreEqual(entityAInNew.Entity.Id, newAsset.Hierarchy.RootEntities[0]);
            Assert.AreEqual(entityBInNew.Entity.Id, newAsset.Hierarchy.RootEntities[1]);
            Assert.AreEqual(entityCInNew.Entity.Id, newAsset.Hierarchy.RootEntities[2]);
        }
 public SpriteStudioSheetThumbnailCommand(ThumbnailCompilerContext context, string url, AssetItem spriteStudioSheetItem, IAssetFinder assetFinder, ThumbnailCommandParameters description)
     : base(context, spriteStudioSheetItem, assetFinder, url, description)
 {
 }
            public TextureThumbnailBuildCommand(ThumbnailCompilerContext context, string url, AssetItem assetItem, IAssetFinder assetFinder, TextureThumbnailParameters parameters)
                : base(context, assetItem, assetFinder, url, parameters)
            {
                // Compute color space to use during rendering with hint and color space set on texture
                var textureAsset = (TextureAsset)Parameters.Asset;

                AdditiveColor         = new Color(0.0f, 0.0f, 0.0f, 0.0f);
                parameters.ColorSpace = textureAsset.Type.IsSRgb(parameters.ColorSpace) ? ColorSpace.Linear : ColorSpace.Gamma;
                Swizzle = textureAsset.Type.Hint == TextureHint.Grayscale ? SwizzleMode.RRR1 : (textureAsset.Type.Hint == TextureHint.NormalMap ? SwizzleMode.NormalMap : SwizzleMode.None);
            }
        protected override void Compile(AssetCompilerContext context, AssetItem assetItem, string targetUrlInStorage, AssetCompilerResult result)
        {
            var asset             = (SpriteSheetAsset)assetItem.Asset;
            var gameSettingsAsset = context.GetGameSettingsAsset();
            var renderingSettings = gameSettingsAsset.Get <RenderingSettings>(context.Platform);

            result.BuildSteps = new ListBuildStep();

            // create the registry containing the sprite assets texture index association
            var imageToTextureUrl = new Dictionary <SpriteInfo, string>();

            var colorSpace = context.GetColorSpace();

            // create and add import texture commands
            if (asset.Sprites != null && !asset.Packing.Enabled)
            {
                // sort sprites by referenced texture.
                var spriteByTextures = asset.Sprites.GroupBy(x => x.Source).ToArray();
                for (int i = 0; i < spriteByTextures.Length; i++)
                {
                    // skip the texture if the file is not valid.
                    var textureFile = spriteByTextures[i].Key;
                    if (!TextureFileIsValid(textureFile))
                    {
                        continue;
                    }

                    var textureUrl = SpriteSheetAsset.BuildTextureUrl(targetUrlInStorage, i);

                    var spriteAssetArray = spriteByTextures[i].ToArray();
                    foreach (var spriteAsset in spriteAssetArray)
                    {
                        imageToTextureUrl[spriteAsset] = textureUrl;
                    }

                    // create an texture asset.
                    var textureAsset = new TextureAsset
                    {
                        Id               = AssetId.Empty, // CAUTION: It is important to use an empty GUID here, as we don't want the command to be rebuilt (by default, a new asset is creating a new guid)
                        Alpha            = asset.Alpha,
                        Format           = asset.Format,
                        GenerateMipmaps  = asset.GenerateMipmaps,
                        PremultiplyAlpha = asset.PremultiplyAlpha,
                        ColorKeyColor    = asset.ColorKeyColor,
                        ColorKeyEnabled  = asset.ColorKeyEnabled,
                        ColorSpace       = asset.ColorSpace,
                        Hint             = TextureHint.Color
                    };

                    // Get absolute path of asset source on disk
                    var assetDirectory = assetItem.FullPath.GetParent();
                    var assetSource    = UPath.Combine(assetDirectory, spriteAssetArray[0].Source);

                    // add the texture build command.
                    result.BuildSteps.Add(new AssetBuildStep(new AssetItem(textureUrl, textureAsset))
                    {
                        new TextureAssetCompiler.TextureConvertCommand(
                            textureUrl,
                            new TextureConvertParameters(assetSource, textureAsset, context.Platform, context.GetGraphicsPlatform(assetItem.Package), renderingSettings.DefaultGraphicsProfile, gameSettingsAsset.Get <TextureSettings>().TextureQuality, colorSpace))
                    });
                }
            }

            if (!result.HasErrors)
            {
                var parameters = new SpriteSheetParameters(asset, imageToTextureUrl, context.Platform, context.GetGraphicsPlatform(assetItem.Package), renderingSettings.DefaultGraphicsProfile, gameSettingsAsset.Get <TextureSettings>().TextureQuality, colorSpace);
                result.BuildSteps.Add(new AssetBuildStep(assetItem)
                {
                    new SpriteSheetCommand(targetUrlInStorage, parameters)
                });
            }
        }
 public AssertCommand(AssetItem assetItem, T parameters, IAssetFinder assetFinder, Action <string, T, IAssetFinder> assertFunc)
     : base(assetItem.Location, parameters, assetFinder)
 {
     this.assetItem  = assetItem;
     this.assertFunc = assertFunc;
 }
        protected override void CompileThumbnail(ThumbnailCompilerContext context, string thumbnailStorageUrl, AssetItem assetItem, Package originalPackage, AssetCompilerResult result)
        {
            var gameSettings      = context.GetGameSettingsAsset();
            var renderingSettings = gameSettings.GetOrCreate <RenderingSettings>();

            result.BuildSteps.Add(new ThumbnailBuildStep(new StaticThumbnailCommand <T>(thumbnailStorageUrl, staticImageData, context.ThumbnailResolution, renderingSettings.ColorSpace == ColorSpace.Linear, assetItem.Package)));
        }
 protected override void CompileThumbnail(ThumbnailCompilerContext context, string thumbnailStorageUrl, AssetItem assetItem, Package originalPackage, AssetCompilerResult result)
 {
     result.BuildSteps.Add(new ThumbnailBuildStep(new SpriteStudioSheetThumbnailCommand(context, thumbnailStorageUrl, assetItem, originalPackage,
                                                                                        new ThumbnailCommandParameters(assetItem.Asset, thumbnailStorageUrl, context.ThumbnailResolution))));
 }
Exemple #37
0
 public AssetCompositePropertyGraph([NotNull] AssetPropertyGraphContainer container, [NotNull] AssetItem assetItem, ILogger logger)
     : base(container, assetItem, logger)
 {
 }
        public void CompilerVisitRuntimeType()
        {
            PackageSessionPublicHelper.FindAndSetMSBuildVersion();

            var package = new Package();
            // ReSharper disable once UnusedVariable - we need a package session to compile
            var packageSession = new PackageSession(package);
            var otherAssets    = new List <AssetItem>
            {
                new AssetItem("contentRB", new MyAssetContentType(0), package),
                new AssetItem("contentRA", new MyAssetContentType(1), package),
                new AssetItem("content0B", new MyAssetContentType(2), package),
                new AssetItem("content0M", new MyAssetContentType(3), package),
                new AssetItem("content0A", new MyAssetContentType(4), package),
                new AssetItem("content1B", new MyAssetContentType(5), package),
                new AssetItem("content1M", new MyAssetContentType(6), package),
                new AssetItem("content1A", new MyAssetContentType(7), package),
                new AssetItem("content2B", new MyAssetContentType(8), package),
                new AssetItem("content2M", new MyAssetContentType(9), package),
                new AssetItem("content2A", new MyAssetContentType(10), package),
                new AssetItem("content3B", new MyAssetContentType(11), package),
                new AssetItem("content3M", new MyAssetContentType(12), package),
                new AssetItem("content3A", new MyAssetContentType(13), package),
                new AssetItem("content4B", new MyAssetContentType(14), package),
                new AssetItem("content4M", new MyAssetContentType(15), package),
                new AssetItem("content4A", new MyAssetContentType(16), package),
            };

            var assetToVisit = new MyAsset1();

            assetToVisit.Before = AttachedReferenceManager.CreateProxyObject <MyContentType>(otherAssets[0].Id, otherAssets[0].Location);
            assetToVisit.Zafter = AttachedReferenceManager.CreateProxyObject <MyContentType>(otherAssets[1].Id, otherAssets[1].Location);
            assetToVisit.RuntimeTypes.Add(CreateRuntimeType(otherAssets[2], otherAssets[3], otherAssets[4]));
            assetToVisit.RuntimeTypes.Add(CreateRuntimeType(otherAssets[5], otherAssets[6], otherAssets[7]));
            assetToVisit.RuntimeTypes.Add(CreateRuntimeType(otherAssets[8], otherAssets[9], otherAssets[10]));
            assetToVisit.RuntimeTypes.Add(CreateRuntimeType(otherAssets[11], otherAssets[12], otherAssets[13]));
            assetToVisit.RuntimeTypes.Add(CreateRuntimeType(otherAssets[14], otherAssets[15], otherAssets[16]));
            assetToVisit.RuntimeTypes[0].A = assetToVisit.RuntimeTypes[1];
            assetToVisit.RuntimeTypes[0].B = assetToVisit.RuntimeTypes[2];
            assetToVisit.RuntimeTypes[1].A = assetToVisit.RuntimeTypes[3];
            assetToVisit.RuntimeTypes[1].B = assetToVisit.RuntimeTypes[4];

            otherAssets.ForEach(x => package.Assets.Add(x));
            var assetItem = new AssetItem("asset", assetToVisit, package);

            package.Assets.Add(assetItem);
            package.RootAssets.Add(new AssetReference(assetItem.Id, assetItem.Location));

            // Create context
            var context = new AssetCompilerContext {
                CompilationContext = typeof(AssetCompilationContext)
            };

            // Builds the project
            var assetBuilder = new PackageCompiler(new RootPackageAssetEnumerator(package));

            context.Properties.Set(BuildAssetNode.VisitRuntimeTypes, true);
            var assetBuildResult = assetBuilder.Prepare(context);

            Assert.Equal(16, assetBuildResult.BuildSteps.Count);
        }
Exemple #39
0
 public virtual IEnumerable <ObjectUrl> GetInputFiles(AssetItem assetItem)
 {
     yield break;
 }
Exemple #40
0
 public virtual IEnumerable <Type> GetRuntimeTypes(AssetItem assetItem)
 {
     yield break;
 }
Exemple #41
0
 public abstract AssetCompilerResult Prepare(AssetCompilerContext context, AssetItem assetItem);
Exemple #42
0
 public PrefabModelAssetCompileCommand(string url, PrefabModelAsset parameters, AssetItem assetItem, RenderingSettings renderingSettings)
     : base(url, parameters)
 {
     package = assetItem.Package;
     this.renderingSettings = renderingSettings;
 }
 public CustomAssetThumbnailBuildCommand(ThumbnailCompilerContext context, string url, AssetItem assetItem, IAssetFinder assetFinder, ThumbnailCommandParameters description)
     : base(context, assetItem, assetFinder, url, description)
 {
 }
        /// <inheritdoc />
        protected override void CompileThumbnail(ThumbnailCompilerContext context, string thumbnailStorageUrl, AssetItem assetItem, Package originalPackage, AssetCompilerResult result)
        {
            var   thumbnailSize = context.ThumbnailResolution;
            UFile assetSource   = null;

            var sourceValid = !string.IsNullOrEmpty(Asset.Source);

            if (sourceValid)
            {
                // Get absolute path of asset source on disk
                var assetDirectory = assetItem.FullPath.GetParent();
                assetSource = UPath.Combine(assetDirectory, Asset.Source);
                sourceValid = File.Exists(assetSource);
            }

            if (sourceValid)
            {
                result.BuildSteps.Add(new ThumbnailBuildStep(new TextureThumbnailBuildCommand(context, thumbnailStorageUrl, assetItem, originalPackage, new TextureThumbnailParameters(Asset, assetSource, thumbnailStorageUrl, thumbnailSize))));
            }
            else
            {
                var gameSettings = context.GetGameSettingsAsset();
                result.Error($"Source is null or unreachable for Texture Asset [{Asset}]");
                result.BuildSteps.Add(new StaticThumbnailCommand <TextureAsset>(thumbnailStorageUrl, DefaultThumbnails.TextureNoSource, thumbnailSize, gameSettings.GetOrCreate <RenderingSettings>().ColorSpace == ColorSpace.Linear, assetItem.Package));
            }
        }
Exemple #45
0
        public static IEnumerator CoCreatePreviews(ProjectItem[] items, IProject project, IResourcePreviewUtility resourcePreview, Action done = null)
        {
            if (resourcePreview == null)
            {
                if (done != null)
                {
                    done();
                }
                yield break;
            }

            IRTE rte = IOC.Resolve <IRTE>();

            if (rte.Selection.activeObject != null)
            {
                long        id = project.ToID(rte.Selection.activeObject);
                ProjectItem selectedProjectItem = items.Where(item => item.ItemID == id).FirstOrDefault();
                if (selectedProjectItem != null && selectedProjectItem is AssetItem)
                {
                    AssetItem selectedAssetItem = (AssetItem)selectedProjectItem;
                    selectedAssetItem.Preview = null;
                }
            }

            for (int i = 0; i < items.Length; ++i)
            {
                ImportItem importItem = items[i] as ImportItem;
                if (importItem != null)
                {
                    if (/*importItem.Preview == null &&*/ importItem.Object != null)
                    {
                        importItem.Preview = new Preview
                        {
                            ItemID      = importItem.ItemID,
                            PreviewData = resourcePreview.CreatePreviewData(importItem.Object)
                        };
                    }
                }
                else
                {
                    AssetItem assetItem = items[i] as AssetItem;
                    if (assetItem != null)
                    {
                        UnityObject obj = null;
                        if (assetItem.Preview == null)
                        {
                            obj = project.FromID <UnityObject>(assetItem.ItemID);
                        }

                        if (obj != null)
                        {
                            assetItem.Preview = new Preview
                            {
                                ItemID      = assetItem.ItemID,
                                PreviewData = resourcePreview.CreatePreviewData(obj)
                            };
                        }
                    }
                }

                if (i % 10 == 0)
                {
                    yield return(new WaitForSeconds(0.005f));
                }
            }

            if (done != null)
            {
                done();
            }
        }
Exemple #46
0
 public AssetTestContainer(AssetPropertyGraphContainer container, Asset asset)
 {
     Container = container;
     AssetItem = new AssetItem("MyAsset", asset);
 }
 protected ThumbnailFromEntityCommand(ThumbnailCompilerContext context, AssetItem assetItem, IAssetFinder assetFinder, string url, ThumbnailCommandParameters parameters)
     : base(context, assetItem, assetFinder, url, parameters)
 {
 }
 public HeightmapThumbnailCommand(ThumbnailCompilerContext context, AssetItem assetItem, IAssetFinder assetFinder, string url, ThumbnailCommandParameters parameters)
     : base(context, assetItem, assetFinder, url, parameters)
 {
     parameters.ColorSpace = ColorSpace.Linear;
 }
 public override IEnumerable <Type> GetRuntimeTypes(AssetItem assetItem)
 {
     yield return(typeof(MyRuntimeType));
 }
        private static MyRuntimeType CreateRuntimeType(AssetItem beforeReference, AssetItem middleReference, AssetItem afterReference)
        {
            var result = new MyRuntimeType
            {
                Before = CreateRef <MyContentType>(beforeReference),
                Middle = CreateRef <MyContentType>(middleReference),
                Zafter = CreateRef <MyContentType>(afterReference),
            };

            return(result);
        }
        private void Spawn(AssetItem item, SceneGraphNode hit, ref Vector3 hitLocation)
        {
            // TODO: refactor this and dont use ContentDomain but only asset Type for matching

            if (item is BinaryAssetItem binaryAssetItem)
            {
                if (binaryAssetItem.Type == typeof(ParticleSystem))
                {
                    var particleSystem = FlaxEngine.Content.LoadAsync <ParticleSystem>(item.ID);
                    var actor          = ParticleEffect.New();
                    actor.Name           = item.ShortName;
                    actor.ParticleSystem = particleSystem;
                    actor.Position       = PostProcessSpawnedActorLocation(actor, ref hitLocation);
                    Spawn(actor);

                    return;
                }
            }

            switch (item.ItemDomain)
            {
            case ContentDomain.Material:
            {
                if (hit is StaticModelNode.EntryNode meshNode)
                {
                    var material = FlaxEngine.Content.LoadAsync <MaterialBase>(item.ID);
                    using (new UndoBlock(Undo, meshNode.Model, "Change material"))
                        meshNode.Entry.Material = material;
                }
                else if (hit is BoxBrushNode.SideLinkNode brushSurfaceNode)
                {
                    var material = FlaxEngine.Content.LoadAsync <MaterialBase>(item.ID);
                    using (new UndoBlock(Undo, brushSurfaceNode.Brush, "Change material"))
                        brushSurfaceNode.Surface.Material = material;
                }

                break;
            }

            case ContentDomain.Model:
            {
                if (item.TypeName == typeof(SkinnedModel).FullName)
                {
                    var model = FlaxEngine.Content.LoadAsync <SkinnedModel>(item.ID);
                    var actor = AnimatedModel.New();
                    actor.Name         = item.ShortName;
                    actor.SkinnedModel = model;
                    actor.Position     = PostProcessSpawnedActorLocation(actor, ref hitLocation);
                    Spawn(actor);
                }
                else
                {
                    var model = FlaxEngine.Content.LoadAsync <Model>(item.ID);
                    var actor = StaticModel.New();
                    actor.Name     = item.ShortName;
                    actor.Model    = model;
                    actor.Position = PostProcessSpawnedActorLocation(actor, ref hitLocation);
                    Spawn(actor);
                }

                break;
            }

            case ContentDomain.Audio:
            {
                var clip  = FlaxEngine.Content.LoadAsync <AudioClip>(item.ID);
                var actor = AudioSource.New();
                actor.Name     = item.ShortName;
                actor.Clip     = clip;
                actor.Position = PostProcessSpawnedActorLocation(actor, ref hitLocation);
                Spawn(actor);

                break;
            }

            case ContentDomain.Prefab:
            {
                var prefab = FlaxEngine.Content.LoadAsync <Prefab>(item.ID);
                var actor  = PrefabManager.SpawnPrefab(prefab, null);
                actor.Name     = item.ShortName;
                actor.Position = PostProcessSpawnedActorLocation(actor, ref hitLocation);
                Spawn(actor);

                break;
            }

            default: throw new ArgumentOutOfRangeException();
            }
        }
        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);
            }
        }
 public ProceduralModelThumbnailBuildCommand(ThumbnailCompilerContext context, string url, AssetItem modelItem, IAssetFinder assetFinder, ThumbnailCommandParameters description)
     : base(context, modelItem, assetFinder, url, description)
 {
 }
Exemple #54
0
        private void Prepare(AssetCompilerResult finalResult, AssetCompilerContext context, AssetItem assetItem, [NotNull] Type compilationContext, HashSet <BuildAssetNode> visitedItems, Dictionary <AssetId, BuildStep> compiledItems, BuildStep parentBuildStep = null,
                             BuildDependencyType dependencyType = BuildDependencyType.Runtime)
        {
            if (compilationContext == null)
            {
                throw new ArgumentNullException(nameof(compilationContext));
            }
            var assetNode = BuildDependencyManager.FindOrCreateNode(assetItem, compilationContext);

            compiledItems.TryGetValue(assetNode.AssetItem.Id, out var assetBuildSteps);

            // Prevent re-entrancy in the same node
            if (visitedItems.Add(assetNode))
            {
                assetNode.Analyze(context);

                // Invoke the compiler to prepare the build step for this asset if the dependency needs to compile it (Runtime or CompileContent)
                if ((dependencyType & ~BuildDependencyType.CompileAsset) != 0 && assetBuildSteps == null)
                {
                    var mainCompiler = BuildDependencyManager.AssetCompilerRegistry.GetCompiler(assetItem.Asset.GetType(), assetNode.CompilationContext);
                    if (mainCompiler == null)
                    {
                        return;
                    }

                    var compilerResult = mainCompiler.Prepare(context, assetItem);

                    if ((dependencyType & BuildDependencyType.Runtime) == BuildDependencyType.Runtime && compilerResult.HasErrors) //allow Runtime dependencies to fail
                    {
                        assetBuildSteps = new ErrorBuildStep(assetItem, compilerResult.Messages);
                    }
                    else
                    {
                        assetBuildSteps = compilerResult.BuildSteps;
                        compiledItems.Add(assetNode.AssetItem.Id, assetBuildSteps);

                        // Copy the log to the final result (note: this does not copy or forward the build steps)
                        compilerResult.CopyTo(finalResult);
                        if (compilerResult.HasErrors)
                        {
                            finalResult.Error($"Failed to prepare asset {assetItem.Location}");
                            return;
                        }
                    }

                    // Add the resulting build steps to the final
                    finalResult.BuildSteps.Add(assetBuildSteps);

                    AssetCompiled?.Invoke(this, new AssetCompiledArgs(assetItem, compilerResult));
                }

                // Go through the dependencies of the node and prepare them as well
                foreach (var reference in assetNode.References)
                {
                    var target = reference.Target;
                    Prepare(finalResult, context, target.AssetItem, target.CompilationContext, visitedItems, compiledItems, assetBuildSteps, reference.DependencyType);
                    if (finalResult.HasErrors)
                    {
                        return;
                    }
                }

                // If we didn't prepare any build step for this asset let's exit here.
                if (assetBuildSteps == null)
                {
                    return;
                }
            }

            // Link the created build steps to their parent step.
            if (parentBuildStep != null && assetBuildSteps != null && (dependencyType & BuildDependencyType.CompileContent) == BuildDependencyType.CompileContent) //only if content is required Content.Load
            {
                BuildStep.LinkBuildSteps(assetBuildSteps, parentBuildStep);
            }
        }
 protected override void CompileThumbnail(ThumbnailCompilerContext context, string thumbnailStorageUrl, AssetItem assetItem, Package originalPackage, AssetCompilerResult result)
 {
     result.BuildSteps.Add(
         new ThumbnailBuildStep(
             new HeightmapThumbnailCommand(context, assetItem, originalPackage, thumbnailStorageUrl,
                                           new ThumbnailCommandParameters(assetItem.Asset, thumbnailStorageUrl, context.ThumbnailResolution))
     {
         InputFilesGetter = () => GetInputFiles(assetItem)
     }));
 }
Exemple #56
0
 public ErrorBuildStep(AssetItem assetItem, IEnumerable <ILogMessage> messages)
     : base(assetItem)
 {
     this.messages = messages.ToList();
 }
Exemple #57
0
        protected override void PostAssetCreation(AssetTemplateGeneratorParameters parameters, AssetItem assetItem)
        {
            base.PostAssetCreation(parameters, assetItem);
            var material = parameters.GetTag(MaterialKey);

            ((PrimitiveProceduralModelBase)((ProceduralModelAsset)assetItem.Asset).Type).MaterialInstance.Material = material;
        }
 /// <summary>
 /// Validates the asset items drag operation.
 /// </summary>
 /// <param name="assetItem">The asset item.</param>
 /// <returns>True if can drag that item, otherwise false.</returns>
 protected virtual bool ValidateDragItem(AssetItem assetItem)
 {
     return(false);
 }
Exemple #59
0
 public void CopyTo(AssetItem target)
 {
     target.Id    = Id;
     target.Asset = Asset;
 }
        public override IEnumerable <Type> GetInputTypesToExclude(AssetItem assetItem)
        {
            yield return(typeof(SceneAsset));

            yield return(typeof(NavigationMeshAsset));
        }