コード例 #1
0
ファイル: BuildDriver.cs プロジェクト: mohammedmanssour/uno
        public BuildDriver(Log log, BuildTarget target, BuildOptions options, Project project, UnoConfig config)
            : base(log)
        {
            _target           = target;
            _options          = options;
            _project          = project;
            _config           = config;
            Log.MaxErrorCount = options.MaxErrorCount;
            Log.WarningLevel  = options.WarningLevel;

            Log.Reset();
            if (target.IsObsolete)
            {
                Log.Warning("The build target " + target.Quote() + " is obsolete and might not work any more.");
            }

            _anim = Log.StartAnimation("Configuring");
            PrintRow("Project file", project.FullPath);

            _compilerOptions = new CompilerOptions {
                BuildTarget     = _target.Identifier,
                Configuration   = _options.Configuration.ToString(),
                OutputDirectory = !string.IsNullOrEmpty(_options.OutputDirectory)
                    ? Path.GetFullPath(_options.OutputDirectory)
                    : project.OutputDirectory,
                MainClass  = _options.MainClass,
                Debug      = _options.Configuration != BuildConfiguration.Release,
                Parallel   = _options.Parallel,
                Strip      = _options.Strip ?? _target.DefaultStrip,
                CanCacheIL = _options.PackageCache != null
            };

            if (_options.Test)
            {
                _options.Defines.Add("UNO_TEST");
                _compilerOptions.TestOptions = new TestOptions {
                    TestServerUrl = _options.TestServerUrl,
                    Filter        = _options.TestFilter
                };
            }

            _cache = _options.PackageCache ?? new PackageCache(Log, _config);
            PrintRow("Search paths", _cache.SearchPaths);

            _compiler = new Compiler(
                Log,
                _target.CreateBackend(config),
                GetPackage(),
                _compilerOptions);
            _env     = _compiler.Environment;
            _backend = _compiler.Backend;
            _input   = _compiler.Input;

            if (_options.Clean)
            {
                _compiler.Disk.DeleteDirectory(_env.OutputDirectory);
            }

            _file = new BuildFile(_env.OutputDirectory);
        }
コード例 #2
0
        public IEnumerable <IPackage> FindPackages(IReadOnlyList <string> names, string version = null)
        {
            var cache        = new PackageCache();
            var list         = new List <LocalPackage>();
            var namesUpper   = new HashSet <string>(names.Select(x => x.ToUpperInvariant()));
            var versionUpper = string.IsNullOrEmpty(version) ? null : version.ToUpperInvariant();

            foreach (var directory in cache.SearchPaths)
            {
                foreach (var package in cache.GetPackageDirectories(directory).Keys)
                {
                    if (namesUpper.Count == 0 || namesUpper.Contains(package.ToUpperInvariant()))
                    {
                        foreach (var versionDir in cache.GetVersionDirectories(package))
                        {
                            if ((versionUpper == null || versionUpper == versionDir.Name.ToUpperInvariant()) &&
                                PackageFile.Exists(versionDir.FullName))
                            {
                                list.Add(new LocalPackage(package, versionDir.Name, versionDir.FullName));
                            }
                        }
                    }
                }
            }
            list.Sort();
            return(list);
        }
コード例 #3
0
ファイル: TestBase.cs プロジェクト: yongaru/fuse-studio
        protected void TestPerformance(string code, [CallerMemberName] string testName = "")
        {
            ConfigureProjectReferences();

            //get calling method info
            StackTrace stackTrace    = new StackTrace();
            var        callingMethod = stackTrace.GetFrame(1).GetMethod();
            var        testAttribute = (PerformanceTestAttribute)callingMethod.GetCustomAttributes(typeof(PerformanceTestAttribute), true)[0];

            var caret    = GetCaret(ref code);
            var filePath = AbsoluteDirectoryPath.Parse(Directory.GetCurrentDirectory()) / new FileName(testName);

            var log         = new DummyLogger();
            var context     = Context.CreateContext(filePath, code, caret, new DummySourcePackage());
            var mainPackage = PackageCache.GetPackage(new Log(log.TextWriter), _project);

            mainPackage.SetCacheDirectory((AbsoluteDirectoryPath.Parse(mainPackage.CacheDirectory) / new DirectoryName("UxCompletion")).NativePath);

            var build = new CodeNinjaBuild(log, _project, _editors, mainPackage, mainPackage.References.ToList(), code, filePath);

            build.Execute();

            Stopwatch sw = new Stopwatch();

            sw.Start();
            SuggestionParser.GetSuggestions(build.Compiler, context, caret, new DummyReader());
            sw.Stop();

            if (_context == null)
            {
                throw new ArgumentNullException("_context");
            }

            _context.Logger.LogTimeEvent(testName, testAttribute.Description, sw.ElapsedMilliseconds / 1000f);
        }
コード例 #4
0
        public override void Load()
        {
            if (File.Exists(journalPath))
            {
                var json = fileSystem.ReadFile(journalPath);

                if (TryDeserializeJournal(json, out var journalContents))
                {
                    journalEntries = journalContents
                                     ?.JournalEntries
                                     ?.ToDictionary(entry => entry.Package, entry => entry)
                                     ?? new Dictionary <PackageIdentity, JournalEntry>();
                    Cache = journalContents?.Cache ?? new PackageCache(0);
                }
                else
                {
                    var journalFileName       = Path.GetFileNameWithoutExtension(journalPath);
                    var backupJournalFileName = $"{journalFileName}_{DateTimeOffset.UtcNow:yyyyMMddTHHmmss}.json"; // eg. PackageRetentionJournal_20210101T120000.json

                    log.Warn($"The existing package retention journal file {journalPath} could not be read. The file will be renamed to {backupJournalFileName}. A new journal will be created.");

                    // NET Framework 4.0 doesn't have File.Move(source, dest, overwrite) so we use Copy and Delete to replicate this
                    File.Copy(journalPath, Path.Combine(Path.GetDirectoryName(journalPath), backupJournalFileName), true);
                    File.Delete(journalPath);

                    journalEntries = new Dictionary <PackageIdentity, JournalEntry>();
                    Cache          = new PackageCache(0);
                }
            }
            else
            {
                journalEntries = new Dictionary <PackageIdentity, JournalEntry>();
                Cache          = new PackageCache(0);
            }
        }
コード例 #5
0
ファイル: TestBase.cs プロジェクト: yongaru/fuse-studio
        public void AssertUX(string code, [CallerMemberName] string path = "")
        {
            int caret = 0;
            var assertCodeSnippets = GetAsserts(ref code, ref caret);
            var filePath           = AbsoluteDirectoryPath.Parse(Directory.GetCurrentDirectory()) / new FileName(path);

            var log         = new DummyLogger();
            var context     = Context.CreateContext(filePath, code, caret, new DummySourcePackage());
            var mainPackage = PackageCache.GetPackage(new Log(log.TextWriter), _project);

            mainPackage.SetCacheDirectory((AbsoluteDirectoryPath.Parse(mainPackage.CacheDirectory) / new DirectoryName("UxCompletion")).NativePath);

            var build = new CodeNinjaBuild(log, _project, _editors, mainPackage, mainPackage.References.ToList(), code, filePath);

            build.Execute();

            var suggestions = SuggestionParser.GetSuggestions(build.Compiler, context, caret, new DummyReader());

            if (assertCodeSnippets != null)
            {
                foreach (var codeSnippet in assertCodeSnippets)
                {
                    OnAssert(code, codeSnippet, suggestions, log);
                }
            }
        }
コード例 #6
0
 public SavePackageCacheTask(PackageCache packageCache)
 {
     TaskName        = "Saving package cache...";
     TaskDescription = Path.Combine(App.EXECUTABLE_DIRECTORY, "packages", "package.cache");
     ActionName      = "Save package cache";
     PackageCache    = packageCache;
     IsIndeterminate = true;
 }
コード例 #7
0
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        foreach (UploadItem i in ConflictUploadItems)
        {
            // Delete the new package from disk since the user has decided not to go through with overwriting the old package.
            PackageCache.DeleteTemplatePackage(i.PackageID);

            CanceledUploadItems.Add(i);                 // Add the item to the list of canceled items.
        }

        ConflictUploadItems.Clear();         // Remove all conflict items.
        UpdatePanelVisibility();
    }
コード例 #8
0
        public BipsDrive(PSDriveInfo driveInfo) : base(driveInfo)
        {
            _driveRoot = driveInfo.Root;
            _helper    = new SsisDbHelper(_driveRoot);
            _cache     = new PackageCache(this);

            if (File.Exists(_driveRoot) || Directory.Exists(_driveRoot))
            {
                return;
            }

            _proxy = new ServerPackageProxy(_driveRoot);
            _proxy.Clear();
        }
コード例 #9
0
        private LocalNuGetPackageCacheItem LookupCachedItem(SharePointConnection sharePointConnection)
        {
            if (sharePointConnection == null)
            {
                return(null);
            }

            if (!PackageCache.ContainsKey(sharePointConnection))
            {
                PackageCache.Add(sharePointConnection, new LocalNuGetPackageCacheItem());
            }

            return(PackageCache[sharePointConnection]);
        }
コード例 #10
0
        /// <summary>
        /// Gives the Package containing both the IPackage and the derived metadata.
        /// The returned Package will be null if <paramref name="package" /> no longer exists in the cache.
        /// </summary>
        public Package GetMetadataPackage(IPackage package)
        {
            Package metadata = null;

            // The cache may have changed, and the metadata may no longer exist
            DerivedPackageData data = null;

            if (PackageCache.TryGetValue(package, out data))
            {
                metadata = new Package(package, data);
            }

            return(metadata);
        }
コード例 #11
0
        public PackageCache Insert(PackageCache packageCache)
        {
            try
            {
                _context.PackageCaches.Add(packageCache);
                Save();

                return(packageCache);
            }
            catch (Exception ex)
            {
                _log.Error("Insert(): Unable to add new package cache", ex);

                return(null);
            }
        }
コード例 #12
0
ファイル: Engine.cs プロジェクト: yongaru/fuse-studio
        bool ChangeProject(string projectPath)
        {
            _currentProject = Project.Load(projectPath);

            new Shell()
            .Watch(AbsoluteFilePath.Parse(projectPath).ContainingDirectory, "*.unoproj")
            .Where(e => e.Event == FileSystemEvent.Changed || e.Event == FileSystemEvent.Removed)
            .Subscribe(f => _currentProject = null);

            MainPackage = PackageCache.GetPackage(Log.Default, _currentProject);
            MainPackage.SetCacheDirectory((AbsoluteDirectoryPath.Parse(MainPackage.CacheDirectory) / new DirectoryName("CodeCompletion")).NativePath);

            TriggerBuild();

            return(true);
        }
コード例 #13
0
        private void Run()
        {
            string path = Path.Combine(App.EXECUTABLE_DIRECTORY, "packages", "package.cache");

            if (File.Exists(path))
            {
                try
                {
                    PackageCache     = JsonConvert.DeserializeObject <PackageCache>(File.ReadAllText(path));
                    App.PackageCache = PackageCache;
                }
                catch (Exception ex)
                {
                    Dialog.CancelAllTasks($"An error occured while tring to read the package cache file:\n{ex.Message}");
                }
            }
        }
コード例 #14
0
        public Boolean DeletePackageCache(String packageCacheId, String packageCacheLocation)
        {
            PackageCache packageCache = _packageCacheDataAccess.Get(packageCacheId);

            if (packageCache != null)
            {
                String projectPackageCacheLocation = packageCacheLocation.TrimEnd(new char[] { '\\' }) + "\\" + packageCache.Project.ID + "\\" + packageCache.Name;

                if (Directory.Exists(projectPackageCacheLocation))
                {
                    IOHelper.DeleteDirectory(projectPackageCacheLocation);
                }

                return(_packageCacheDataAccess.Delete(packageCacheId));
            }
            return(false);
        }
コード例 #15
0
    protected void tplGrid_SelectedIndexChanged(object sender, EventArgs e)
    {
        _packageID           = tplGrid.SelectedItem.Cells[5].Text;
        Session["PackageID"] = _packageID;

        if (string.IsNullOrEmpty(_packageID) || _packageID.IndexOfAny(new char[] { '/', '\\', ':' }) >= 0)         //Don't allow path control elements in a package ID.
        {
            MessageBox.Show("Invalid template path");
            return;
        }

        if (!PackageCache.PackageExists(_packageID))
        {
            MessageBox.Show("The selected template could not be found. Please contact your Sample Portal site administrator for assistance.");
            return;
        }
        SwitchMode(EmbeddedPageMode.SelectAnswers);
    }
コード例 #16
0
        public static PartConstraintCollection Create <T>(PackageCache cache, Type type)
            where T : IConstraintAttribute
        {
            var collection = new PartConstraintCollection();

            foreach (var constraint in type.GetTypeInfo().GetCustomAttributes(inherit: false).OfType <T>())
            {
                collection.Add(new PartConstraintRule(cache.GetElementTypeInfo(constraint.ConstraintType), constraint.MinOccursIsNonZero, constraint.MaxOccursGreatThanOne));
            }

            if (collection.Count == 0)
            {
                return(Instance);
            }

            collection._writeable = false;

            return(collection);
        }
コード例 #17
0
        /// <summary>
        /// Updates 'index.xml' the new title, description, and packageID passed in.
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="title"></param>
        /// <param name="desc"></param>
        /// <param name="packageID"></param>
        public void UpdateTemplate(string filename, string title, string desc, string packageID)
        {
            DataView dv    = null;
            FileInfo finfo = new FileInfo(filename);

            switch (finfo.Extension.ToLower())
            {
            case ".url":
                dv = SelectTitle(title, finfo.Extension);
                break;

            default:
                dv = SelectFile(filename);
                break;
            }
            string curPkgID = dv[0]["PackageID"].ToString();

            if (packageID != null)
            {
                if (curPkgID != packageID)
                {
                    // If the packageID is different than the old one, delete the old package from disk.
                    PackageCache.DeleteTemplatePackage(curPkgID);
                }

                dv[0]["PackageID"] = packageID;
            }
            // pass null if you don't want something changed
            if (filename != null)
            {
                dv[0]["Filename"] = filename;
            }
            if (title != null)
            {
                dv[0]["Title"] = title;
            }
            if (desc != null)
            {
                dv[0]["Description"] = desc;
            }
            FlushUpdates();
        }
コード例 #18
0
ファイル: Test.cs プロジェクト: yongaru/fuse-studio
        protected void AssertCode(string code, [CallerMemberName] string path = "")
        {
            int caret = 0;
            var assertCodeSnippets = GetAsserts(ref code, ref caret);

            var ubProject = _project;

            var filePath = AbsoluteDirectoryPath.Parse(Directory.GetCurrentDirectory()) / new FileName(path);

            _log = new DummyLogger();
            var editors     = new DummyEditorManager();
            var mainPackage = new PackageCache(new Log(_log.TextWriter), ubProject.Config).GetPackage(ubProject);

            mainPackage.SetCacheDirectory((AbsoluteDirectoryPath.Parse(mainPackage.CacheDirectory) / new DirectoryName("CodeCompletion")).NativePath);
            var build = new CodeNinjaBuild(_log, ubProject, editors, mainPackage, mainPackage.References.ToList(), code, filePath);

            build.Execute();

            var engine        = new DummyEngine(build.Compiler);
            var codeCompleter = new CodeCompleter(engine.Compiler,
                                                  new Source(build.ProjectPackage, filePath.NativePath),
                                                  new CodeReader(code, caret),
                                                  caret,
                                                  Parser.Parse(code));

            if (codeCompleter.Context.NodePath.Count < 1)
            {
                throw new TestException("Invalid node path was generated for the test case");
            }

            ConfidenceLevel confidenceLevel;
            var             suggestions = codeCompleter.SuggestCompletion("", out confidenceLevel);

            if (assertCodeSnippets != null)
            {
                foreach (var codeSnippet in assertCodeSnippets)
                {
                    OnAssert(code, codeSnippet, suggestions);
                }
            }
        }
コード例 #19
0
        public Boolean Update(String packageCacheId, String version)
        {
            PackageCache packageCache = null;

            try
            {
                packageCache = _context.PackageCaches.SingleOrDefault(i => i.ExternalId == packageCacheId);
            }
            catch (Exception ex)
            {
                _log.Error("Update(" + packageCacheId + "): Unable to get package cache", ex);

                return(false);
            }

            if (packageCache != null)
            {
                packageCache.Version = version;

                try
                {
                    Save();

                    return(true);
                }
                catch (Exception ex)
                {
                    _log.Error("Update(" + packageCacheId + "): Unable to save package cache", ex);

                    return(false);
                }
            }
            else
            {
                _log.Error("Update(" + packageCacheId + "): Unable to get find package cache");

                return(false);
            }
        }
コード例 #20
0
        public Boolean Delete(String packageCacheId)
        {
            PackageCache packageCache = null;

            try
            {
                packageCache = _context.PackageCaches.SingleOrDefault(i => i.ExternalId == packageCacheId);
            }
            catch (Exception ex)
            {
                _log.Error("Delete(" + packageCacheId + "): Unable to get package cache", ex);

                return(false);
            }

            if (packageCache != null)
            {
                _context.PackageCaches.Remove(packageCache);

                try
                {
                    Save();

                    return(true);
                }
                catch (Exception ex)
                {
                    _log.Error("Delete(): An error occured deleting the package cache", ex);

                    return(false);
                }
            }
            else
            {
                _log.Info("Unable to find package cache");

                return(false);
            }
        }
コード例 #21
0
        public FuseJS(PackageCache packages)
            : base(packages.Log)
        {
            var upk    = packages.GetPackage("FuseJS.Transpiler");
            var script = Path.Combine(upk.SourceDirectory, "server.min.js");

            _task = new Shell(packages.Log).Start(
                "node",
                script.QuoteSpace(),
                outputReceived: (sender, args) => {
                string port;
                if (TryMatchPort(args.Data, out port))
                {
                    _url = "http://127.0.0.1:" + port;
                }

                _output.AppendLine(args.Data);
            },
                errorReceived: (sender, args) => {
                _output.AppendLine(args.Data);
            });
        }
コード例 #22
0
    protected void tplGrid_SelectedIndexChanged(object sender, EventArgs e)
    {
        string packageId = tplGrid.SelectedItem.Cells[5].Text;

        if (string.IsNullOrEmpty(packageId) || packageId.IndexOfAny(new char[] { '/', '\\', ':' }) >= 0)         //Don't allow path control elements in a package ID.
        {
            MessageBox.Show("Invalid template path");
            return;
        }

        if (!PackageCache.PackageExists(packageId))
        {
            MessageBox.Show("The selected template could not be found. Please contact your Sample Portal site administrator for assistance.");
            return;
        }

        //Open a new work session.
        try
        {
            // title is in Cells[2].
            string templateTitle = tplGrid.SelectedItem.Cells[2].Text;
            _session = Factory.CreateWorkSession(Session, packageId, templateTitle);

            // Make sure that there is a cache for the assembled documents, and that it is empty.
            AssembledDocsCache cache = Factory.GetAssembledDocsCache(this.Session);
            cache.Clear();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            return;
        }

        //Redirect to "select answer set" page
        Response.Redirect("SelAns.aspx");
    }
コード例 #23
0
ファイル: Config.cs プロジェクト: lee1431/uno
        static IReadOnlyList <Library> GetUnoLibraries()
        {
            var cache = new PackageCache();
            var list  = new List <Library>();
            var set   = new HashSet <string>();

            foreach (var directory in cache.SearchPaths)
            {
                foreach (var package in cache.GetPackageDirectories(directory).Keys)
                {
                    foreach (var versionDir in cache.GetVersionDirectories(package))
                    {
                        if (PackageFile.Exists(versionDir.FullName) && !set.Contains(versionDir.FullName))
                        {
                            list.Add(new Library(package, versionDir.FullName));
                            set.Add(versionDir.FullName);
                        }
                    }
                }
            }

            list.Sort();
            return(list);
        }
コード例 #24
0
        private void BuildPackageCache()
        {
            PackageCache packageCache1 = new PackageCache();

            packageCache1.ID         = 1;
            packageCache1.ExternalId = "5355710e-b947-4762-af19-e78972ef207f";
            packageCache1.Name       = "express";
            packageCache1.Version    = "4.8.2";
            packageCache1.Store      = true;
            packageCache1.Project    = Projects.SingleOrDefault(p => p.ID == 1);

            PackageCaches.Add(packageCache1);

            PackageCache packageCache2 = new PackageCache();

            packageCache2.ID         = 2;
            packageCache2.ExternalId = "885f4f63-e696-4f0c-bb19-32a0702bc7cc";
            packageCache2.Name       = "mongoose";
            packageCache2.Version    = "3.8.3";
            packageCache2.Store      = true;
            packageCache2.Project    = Projects.SingleOrDefault(p => p.ID == 1);

            PackageCaches.Add(packageCache2);
        }
コード例 #25
0
ファイル: ModelPreview.cs プロジェクト: ME3Tweaks/ME3Explorer
        /// <summary>
        /// Creates a ModelPreviewMaterial that renders as close to what the given <see cref="MaterialInstanceConstant"/> looks like as possible.
        /// </summary>
        /// <param name="texcache">The texture cache to request textures from.</param>
        /// <param name="mat">The material that this ModelPreviewMaterial will try to look like.</param>
        protected ModelPreviewMaterial(PreviewTextureCache texcache, MaterialInstanceConstant mat, PackageCache assetCache, List <PreloadedTextureData> preloadedTextures = null)
        {
            if (mat == null)
            {
                return;
            }
            Properties.Add("Name", mat.Export.ObjectName);
            foreach (var textureEntry in mat.Textures)
            {
                if (!Textures.ContainsKey(textureEntry.FullPath) && textureEntry.ClassName == "Texture2D")  //Apparently some assets are cubemaps, we don't want these.
                {
                    if (preloadedTextures != null)
                    {
                        var preloadedInfo = preloadedTextures.FirstOrDefault(x => x.MaterialExport == mat.Export && x.Mip.Export.ObjectName.Name == textureEntry.ObjectName.Name); //i don't like matching on object name but its export vs import here.
                        if (preloadedInfo != null)
                        {
                            Textures.Add(textureEntry.FullPath, texcache.LoadTexture(preloadedInfo.Mip.Export, preloadedInfo.Mip, preloadedInfo.decompressedTextureData));
                        }
                        else
                        {
                            Debug.WriteLine("Preloading error");
                        }
                        //if (textureEntry is ExportEntry texPort && preloadedMipInfo.Export != texPort) throw new Exception();
                        continue; //Don't further parse
                    }

                    if (textureEntry is ImportEntry import)
                    {
                        var extAsset = EntryImporter.ResolveImport(import, null, assetCache);
                        if (extAsset != null)
                        {
                            Textures.Add(textureEntry.FullPath, texcache.LoadTexture(extAsset));
                        }
                    }
                    else
                    {
                        Textures.Add(textureEntry.FullPath, texcache.LoadTexture(textureEntry as ExportEntry));
                    }
                }
            }
        }
コード例 #26
0
ファイル: ModelPreview.cs プロジェクト: ME3Tweaks/ME3Explorer
        /// <summary>
        /// Creates a preview of the given <see cref="SkeletalMesh"/>.
        /// </summary>
        /// <param name="Device">The Direct3D device to use for buffer creation.</param>
        /// <param name="m">The mesh to generate a preview for.</param>
        /// <param name="texcache">The texture cache for loading textures.</param>
        public ModelPreview(Device Device, SkeletalMesh m, PreviewTextureCache texcache, PackageCache assetCache, PreloadedModelData preloadedData = null)
        {
            // STEP 1: MATERIALS
            if (preloadedData == null)
            {
                for (int i = 0; i < m.Materials.Length; i++)
                {
                    UIndex materialUIndex        = m.Materials[i];
                    MaterialInstanceConstant mat = null;
                    if (materialUIndex.value > 0)
                    {
                        mat = new MaterialInstanceConstant(m.Export.FileRef.GetUExport(materialUIndex.value));
                    }
                    else if (materialUIndex.value < 0)
                    {
                        // The material instance is an import!
                        ImportEntry matImport     = m.Export.FileRef.GetImport(materialUIndex.value);
                        var         externalAsset = EntryImporter.ResolveImport(matImport, null, assetCache);
                        if (externalAsset != null)
                        {
                            mat = new MaterialInstanceConstant(externalAsset);
                        }
                    }

                    if (mat != null)
                    {
                        ModelPreviewMaterial material;
                        // TODO: pick what material class best fits based on what properties the
                        // MaterialInstanceConstant mat has.
                        // For now, just use the default material.
                        material = new TexturedPreviewMaterial(texcache, mat, assetCache);
                        AddMaterial(material.Properties["Name"], material);
                    }
                }
            }
            else
            {
                //Preloaded
                //sections = preloadedData.sections;
                var uniqueMaterials = preloadedData.texturePreviewMaterials.Select(x => x.MaterialExport).Distinct();
                foreach (var mat in uniqueMaterials)
                {
                    var material = new TexturedPreviewMaterial(texcache, new MaterialInstanceConstant(mat), assetCache, preloadedData.texturePreviewMaterials);
                    AddMaterial(mat.ObjectName.Name, material);
                }
            }

            // STEP 2: LODS
            foreach (var lodmodel in m.LODModels)
            {
                // Vertices
                List <WorldVertex> vertices = new List <WorldVertex>(m.Export.Game == MEGame.ME1 ? lodmodel.ME1VertexBufferGPUSkin.Length : lodmodel.VertexBufferGPUSkin.VertexData.Length);
                if (m.Export.Game == MEGame.ME1)
                {
                    foreach (var vertex in lodmodel.ME1VertexBufferGPUSkin)
                    {
                        vertices.Add(new WorldVertex(new Vector3(-vertex.Position.X, vertex.Position.Z, vertex.Position.Y), Vector3.Zero, new Vector2(vertex.UV.X, vertex.UV.Y)));
                    }
                }
                else
                {
                    foreach (var vertex in lodmodel.VertexBufferGPUSkin.VertexData)
                    {
                        vertices.Add(new WorldVertex(new Vector3(-vertex.Position.X, vertex.Position.Z, vertex.Position.Y), Vector3.Zero, new Vector2(vertex.UV.X, vertex.UV.Y)));
                    }
                }
                // Triangles
                List <Triangle> triangles = new List <Triangle>(lodmodel.IndexBuffer.Length / 3);
                for (int i = 0; i < lodmodel.IndexBuffer.Length; i += 3)
                {
                    triangles.Add(new Triangle(lodmodel.IndexBuffer[i], lodmodel.IndexBuffer[i + 1], lodmodel.IndexBuffer[i + 2]));
                }
                WorldMesh mesh = new WorldMesh(Device, triangles, vertices);
                // Sections
                List <ModelPreviewSection> sections = new List <ModelPreviewSection>();
                foreach (var section in lodmodel.Sections)
                {
                    if (section.MaterialIndex < Materials.Count)
                    {
                        sections.Add(new ModelPreviewSection(Materials.Keys.ElementAt(section.MaterialIndex), section.BaseIndex, (uint)section.NumTriangles));
                    }
                }
                LODs.Add(new ModelPreviewLOD(mesh, sections));
            }
        }
コード例 #27
0
ファイル: ModelPreview.cs プロジェクト: ME3Tweaks/ME3Explorer
        /// <summary>
        /// Creates a preview of the given <see cref="StaticMesh"/>.
        /// </summary>
        /// <param name="Device">The Direct3D device to use for buffer creation.</param>
        /// <param name="m">The mesh to generate a preview for.</param>
        /// <param name="texcache">The texture cache for loading textures.</param>
        public ModelPreview(Device Device, StaticMesh m, int selectedLOD, PreviewTextureCache texcache, PackageCache assetCache, PreloadedModelData preloadedData = null)
        {
            if (selectedLOD < 0)  //PREVIEW BUG WORKAROUND
            {
                return;
            }

            // STEP 1: MESH
            var                lodModel  = m.LODModels[selectedLOD];
            List <Triangle>    triangles = new List <Triangle>(lodModel.IndexBuffer.Length / 3);
            List <WorldVertex> vertices  = new List <WorldVertex>((int)lodModel.NumVertices);

            // Gather all the vertex data
            // Only one LOD? odd but I guess that's just how it rolls.

            for (int i = 0; i < lodModel.NumVertices; i++)
            {
                var v = lodModel.PositionVertexBuffer.VertexData[i];
                if (lodModel.VertexBuffer.bUseFullPrecisionUVs)
                {
                    var uvVector = lodModel.VertexBuffer.VertexData[i].FullPrecisionUVs;
                    //SharpDX takes items differently than unreal.
                    vertices.Add(new Scene3D.WorldVertex(new Vector3(-v.X, v.Z, v.Y), Vector3.Zero, new Vector2(uvVector[0].X, uvVector[0].Y)));
                }
                else
                {
                    var uvVector = lodModel.VertexBuffer.VertexData[i].HalfPrecisionUVs;
                    //SharpDX takes items differently than unreal.
                    vertices.Add(new Scene3D.WorldVertex(new Vector3(-v.X, v.Z, v.Y), Vector3.Zero, new Vector2(uvVector[0].X, uvVector[0].Y)));
                }
            }

            //OLD CODE
            //for (int i = 0; i < m.L.Vertices.Points.Count; i++)
            //{
            //    // Note the reversal of the Z and Y coordinates. Unreal seems to think that Z should be up.
            //    vertices.Add(new Scene3D.WorldVertex(new SharpDX.Vector3(-m.Mesh.Vertices.Points[i].X, m.Mesh.Vertices.Points[i].Z, m.Mesh.Vertices.Points[i].Y), SharpDX.Vector3.Zero, new SharpDX.Vector2(m.Mesh.Edges.UVSet[i].UVs[0].X, m.Mesh.Edges.UVSet[i].UVs[0].Y)));
            //}

            // Sometimes there might not be an index buffer.
            // If there is one, use that.
            // Otherwise, assume that each vertex is used exactly once.
            // Note that this is based on the earlier implementation which didn't take LODs into consideration, which is odd considering that both the hit testing and the skeletalmesh class do.
            if (lodModel.IndexBuffer.Length > 0)
            {
                // Hey, we have indices all set up for us. How considerate.
                for (int i = 0; i < lodModel.IndexBuffer.Length; i += 3)
                {
                    triangles.Add(new Triangle(lodModel.IndexBuffer[i], lodModel.IndexBuffer[i + 1], lodModel.IndexBuffer[i + 2]));
                }
            }
            else
            {
                // Gather all the vertex data from the raw triangles, not the Mesh.Vertices.Point list.
                if (m.Export.Game <= MEGame.ME2)
                {
                    var kdop = m.kDOPTreeME1ME2;
                    for (int i = 0; i < kdop.Triangles.Length; i++)
                    {
                        triangles.Add(new Triangle(kdop.Triangles[i].Vertex1, kdop.Triangles[i].Vertex2, kdop.Triangles[i].Vertex3));
                    }
                }
                else
                {
                    var kdop = m.kDOPTreeME3UDK;
                    for (int i = 0; i < kdop.Triangles.Length; i++)
                    {
                        triangles.Add(new Triangle(kdop.Triangles[i].Vertex1, kdop.Triangles[i].Vertex2, kdop.Triangles[i].Vertex3));
                    }
                }
            }



            /*
             * if (m.Mesh.IdxBuf.Indexes != null && m.Mesh.IdxBuf.Indexes.Count > 0)
             * {
             *  // Hey, we have indices all set up for us. How considerate.
             *  for (int i = 0; i < m.Mesh.IdxBuf.Indexes.Count; i += 3)
             *  {
             *      triangles.Add(new Triangle(m.Mesh.IdxBuf.Indexes[i], m.Mesh.IdxBuf.Indexes[i + 1], m.Mesh.IdxBuf.Indexes[i + 2]));
             *  }
             * }
             * else
             * {
             *  // Gather all the vertex data from the raw triangles, not the Mesh.Vertices.Point list.
             *  for (int i = 0; i < m.Mesh.RawTris.RawTriangles.Count; i++)
             *  {
             *      triangles.Add(new Triangle((uint)m.Mesh.RawTris.RawTriangles[i].v0, (uint)m.Mesh.RawTris.RawTriangles[i].v1, (uint)m.Mesh.RawTris.RawTriangles[i].v2));
             *  }
             * }*/


            //OLD CODE

            /* if (m.Mesh.IdxBuf.Indexes != null && m.Mesh.IdxBuf.Indexes.Count > 0)
             *          {
             *              // Hey, we have indices all set up for us. How considerate.
             *              for (int i = 0; i < m.Mesh.IdxBuf.Indexes.Count; i += 3)
             *              {
             *                  triangles.Add(new Triangle(m.Mesh.IdxBuf.Indexes[i], m.Mesh.IdxBuf.Indexes[i + 1], m.Mesh.IdxBuf.Indexes[i + 2]));
             *              }
             *          }
             *          else
             *          {
             *              // Gather all the vertex data from the raw triangles, not the Mesh.Vertices.Point list.
             *              for (int i = 0; i < m.Mesh.RawTris.RawTriangles.Count; i++)
             *              {
             *                  triangles.Add(new Triangle((uint)m.Mesh.RawTris.RawTriangles[i].v0, (uint)m.Mesh.RawTris.RawTriangles[i].v1, (uint)m.Mesh.RawTris.RawTriangles[i].v2));
             *              }
             *          }*/

            // STEP 2: MATERIALS
            //foreach (var v in lodModel.Elements)


            //foreach (Unreal.Classes.MaterialInstanceConstant mat in m.Mesh.Mat.MatInst)
            //{
            //    ModelPreviewMaterial material;
            //    // TODO: pick what material class best fits based on what properties the
            //    // MaterialInstanceConstant mat has.
            //    // For now, just use the default material.
            //    material = new TexturedPreviewMaterial(texcache, mat);
            //    AddMaterial(material.Properties["Name"], material);
            //}

            // STEP 3: SECTIONS
            List <ModelPreviewSection> sections = preloadedData != null ? preloadedData.sections : null;
            List <IMEPackage>          assetLookupPackagesToDispose = new List <IMEPackage>();

            //This section exists for Meshplorer Winforms. WPF version preloads this in a background thread to improve performance
            if (sections == null)
            {
                sections = new List <ModelPreviewSection>();
                foreach (var section in lodModel.Elements)
                {
                    if (section.Material.value > 0)
                    {
                        ModelPreviewMaterial material;
                        // TODO: pick what material class best fits based on what properties the
                        // MaterialInstanceConstant mat has.
                        // For now, just use the default material.
                        ExportEntry entry = m.Export.FileRef.GetUExport(section.Material.value);
                        material = new TexturedPreviewMaterial(texcache, new MaterialInstanceConstant(entry), assetCache);
                        AddMaterial(material.Properties["Name"], material);
                    }
                    else if (section.Material.value < 0)
                    {
                        var extMaterialExport = FindExternalAsset(m.Export.FileRef.GetImport(section.Material.value), texcache.cache.Select(x => x.TextureExport).ToList(), assetLookupPackagesToDispose);
                        if (extMaterialExport != null)
                        {
                            ModelPreviewMaterial material;
                            // TODO: pick what material class best fits based on what properties the
                            // MaterialInstanceConstant mat has.
                            // For now, just use the default material.
                            material = new TexturedPreviewMaterial(texcache, new MaterialInstanceConstant(extMaterialExport), assetCache);
                            AddMaterial(material.Properties["Name"], material);
                        }
                        else
                        {
                            Debug.WriteLine("Could not find import material from section.");
                            Debug.WriteLine("Import material: " + m.Export.FileRef.GetEntryString(section.Material.value));
                        }
                    }

                    sections.Add(new ModelPreviewSection(m.Export.FileRef.getObjectName(section.Material.value), section.FirstIndex, section.NumTriangles));
                }
            }
            else
            {
                //Preloaded
                sections = preloadedData.sections;
                var uniqueMaterials = preloadedData.texturePreviewMaterials.Select(x => x.MaterialExport).Distinct();
                foreach (var mat in uniqueMaterials)
                {
                    var material = new TexturedPreviewMaterial(texcache, new MaterialInstanceConstant(mat), assetCache, preloadedData.texturePreviewMaterials);
                    AddMaterial(mat.ObjectName.Name, material);
                }
            }

            foreach (var package in assetLookupPackagesToDispose)
            {
                package?.Dispose(); //Release
            }
            //List<ModelPreviewSection> sections = new List<ModelPreviewSection>();
            //foreach (var section in lodModel.Elements)
            //{
            //    sections.Add(new ModelPreviewSection(m.Export.FileRef.getObjectName(section.Material.value), section.FirstIndex, section.NumTriangles));
            //}
            LODs.Add(new ModelPreviewLOD(new WorldMesh(Device, triangles, vertices), sections));
        }
コード例 #28
0
ファイル: ModelPreview.cs プロジェクト: ME3Tweaks/ME3Explorer
        /// <summary>
        /// Creates a preview of a generic untextured mesh
        /// </summary>
        /// <param name="device"></param>
        /// <param name="mesh"></param>
        public ModelPreview(Device device, WorldMesh mesh, PreviewTextureCache texcache, PackageCache assetCache, PreloadedModelData preloadedData = null)
        {
            //Preloaded
            List <ModelPreviewSection> sections = new List <ModelPreviewSection>();

            if (preloadedData != null)
            {
                sections = preloadedData.sections;
                var uniqueMaterials = preloadedData.texturePreviewMaterials.Select(x => x.MaterialExport).Distinct();
                foreach (var mat in uniqueMaterials)
                {
                    var material = new TexturedPreviewMaterial(texcache, new MaterialInstanceConstant(mat), assetCache, preloadedData.texturePreviewMaterials);
                    AddMaterial(mat.ObjectName.Name, material);
                }
            }
            LODs.Add(new ModelPreviewLOD(mesh, sections));
        }
コード例 #29
0
ファイル: ModelPreview.cs プロジェクト: ME3Tweaks/ME3Explorer
        /// <summary>
        /// Creates a TexturedPreviewMaterial that renders as close to what the given <see cref="MaterialInstanceConstant"/> looks like as possible.
        /// </summary>
        /// <param name="texcache">The texture cache to request textures from.</param>
        /// <param name="mat">The material that this ModelPreviewMaterial will try to look like.</param>
        public TexturedPreviewMaterial(PreviewTextureCache texcache, MaterialInstanceConstant mat, PackageCache assetCache, List <PreloadedTextureData> preloadedTextures = null) : base(texcache, mat, assetCache, preloadedTextures)
        {
            string matPackage = null;

            if (mat.Export.Parent != null)
            {
                matPackage = mat.Export.Parent.FullPath.ToLower();
            }
            foreach (var textureEntry in mat.Textures)
            {
                var texObjectName = textureEntry.FullPath.ToLower();
                if ((matPackage == null || texObjectName.StartsWith(matPackage)) && texObjectName.Contains("diff"))
                {
                    // we have found the diffuse texture!
                    DiffuseTextureFullName = textureEntry.FullPath;
                    Debug.WriteLine("Diffuse texture of new material <" + Properties["Name"] + "> is " + DiffuseTextureFullName);
                    return;
                }
            }

            foreach (var textureEntry in mat.Textures)
            {
                var texObjectName = textureEntry.ObjectName.Name.ToLower();
                if (texObjectName.Contains("diff") || texObjectName.Contains("tex"))
                {
                    // we have found the diffuse texture!
                    DiffuseTextureFullName = textureEntry.FullPath;
                    Debug.WriteLine("Diffuse texture of new material <" + Properties["Name"] + "> is " + DiffuseTextureFullName);
                    return;
                }
            }
            foreach (var texparam in mat.Textures)
            {
                var texObjectName = texparam.ObjectName.Name.ToLower();

                if (texObjectName.Contains("detail"))
                {
                    // I guess a detail texture is good enough if we didn't return for a diffuse texture earlier...
                    DiffuseTextureFullName = texparam.FullPath;
                    Debug.WriteLine("Diffuse (Detail) texture of new material <" + Properties["Name"] + "> is " + DiffuseTextureFullName);
                    return;
                }
            }
            foreach (var texparam in mat.Textures)
            {
                var texObjectName = texparam.ObjectName.Name.ToLower();
                if (!texObjectName.Contains("norm") && !texObjectName.Contains("opac"))
                {
                    //Anything is better than nothing I suppose
                    DiffuseTextureFullName = texparam.FullPath;
                    Debug.WriteLine("Using first found texture (last resort)  of new material <" + Properties["Name"] + "> as diffuse: " + DiffuseTextureFullName);
                    return;
                }
            }
        }
コード例 #30
0
 public InMemoryJournalRepository(Dictionary <PackageIdentity, JournalEntry> journalEntries)
 {
     this.journalEntries = journalEntries;
     Cache = new PackageCache(0);
 }