Пример #1
0
        private void BuildEffect(string effectFile, TargetPlatform targetPlatform, string defines = null)
        {
            var importerContext = new ImporterContext();
            var importer = new EffectImporter();
            var input = importer.Import(effectFile, importerContext);

            Assert.NotNull(input);

            var processorContext = new TestProcessorContext(targetPlatform, Path.ChangeExtension(effectFile, ".xnb"));
            var processor = new EffectProcessor { Defines = defines };
            var output = processor.Process(input, processorContext);

            Assert.NotNull(output);

            // TODO: Should we test the writer?
        }
Пример #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="src"></param>
        /// <param name="prefabPath"></param>
        public static void ImportAsset(string src, UnityPath prefabPath)
        {
            if (!prefabPath.IsUnderAssetsFolder)
            {
                Debug.LogWarningFormat("out of asset path: {0}", prefabPath);
                return;
            }

            var context = new ImporterContext();

            context.Parse(src);

            // Extract textures to assets folder
            context.ExtractImages(prefabPath);

            ImportDelayed(src, prefabPath, context);
        }
Пример #3
0
        private void EditorImport(ImporterContext context)
        {
            var animationClips             = new AnimationClip[context.GLTF.animations.Count];
            List <AnimationClip> usedClips = new List <AnimationClip>();

            // node extension animation
            for (int i = 0; i < context.GLTF.nodes.Count; i++)
            {
                var node = context.GLTF.nodes[i];
                if (node.extensions == null || node.extensions.VCAST_vci_animation == null)
                {
                    continue;
                }

                var vciAnimation = node.extensions.VCAST_vci_animation;
                var root         = context.Nodes[i];
                var animation    = root.gameObject.AddComponent <Animation>();

                foreach (var animationReference in vciAnimation.animationReferences)
                {
                    if (context.AnimationClips[animationReference.animation] != null)
                    {
                        var clip = context.AnimationClips[animationReference.animation];
                        animation.AddClip(clip, clip.name);
                        usedClips.Add(clip);
                    }
                }
            }

            // root animation
            var rootAnimation = context.Root.GetComponent <Animation>();

            if (rootAnimation == null)
            {
                rootAnimation = context.Root.AddComponent <Animation>();
            }

            foreach (var clip in context.AnimationClips)
            {
                if (!usedClips.Contains(clip))
                {
                    rootAnimation.AddClip(clip, clip.name);
                }
            }
        }
Пример #4
0
        private void LoadMotion(string path)
        {
            try
            {
                // Trigger BVH
                _bvhLoadingTrigger = true;
                // Save current path
                _bvhPathLocal = path;
                var previous_motion = _bvhMotion;
                if (previous_motion != null)
                {
                    Destroy(previous_motion.Root);
                }

                var context = new UniHumanoid.ImporterContext
                {
                    Path = path
                };
                _bvhMotion = context;
                UniHumanoid.BvhImporter.Import(context);

                if (context.Avatar == null || context.Avatar.isValid == false)
                {
                    if (context.Root != null)
                    {
                        Destroy(context.Root);
                    }
                    throw new Exception("BVH importer failed");
                }

                // Send BVH
                _informationUpdate.SetBVH(_bvhMotion.Root);

                SetMotion(context.Root.GetComponent <HumanPoseTransfer>());
            }
            catch (Exception e)
            {
                if (_bvhMotion.Root == true)
                {
                    Destroy(_bvhMotion.Root);
                }
                _errorMessagePanel.SetMessage(MultipleLanguageSupport.BvhLoadErrorMessage + "\nError message: " + e.Message);
                throw;
            }
        }
        private void BuildEffect(string effectFile, TargetPlatform targetPlatform, string defines = null)
        {
            var importerContext = new ImporterContext();
            var importer        = new EffectImporter();
            var input           = importer.Import(effectFile, importerContext);

            Assert.NotNull(input);

            var processorContext = new TestProcessorContext(targetPlatform, Path.ChangeExtension(effectFile, ".xnb"));
            var processor        = new EffectProcessor {
                Defines = defines
            };
            var output = processor.Process(input, processorContext);

            Assert.NotNull(output);

            // TODO: Should we test the writer?
        }
Пример #6
0
        /// <summary>
        /// Import GLB.
        /// </summary>
        /// <returns></returns>
        public static void ImportGlb()
        {
            string path = EditorUtility.OpenFilePanel(title: "Open File Dialog", directory: "", extension: "glb");

            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            if (Application.isPlaying)
            {
                //
                // load into scene
                //
                var context = new ImporterContext();

                context.Load(path);

                context.ShowMeshes();

                Selection.activeGameObject = context.Root;
            }
            else
            {
                //
                // save as asset
                //
                if (path.StartsWithUnityAssetPath())
                {
                    Debug.LogWarningFormat("disallow import from folder under the Assets");
                    return;
                }

                string assetPath = EditorUtility.SaveFilePanel(title: "Save prefab", directory: "Assets", defaultName: Path.GetFileNameWithoutExtension(path), extension: "prefab");

                if (string.IsNullOrEmpty(path))
                {
                    return;
                }

                // import as asset
                GlbAssetPostprocessor.ImportAsset(src: path, prefabPath: UnityPath.FromFullpath(assetPath));
            }
        }
Пример #7
0
    GameObject Load(string path)
    {
        var bytes = File.ReadAllBytes(path);

        Debug.LogFormat("[OnClick] {0}", path);
        var context = new ImporterContext();

        var ext = Path.GetExtension(path).ToLower();

        switch (ext)
        {
        case ".gltf":
            context.ParseJson(Encoding.UTF8.GetString(bytes), new FileSystemStorage(Path.GetDirectoryName(path)));
            break;

        case ".zip":
        {
            var zipArchive = UniGLTF.Zip.ZipArchiveStorage.Parse(bytes);
            var gltf       = zipArchive.Entries.FirstOrDefault(x => x.FileName.ToLower().EndsWith(".gltf"));
            if (gltf == null)
            {
                throw new Exception("no gltf in archive");
            }
            var jsonBytes = zipArchive.Extract(gltf);
            var json      = Encoding.UTF8.GetString(jsonBytes);
            context.ParseJson(json, zipArchive);
        }
        break;

        case ".glb":
            context.ParseGlb(bytes);
            break;

        default:
            throw new NotImplementedException();
        }

        gltfImporter.Load(context);
        context.Root.name = Path.GetFileNameWithoutExtension(path);
        context.ShowMeshes();

        return(context.Root);
    }
Пример #8
0
        public override ImageData Import(FileStream stream, ImporterContext ctx)
        {
            // Ensure it is a supported image type
            switch (ctx.FileExtension)
            {
            case ".png":
            case ".jpg":
            case ".jpeg":
            case ".bmp":
            case ".tga": break;

            default:
                ctx.Logger.Error($"unsupported image file format '{ctx.FileExtension.Substring(1)}'.");
                return(null);
            }

            // Load as a 4-channel rgba
            return(NativeImage.Load(ctx.FilePath));
        }
Пример #9
0
        private IEnumerator Load(string path)
        {
            Debug.LogFormat("load: {0}", path);

            if (m_loaded != null)
            {
                m_loaded.Dispose();
            }

            var loader = new VCIImporter();

            loader.Parse(path);
            yield return(loader.LoadCoroutine());

            yield return(loader.SetupCoroutine());

            loader.ShowMeshes();

            m_loaded = loader;
        }
        /// <summary>
        /// Adds a new content file to the MSBuild project. The importer and
        /// processor are optional: if you leave the importer null, it will
        /// be autodetected based on the file extension, and if you leave the
        /// processor null, data will be passed through without any processing.
        /// </summary>
        public void Add(string filename, string name, string importerString, string processor)
        {
            var fileExtension = Path.GetExtension(filename) ?? "";

            var isContentBuildItem = !_secondaryImporters.ContainsKey(fileExtension);
            var importer           = _importers.FindByName(fileExtension.ToLower());

            if (isContentBuildItem)
            {
                importerString = importer.Value;
                processor      = importer.Other;

                ProjectItem item = _buildProject.AddItem("Compile", filename)[0];

                item.SetMetadataValue("Link", Path.GetFileName(filename));
                item.SetMetadataValue("Name", name);

                if (!string.IsNullOrEmpty(importerString))
                {
                    item.SetMetadataValue("Importer", importerString);
                }

                if (!string.IsNullOrEmpty(processor))
                {
                    item.SetMetadataValue("Processor", processor);
                }

                _projectItems.Add(item);
            }
            else
            {
                var secondaryImporter = _secondaryImporters[fileExtension];
                var fileTuple         = new ImporterContext
                {
                    AssetName            = name + fileExtension,
                    TargetDirectory      = BuildArtifactsDirectory,
                    SourceAssetDirectory = filename.Replace(name + fileExtension, "")
                };
                secondaryImporter.Item2.Add(fileTuple);
            }
        }
        public static void Import(byte[] document, UserAssetPreviewModel preview)
        {
            using (Transaction tr = new Transaction())
            {
                var doc = new MemoryStream(document).Using(XDocument.Load);

                ImporterContext importer = new ImporterContext(doc,
                                                               preview.Lines
                                                               .Where(a => a.Action == EntityAction.Different)
                                                               .ToDictionary(a => a.Guid, a => a.OverrideEntity));

                foreach (var item in importer.elements)
                {
                    importer.GetEntity(item.Key);
                }

                Database.DeleteList(importer.toRemove);

                tr.Commit();
            }
        }
Пример #12
0
    void GLB(string path)
    {
        var bytes   = File.ReadAllBytes(path);
        var context = new ImporterContext();

        context.ParseGlb(bytes);
        context.LoadAsync(() =>
        {
            context.ShowMeshes();

            var markerM      = Instantiate(MarkerM).transform;
            markerM.name     = "GLB_Root";
            markerM.position = new Vector3(0, -1, 0);
            markerM.gameObject.AddComponent <SaveSceneTarget>().Path = path;
            context.Root.transform.parent = markerM;

            LoadCount++;
        });

        DandD.SetActive(false);
    }
Пример #13
0
        public override RawAudio Import(FileStream stream, ImporterContext ctx)
        {
            // Select loader based on the extension
            RawAudio ra = null;

            switch (ctx.FileExtension)
            {
            case ".wav": ra = NativeAudio.LoadWave(ctx.FilePath); break;

            case ".flac": ra = NativeAudio.LoadFlac(ctx.FilePath); break;

            case ".ogg": ra = NativeAudio.LoadVorbis(ctx.FilePath); break;

            case ".mp3": ra = NativeAudio.LoadMp3(ctx.FilePath); break;

            default:
                ctx.Logger.Error($"unsupported audio file format '{ctx.FileExtension.Substring(1)}'.");
                return(null);
            }

            // Good to move forward
            return(ra);
        }
    IEnumerator GetObjects()
    {
        yield return(new WaitForSeconds(3));

        Debug.Log("Objects request");

        //If not empty, update the ARObject list and remove the old objects
        RemoveOldObjects();

        //For each objects
        foreach (ObjectInfo inf in objectsInfos_Near)
        {
            //We check first if the object already is spawned
            if (!objectsInfos_Near_Old.Contains(inf))
            {
                Debug.Log("NOT SPAWNDED");
                string filepath = filepath_objects + inf.name;
                //We check first if the objects already exists on the phone
                if (File.Exists(filepath))
                {
                    Mapbox.Unity.Utilities.Console.Instance.Log("File exists", "yellow");
                }
                else
                {
                    //Get the data from the server
                    UnityWebRequest request = UnityWebRequest.Get(URL_getObjects + "/" + inf.name);
                    //Set a twelve seconds timeout in case an error isn't returned
                    request.timeout = 12;
                    Mapbox.Unity.Utilities.Console.Instance.Log("URL : " + URL_getObjects + "/" + inf.name, "cyan");
                    yield return(request.SendWebRequest());

                    if (request.isNetworkError || request.isHttpError)
                    {
                        Mapbox.Unity.Utilities.Console.Instance.Log(request.error, "yellow");
                    }
                    else
                    {
                        Mapbox.Unity.Utilities.Console.Instance.Log("data size :" + request.downloadHandler.data.Length, "yellow");
                        //Write object as local file
                        try
                        {
                            File.WriteAllBytes(filepath, request.downloadHandler.data);
                            Mapbox.Unity.Utilities.Console.Instance.Log("File writed", "yellow");
                        }
                        catch (Exception e)
                        {
                            Mapbox.Unity.Utilities.Console.Instance.Log(e.Message, "red");
                        }
                    }
                }
                //Load the glb file as a gameobject
                ImporterContext context = gltfImporter.Load(filepath);
                context.ShowMeshes();

                //ADD ROTATE
                cnt++;
                if (cnt == 4 || cnt == 8 || cnt == 3 || cnt == 7)
                {
                    context.Root.AddComponent <RotateObject>();
                }
                //Add it to the AR objects array
                ARObjects.Add(context.Root);
            }
        }
        //Requests are finshed and objects loaded
        areRequestsFinished = true;
        Mapbox.Unity.Utilities.Console.Instance.Log("Finished reqs", "cyan");
    }
Пример #15
0
        public async IAsyncEnumerable <TestCase> Load(IEnumerable <string> resolvedSpecifications, ImporterContext context)
        {
            if (context.Include.Filter is not null)
            {
                throw new Exception("The AviaNZ importer does not currently support include filters");
            }

            foreach (var path in resolvedSpecifications)
            {
                logger.LogTrace("Loading AviaNZ data file: {file}", path);
                // we expext the test file to exist alongside the file
                // trim the ".data"  extension
                var testFile = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path));
                if (!File.Exists(testFile))
                {
                    throw new FileNotFoundException($"Expected source audio file to be next to AviaNZ training data file but it was not found.", testFile);
                }

                var dataFile = await avianzDeserializer.DeserializeLabelFile(path);

                Arr <IExpectation> expectations = dataFile.Annotations switch
                {
                    { Count : 0 } => Array(MakeNoEventsExpectation(path)),
Пример #16
0
        /// <inheritdoc />
        public override async Task <FontFile?> ImportAsync(Stream stream,
                                                           ImporterContext context,
                                                           CancellationToken cancellationToken)
        {
            return(await Task.Run(
                       () =>
            {
                FontDescription?description = Json.Deserialize <FontDescription>(stream);

                if (description == null)
                {
                    context.AddMessage("Importing item failed! Expected type {0}!", typeof(FontDescription));
                    return null;
                }

                FontStyle fs = FontStyle.Regular;
                if (description.IsBold)
                {
                    fs |= FontStyle.Bold;
                }
                if (description.IsItalic)
                {
                    fs |= FontStyle.Italic;
                }

                using (Font fnt = new Font(description.Name, description.Size, fs))
                {
                    if (string.Compare(
                            fnt.Name, description.Name,
                            StringComparison.InvariantCultureIgnoreCase) != 0)
                    {
                        context.AddMessage(
                            "Can't import the font '{0:OrangeRed}'! " +
                            "The font doesn't exists on the current system!", description);
                        return null;
                    }
                }

                string tempFileNameLocation =
                    Path.Combine(TEMP_FILE_DIR, $"{description.Size}_{Path.GetRandomFileName()}.fnt");

                string configLocation =
                    Path.Combine("tools", $"config{Thread.CurrentThread.ManagedThreadId}.bmfc");

                int textureWidth =
                    Math2.RoundUpToPowerOfTwo(
                        (int)Math.Sqrt(GetCharCount(description.Chars) * description.Size));

                while (textureWidth <= Resource.MaximumTexture2DSize)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return null;
                    }
                    File.WriteAllText(
                        configLocation,
                        CreateConfig(description, textureWidth, textureWidth));

                    using (Process p = Process.Start(
                               new ProcessStartInfo(
                                   _bmFontExeLocation,
                                   $"-c {configLocation} -o {tempFileNameLocation}")
                    {
                        UseShellExecute = false, CreateNoWindow = false
                    }))
                    {
                        if (!p.HasExited)
                        {
                            int i = 0;
                            while (!p.WaitForExit(1_000) &&
                                   !cancellationToken.IsCancellationRequested &&
                                   i++ < 45)
                            {
                            }
                            if (!p.HasExited)
                            {
                                try
                                {
                                    p.Kill();
                                }
                                catch
                                {
                                    /* IGNORE*/
                                }
                            }
                        }

                        if (p.ExitCode == 0)
                        {
                            FontFile fontFile = FontLoader.Load(tempFileNameLocation);
                            if (fontFile.Common !.Pages == 1)
                            {
                                if (CheckFontImageFiles(fontFile, TEMP_FILE_DIR))
                                {
                                    fontFile.Pages ![0].File =
                                        Path.GetFullPath(Path.Combine(TEMP_FILE_DIR, fontFile.Pages[0].File));
                                    return fontFile;
                                }
Пример #17
0
 /// <summary>
 /// Create a new instance of VgoShaderStore.
 /// </summary>
 /// <param name="_"></param>
 public VgoShaderStore(ImporterContext _) : base(_)
 {
 }
Пример #18
0
        private void RuntimeImport(ImporterContext context)
        {
            var animationClips = new AnimationClip[context.GLTF.animations.Count];

            // node extension animation
            for (int i = 0; i < context.GLTF.nodes.Count; i++)
            {
                var node = context.GLTF.nodes[i];
                if (node.extensions == null || node.extensions.VCAST_vci_animation == null)
                {
                    continue;
                }

                var vciAnimation = node.extensions.VCAST_vci_animation;
                var root         = context.Nodes[i];
                var animation    = root.gameObject.AddComponent <Animation>();

                foreach (var animationReference in vciAnimation.animationReferences)
                {
                    var           gltfAnimation = context.GLTF.animations[animationReference.animation];
                    AnimationClip clip          = null;
                    if (animationClips[animationReference.animation] == null)
                    {
                        clip = AnimationImporterUtil.ImportAnimationClip(context, gltfAnimation, node);
                        animationClips[animationReference.animation] = clip;
                    }
                    else
                    {
                        clip = animationClips[animationReference.animation];
                    }

                    if (clip != null)
                    {
                        animation.AddClip(clip, clip.name);
                    }
                }
            }

            // root animation
            var rootAnimation = context.Root.GetComponent <Animation>();

            if (rootAnimation == null)
            {
                rootAnimation = context.Root.AddComponent <Animation>();
            }

            for (int i = 0; i < animationClips.Length; i++)
            {
                if (animationClips[i] != null)
                {
                    continue;
                }

                var gltfAnimation = context.GLTF.animations[i];

                animationClips[i] = AnimationImporterUtil.ImportAnimationClip(context, gltfAnimation);
                rootAnimation.AddClip(animationClips[i], animationClips[i].name);
            }

            context.AnimationClips = new List <AnimationClip>(animationClips);
        }
Пример #19
0
 async Task <object?> IImporter.ImportAsync(Stream stream,
                                            ImporterContext context,
                                            CancellationToken cancellationToken)
 {
     return(await ImportAsync(stream, context, cancellationToken));
 }
Пример #20
0
 public abstract Task <T?> ImportAsync(Stream stream,
                                       ImporterContext context,
                                       CancellationToken cancellationToken);
Пример #21
0
        // The function that runs on the thread
        private void _thread_func(bool rebuild)
        {
            Stopwatch      _timer  = new Stopwatch();
            PipelineLogger _logger = new PipelineLogger(Engine);

            Results.Reset();

            // Create the content stream
            var cStream = new ContentStream();

            // Iterate over the tasks
            while (!Manager.ShouldStop && Manager.GetTaskItem(out BuildEvent current))
            {
                // Report start
                Engine.Logger.ItemStart(current);
                _timer.Restart();
                _logger.UseEvent(current);
                Results.UseItem(current);

                // Check the source file exists
                if (current.InputTime == BuildEvent.ERROR_TIME)
                {
                    Engine.Logger.ItemFailed(current, "Could not find the source file for the item");
                    continue;
                }

                // Check for the requested importer and processor
                if (!_importers.ContainsKey(current.ImporterName))
                {
                    if (Engine.StageCache.Importers.ContainsKey(current.ImporterName))
                    {
                        _importers.Add(current.ImporterName, new ImporterInstance(Engine.StageCache.Importers[current.ImporterName]));
                    }
                    else
                    {
                        Engine.Logger.ItemFailed(current, "The item requested an importer type that does not exist");
                        continue;
                    }
                }
                if (!_processors.ContainsKey(current.ProcessorName))
                {
                    if (Engine.StageCache.Processors.ContainsKey(current.ProcessorName))
                    {
                        _processors.Add(current.ProcessorName, new ProcessorInstance(Engine.StageCache.Processors[current.ProcessorName]));
                    }
                    else
                    {
                        Engine.Logger.ItemFailed(current, "The item requested an processor type that does not exist");
                        continue;
                    }
                }
                var importer  = _importers[current.ImporterName];
                var processor = _processors[current.ProcessorName];

                // Validate stage compatibility
                if (!processor.Type.InputType.IsAssignableFrom(importer.Type.OutputType))
                {
                    Engine.Logger.ItemFailed(current, "The item specified incompatible stages");
                    continue;
                }

                // Compare the current and cached build events to see if we can skip the build
                //   If we are forcing a rebuild we have to build so we can skip the check
                bool compress =
                    (processor.Policy == CompressionPolicy.Always) ||
                    (processor.Policy == CompressionPolicy.ReleaseOnly && Engine.IsRelease) ||
                    (processor.Policy == CompressionPolicy.Default && Engine.Compress) ||
                    false;                     // policy is never, compress = false
                if (!rebuild)
                {
                    var cached = BuildEvent.FromCacheFile(Engine, current.Item);
                    if (!current.NeedsBuild(cached, processor, compress))
                    {
                        Engine.Logger.ItemSkipped(current);
                        Results.PassItem(cached.UCSize, true);
                        if (compress)
                        {
                            Results.UpdatePreviousItem(current.RealSize);                             // Update with the real (compressed) size of the data
                        }
                        continue;
                    }
                }

                // Early stop check
                if (Manager.ShouldStop)
                {
                    Engine.Logger.ItemFailed(current, "The build process was stopped while the item was being built");
                    break;
                }

                // Run the importer
                FileStream importStream = null;
                FileInfo   importInfo   = null;
                try
                {
                    importInfo   = new FileInfo(current.Paths.SourcePath);
                    importStream = importInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
                }
                catch (Exception e)
                {
                    Engine.Logger.ItemFailed(current, $"The item source file could not be opened, {e.Message}");
                    continue;
                }
                object importedData = null;
                try
                {
                    _logger.UpdateStageName(current.ImporterName);
                    ImporterContext ctx = new ImporterContext(this, _logger, importInfo);
                    importedData = importer.Instance.Import(importStream, ctx);
                    if (importedData == null)
                    {
                        Engine.Logger.ItemFailed(current, "The importer for the item did not produce any data");
                        continue;
                    }

                    // Save the dependencies to the event
                    if (ctx.Dependencies.Count > 0)
                    {
                        foreach (var ed in ctx.Dependencies)
                        {
                            current.ExternalDependencies.Add((ed, File.GetLastWriteTimeUtc(ed)));
                        }
                    }
                }
                catch (Exception e)
                {
                    int    pos = e.StackTrace.IndexOf(" at ");
                    string loc = e.StackTrace.Substring(pos + 4).Split('\n')[0];
                    Engine.Logger.ItemFailed(current, $"Unhandled exception in importer, {e.Message} ({e.GetType().Name})\n Source: {loc}");
                    if (e.InnerException != null)
                    {
                        Engine.Logger.ItemFailed(current, $"Inner Exception ({e.InnerException.GetType().Name}): {e.InnerException.Message}");
                    }
                    continue;
                }
                finally
                {
                    importStream.Dispose();
                }

                // Early stop check
                if (Manager.ShouldStop)
                {
                    Engine.Logger.ItemFailed(current, "The build process was stopped while the item was being built");
                    break;
                }

                // Run the processor
                Engine.Logger.ItemContinue(current, BuildLogger.ContinueStage.Processing);
                object processedData = null;
                try
                {
                    _logger.UpdateStageName(current.ProcessorName);
                    ProcessorContext ctx = new ProcessorContext(this, _logger, importInfo);
                    processor.UpdateFields(Engine, current);
                    processedData = processor.Instance.Process(importedData, ctx);
                    if (processedData == null)
                    {
                        Engine.Logger.ItemFailed(current, "The processor for the item did not produce any data");
                        continue;
                    }
                }
                catch (Exception e)
                {
                    int    pos = e.StackTrace.IndexOf(" at ");
                    string loc = e.StackTrace.Substring(pos + 4).Split('\n')[0];
                    Engine.Logger.ItemFailed(current, $"Unhandled exception in processor, {e.Message} ({e.GetType().Name})\n Source: {loc}");
                    if (e.InnerException != null)
                    {
                        Engine.Logger.ItemFailed(current, $"Inner Exception ({e.InnerException.GetType().Name}): {e.InnerException.Message}");
                    }
                    continue;
                }

                // Early stop check
                if (Manager.ShouldStop)
                {
                    Engine.Logger.ItemFailed(current, "The build process was stopped while the item was being built");
                    break;
                }

                // Delete the output and cache files
                try
                {
                    if (File.Exists(current.Paths.OutputPath))
                    {
                        File.Delete(current.Paths.OutputPath);
                    }
                    if (File.Exists(current.CachePath))
                    {
                        File.Delete(current.CachePath);
                    }
                }
                catch
                {
                    Engine.Logger.ItemFailed(current, "Could not delete the output file to rebuild the item");
                    continue;
                }

                // Run the writer
                Engine.Logger.ItemContinue(current, BuildLogger.ContinueStage.Writing);
                try
                {
                    _logger.UpdateStageName(processor.Type.WriterType.Name);
                    uint lastRealSize = cStream.Reset(current.Paths.OutputPath, compress);
                    if (lastRealSize != 0)
                    {
                        Results.UpdatePreviousItem(lastRealSize);
                    }
                    WriterContext ctx = new WriterContext(this, _logger, importInfo);
                    processor.WriterInstance.Write(processedData, cStream, ctx);
                    cStream.Flush();
                }
                catch (Exception e)
                {
                    int    pos = e.StackTrace.IndexOf(" at ");
                    string loc = e.StackTrace.Substring(pos + 4).Split('\n')[0];
                    Engine.Logger.ItemFailed(current, $"Unhandled exception in writer, {e.Message} ({e.GetType().Name})\n Source: {loc}");
                    if (e.InnerException != null)
                    {
                        Engine.Logger.ItemFailed(current, $"Inner Exception ({e.InnerException.GetType().Name}): {e.InnerException.Message}");
                    }
                    continue;
                }

                // Save the cache
                current.SaveCache(Engine, cStream.OutputSize, compress);

                // Report end
                Engine.Logger.ItemFinished(current, _timer.Elapsed);
                Results.PassItem(cStream.OutputSize, false);
            }

            // Wait for the final output to be complete
            uint realsize = cStream.Reset(null, false);

            if (realsize != 0)
            {
                Results.UpdatePreviousItem(realsize);
            }
            Results.UseItem(null);             // In the case that the last item fails
        }
Пример #22
0
 public VCIMaterialImporter(ImporterContext context, List <glTF_VCI_Material> materials, bool srgbToLinearColor) : base(
         new ShaderStore(context), (int index) => context.GetTexture(index))
 {
     m_materials         = materials;
     m_srgbToLinearColor = srgbToLinearColor;
 }
Пример #23
0
    public static void Import(ImporterContext context)
    {
        //
        // parse
        //
        // context.Source = File.ReadAllText(context.Path, Encoding.UTF8);
        context.Bvh = Bvh.Parse(context.Source);
        Debug.LogFormat("parsed {0}", context.Bvh);

        //
        // build hierarchy
        //
        context.Root = new GameObject(Path.GetFileNameWithoutExtension(context.Path));

        BuildHierarchy(context.Root.transform, context.Bvh.Root, 1.0f);

        var hips        = context.Root.transform.GetChild(0);
        var estimater   = new BvhSkeletonEstimator();
        var skeleton    = estimater.Detect(hips.transform);
        var description = AvatarDescription.Create();

        //var values= ((HumanBodyBones[])Enum.GetValues(typeof(HumanBodyBones)));
        description.SetHumanBones(skeleton.ToDictionary(hips.Traverse().ToArray()));

        //
        // scaling. reposition
        //
        float scaling = 1.0f;

        {
            //var foot = animator.GetBoneTransform(HumanBodyBones.LeftFoot);
            var foot      = hips.Traverse().Skip(skeleton.GetBoneIndex(HumanBodyBones.LeftFoot)).First();
            var hipHeight = hips.position.y - foot.position.y;
            // hips height to a meter
            scaling = 1.0f / hipHeight;
            foreach (var x in context.Root.transform.Traverse())
            {
                x.localPosition *= scaling;
            }

            var scaledHeight = hipHeight * scaling;
            hips.position = new Vector3(0, scaledHeight, 0); // foot to ground
        }

        //
        // avatar
        //
        context.Avatar            = description.CreateAvatar(context.Root.transform);
        context.Avatar.name       = "Avatar";
        context.AvatarDescription = description;
        var animator = context.Root.AddComponent <Animator>();

        animator.avatar = context.Avatar;

        //
        // create AnimationClip
        //
        context.Animation          = BvhAnimation.CreateAnimationClip(context.Bvh, scaling);
        context.Animation.name     = context.Root.name;
        context.Animation.legacy   = true;
        context.Animation.wrapMode = WrapMode.Loop;

        var animation = context.Root.AddComponent <Animation>();

        animation.AddClip(context.Animation, context.Animation.name);
        animation.clip = context.Animation;
        animation.Play();

        var humanPoseTransfer = context.Root.AddComponent <HumanPoseTransfer>();

        humanPoseTransfer.Avatar = context.Avatar;

        // create SkinnedMesh for bone visualize
        var renderer = SkeletonMeshUtility.CreateRenderer(animator);

        context.Material        = new Material(Shader.Find("Standard"));
        renderer.sharedMaterial = context.Material;
        context.Mesh            = renderer.sharedMesh;
        context.Mesh.name       = "box-man";

        context.Root.AddComponent <BoneMapping>();
    }
Пример #24
0
        public async IAsyncEnumerable <TestCase> Load(IEnumerable <string> resolvedSpecifications, ImporterContext context)
        {
            var scope = logger.BeginScope("Recursion: {recursionCounter}", Interlocked.Increment(ref recursionCounter));

            try
            {
                if (context.Include.SpectralTolerance is not null || context.Include.TemporalTolerance is not null)
                {
                    logger.LogWarning(
                        $"{nameof(TestCaseInclude.SpectralTolerance)} and {nameof(TestCaseInclude.TemporalTolerance)} are ignored when importing tests from another egret config file. You can put tolerances on the tests directly.");
                }

                foreach (var path in resolvedSpecifications)
                {
                    // warning: recursive
                    await foreach (var test in LoadExternalConfig(path, context))
                    {
                        yield return(test);
                    }
                }
            }
            finally
            {
                scope.Dispose();
                Interlocked.Decrement(ref recursionCounter);
            }
        }
 public void Import(ImporterContext context)
 {
     AnimationImporterUtil.ImportAnimation(context);
 }
Пример #26
0
 public VRMMaterialImporter(ImporterContext context, List <glTF_VRM_Material> materials) : base(new ShaderStore(context), (int index) => context.GetTexture(index))
 {
     m_materials = materials;
 }
Пример #27
0
        public IAsyncEnumerable <TestCase> Load(IEnumerable <string> resolvedSpecifications, ImporterContext context)
        {
            if (context.Include.SpectralTolerance is not null || context.Include.TemporalTolerance is not null)
            {
                logger.LogWarning(
                    $"{nameof(TestCaseInclude.SpectralTolerance)} and {nameof(TestCaseInclude.TemporalTolerance)} are ignored when importing tests from the `common_tests` section. You can put tolerances on the tests directly.");
            }

            // note to future me: there's no point outputting console context here
            // because the globs aren't expanded yet

            return(Sync().ToAsyncEnumerable());

            IEnumerable <TestCase> Sync()
            {
                var matcher = context.Include.FilterMatcher;

                foreach (var key in resolvedSpecifications)
                {
                    if (!matcher.Match(key).HasMatches)
                    {
                        logger.LogDebug("Filtered out common tests for {key}", key);
                        continue;
                    }

                    var result = context.Config.CommonTests[key];
                    foreach (var test in result)
                    {
                        yield return(test);
                    }

                    logger.LogDebug("Loaded common tests for {key}", key);
                }
            }
        }
Пример #28
0
 /// <summary>
 /// Create a new instance of VgoMaterialImporter with ImporterContext.
 /// </summary>
 /// <param name="context"></param>
 public VgoMaterialImporter(ImporterContext context) : base(new VgoShaderStore(context), context)
 {
 }
Пример #29
0
        static void Main(string[] args)
        {
            Log("Effect farm compiler to efb {0}.", EFParser.EfbVersion);

            if (args.Length < 2)
            {
                Log("Usage: efc <input_file> <config_file> [output_file]");
                return;
            }

            try
            {
                var inputFile = args[0];
                if (!File.Exists(inputFile))
                {
                    Log("Could not find '0'.", inputFile);
                    return;
                }

                var configFile = args[1];
                if (!File.Exists(inputFile))
                {
                    Log("Could not find '0'.", inputFile);
                    return;
                }
                var doc = XDocument.Parse(File.ReadAllText(configFile));

                // Parse config
                var config = new Config
                {
                    Targets = ParseTargets(doc)
                };
                if (config.Targets.Length == 0)
                {
                    GenerateError("No target platforms.");
                }

                var rootEntry = (from n in doc.Descendants("RootEntry") select n).FirstOrDefault();
                if (rootEntry == null)
                {
                    GenerateError("Could not find 'RootEntry' node.");
                }

                config.Root = ParseEntry(rootEntry);

                var variants = config.BuildVariants().ToArray();

                var outputFile = string.Empty;

                if (args.Length < 3)
                {
                    outputFile = Path.ChangeExtension(inputFile, "efb");
                }
                else
                {
                    outputFile = Path.ChangeExtension(args[2], "efb");
                }

                var outputLwt = File.GetLastWriteTime(outputFile);
                if (File.Exists(outputFile) &&
                    outputLwt > File.GetLastWriteTime(inputFile) &&
                    outputLwt > File.GetLastWriteTime(configFile))
                {
                    var resultVariants = Substract(variants, outputFile);
                    if (resultVariants.Length == 0)
                    {
                        Log("{0} is up to date.", Path.GetFileName(outputFile));
                        return;
                    }
                }

                var workingFolder = Path.GetDirectoryName(inputFile);
                var includeFx     = new IncludeFX(workingFolder);

                var importerContext  = new ImporterContext();
                var processorContext = new ProcessorContext();

                var effectImporter = new EffectImporter();
                var effectProcesor = new EffectProcessor();

                Log("{0} variants of effects are going to be compiled.", variants.Length);
                using (var stream = File.Open(outputFile, FileMode.Create))
                    using (var writer = new BinaryWriter(stream))
                    {
                        writer.Write(Encoding.UTF8.GetBytes(EFParser.EfbSignature));
                        writer.Write(EFParser.EfbVersion);

                        var idx = 0;
                        foreach (var variant in variants)
                        {
                            Log("#" + idx + ": " + variant.ToString());

                            switch (variant.Platform)
                            {
                            case EFPlatform.MonoGameDirectX:
                            case EFPlatform.MonoGameOpenGL:
                            {
                                var content = effectImporter.Import(inputFile, importerContext);

                                processorContext._targetPlatform = variant.Platform == EFPlatform.MonoGameDirectX ?
                                                                   TargetPlatform.Windows : TargetPlatform.DesktopGL;
                                effectProcesor.Defines = EFVariant.BuildKey(variant.Defines);

                                var result = effectProcesor.Process(content, processorContext);

                                WriteOutput(writer, variant, result.GetEffectCode());
                            }
                            break;

                            case EFPlatform.FNA:
                            {
                                var result = ShaderBytecode.CompileFromFile(inputFile,
                                                                            "fx_2_0",
                                                                            ShaderFlags.OptimizationLevel3,
                                                                            EffectFlags.None,
                                                                            ToMacroses(variant),
                                                                            includeFx);

                                if (result.ResultCode != Result.Ok)
                                {
                                    GenerateError(result.Message);
                                }

                                WriteOutput(writer, variant, result.Bytecode);
                            }
                            break;
                            }

                            ++idx;
                        }
                    }

                Log("Compilation to {0} was succesful.", Path.GetFileName(outputFile));
            }
            catch (Exception ex)
            {
                Log(ex.ToString());
            }
        }
Пример #30
0
 public VRMMaterialImporter(ImporterContext context, List <glTF_VRM_Material> materials) : base(new ShaderStore(context), context)
 {
     m_materials = materials;
 }
        /// <summary>
        /// Adds a new content file to the MSBuild project. The importer and
        /// processor are optional: if you leave the importer null, it will
        /// be autodetected based on the file extension, and if you leave the
        /// processor null, data will be passed through without any processing.
        /// </summary>
        public void Add(string filename, string name, string importerString, string processor)
        {
            var fileExtension = Path.GetExtension(filename) ?? "";

            var isContentBuildItem = !_secondaryImporters.ContainsKey(fileExtension);
            var importer = _importers.FindByName(fileExtension.ToLower());

            if (isContentBuildItem)
            {
                importerString = importer.Value;
                processor = importer.Other;

                ProjectItem item = _buildProject.AddItem("Compile", filename)[0];

                item.SetMetadataValue("Link", Path.GetFileName(filename));
                item.SetMetadataValue("Name", name);

                if (!string.IsNullOrEmpty(importerString))
                    item.SetMetadataValue("Importer", importerString);

                if (!string.IsNullOrEmpty(processor))
                    item.SetMetadataValue("Processor", processor);

                _projectItems.Add(item);
            }
            else
            {
                var secondaryImporter = _secondaryImporters[fileExtension];
                var fileTuple = new ImporterContext
                {
                    AssetName = name + fileExtension,
                    TargetDirectory = BuildArtifactsDirectory,
                    SourceAssetDirectory = filename.Replace(name + fileExtension, "")
                };
                secondaryImporter.Item2.Add(fileTuple);
            }
        }