static AssetLoadInfo GetTestAssetLoadInfo() { GUID asset = new GUID(AssetDatabase.AssetPathToGUID(kTestAsset)); ObjectIdentifier[] oId = ContentBuildInterface.GetPlayerObjectIdentifiersInAsset(asset, EditorUserBuildSettings.activeBuildTarget); AssetLoadInfo loadInfo = new AssetLoadInfo() { asset = asset, address = kTestAsset, includedObjects = oId.ToList(), referencedObjects = new List <ObjectIdentifier>() }; return(loadInfo); }
IEnumerator LoadAssetCoroutine <T>(List <string> pathList, Action <List <AssetLoadInfo> > action, object arg) where T : Object { foreach (var item in pathList) { yield return(LoadAssetCoroutineHelper <T>(item)); } if (action != null) { List <AssetLoadInfo> list = new List <AssetLoadInfo>(); foreach (var item in pathList) { list.Add(AssetLoadInfo.Create(item)); } action.Invoke(list); } }
CachedInfo GetCachedInfo(CacheEntry entry, AssetLoadInfo assetInfo, BuildUsageTagSet usageTags) { var info = new CachedInfo(); info.Asset = entry; var uniqueTypes = new HashSet <Type>(); var objectTypes = new List <KeyValuePair <ObjectIdentifier, Type[]> >(); var dependencies = new HashSet <CacheEntry>(); ExtensionMethods.ExtractCommonCacheData(m_Cache, assetInfo.includedObjects, assetInfo.referencedObjects, uniqueTypes, objectTypes, dependencies); info.Dependencies = dependencies.ToArray(); info.Data = new object[] { assetInfo, usageTags, objectTypes }; return(info); }
static CachedInfo GetCachedInfo(IBuildCache cache, GUID asset, AssetLoadInfo assetInfo, BuildUsageTagSet usageTags, SpriteImporterData importerData, ExtendedAssetData assetData) { var info = new CachedInfo(); info.Asset = cache.GetCacheEntry(asset, kVersion); var uniqueTypes = new HashSet <System.Type>(); var objectTypes = new List <KeyValuePair <ObjectIdentifier, System.Type[]> >(); var dependencies = new HashSet <CacheEntry>(); ExtensionMethods.ExtractCommonCacheData(cache, assetInfo.includedObjects, assetInfo.referencedObjects, uniqueTypes, objectTypes, dependencies); info.Dependencies = dependencies.ToArray(); info.Data = new object[] { assetInfo, usageTags, importerData, assetData, objectTypes }; return(info); }
IDependencyData GetDependencyData(List <ObjectIdentifier> objects, params GUID[] guids) { IDependencyData dep = new BuildDependencyData(); for (int i = 0; i < guids.Length; i++) { AssetLoadInfo loadInfo = new AssetLoadInfo() { asset = guids[i], address = $"path{i}", includedObjects = objects, referencedObjects = objects }; dep.AssetInfo.Add(guids[i], loadInfo); } return(dep); }
void SetOutputInformation(GUID asset, AssetLoadInfo assetInfo, BuildUsageTagSet usageTags, SpriteImporterData importerData, ExtendedAssetData assetData) { // Add generated asset information to IDependencyData m_DependencyData.AssetInfo.Add(asset, assetInfo); m_DependencyData.AssetUsage.Add(asset, usageTags); // Add generated importer data to IBuildSpriteData if (importerData != null) { m_SpriteData.ImporterData.Add(asset, importerData); } if (assetData != null) { m_ExtendedAssetData.ExtendedData.Add(asset, assetData); } }
#pragma warning restore 649 CachedInfo GetCachedInfo(GUID asset, AssetLoadInfo assetInfo, BuildUsageTagSet usageTags, SpriteImporterData importerData) { var info = new CachedInfo(); info.Asset = m_Cache.GetCacheEntry(asset); var dependencies = new HashSet <CacheEntry>(); foreach (var reference in assetInfo.referencedObjects) { dependencies.Add(m_Cache.GetCacheEntry(reference)); } info.Dependencies = dependencies.ToArray(); info.Data = new object[] { assetInfo, usageTags, importerData }; return(info); }
private IEnumerator AssetLoader() { while (true) { if (pendingAssetLoads.Count > 0) { AssetLoadInfo info = pendingAssetLoads.Pop(); AssetBundle assetBundle; if (!currentAssetBundles.TryGetValue(info.resource_url, out assetBundle)) { UnityEngine.Networking.UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(info.resource_url, 0); yield return(request.SendWebRequest()); assetBundle = DownloadHandlerAssetBundle.GetContent(request); if (assetBundle) { currentAssetBundles.Add(info.resource_url, assetBundle); } } if (assetBundle != null) { GameObject extRefObject = assetBundle.LoadAsset <GameObject>(info.object_id); if (extRefObject != null) { GameObject instance = Instantiate(extRefObject); if (instance != null) { instance.name = info.object_id; instance.transform.SetParent(info.parent.transform, false); } } } } yield return(null); } }
private IDictionary <string, IAsset> LoadAssets(ZipArchive archive, SaveLoadMetadata metadata, IReadOnlyDictionary <string, Type> typeAliases, IFileLoadInfo loadInfo) { AssetSaveLoadInfo[] assetInfos; var assetInfoEntry = archive.GetEntry("assetInfos.json") ?? throw new Exception("assetInfo.json not found."); using (var reader = trwFactory.JsonReader(assetInfoEntry.Open())) using (var convertedReader = converterContainer.ConvertAssetInfoReader(reader, metadata.Version, converterContainer.CurrentVersion)) using (var context = saveLoadFactory.AssetsInfoReadContext(convertedReader, typeAliases)) assetInfos = context.Read <AssetSaveLoadInfo[]>(); var assets = new Dictionary <string, IAsset>(); var zipFileSystem = new ZipFileSystem(archive); var actualFileSystem = new ActualFileSystem(); foreach (var assetInfo in assetInfos) { var assetLoadInfo = new AssetLoadInfo { AssetName = assetInfo.AssetName, StorageType = assetInfo.StorageType, ReferencePath = assetInfo.ReferencePath }; switch (assetInfo.StorageType) { case AssetStorageType.CopyLocal: assetLoadInfo.FileSystem = zipFileSystem; assetLoadInfo.LoadPath = assetInfo.LocalCopyPath; break; case AssetStorageType.ReferenceOriginal: assetLoadInfo.FileSystem = actualFileSystem; assetLoadInfo.LoadPath = assetInfo.ReferencePath; break; default: throw new ArgumentOutOfRangeException(); } var asset = loadInfo.OnFoundAsset(assetLoadInfo); assets.Add(asset.Name, asset); } return(assets); }
internal static AssetLoadInfo CreatePrefabWithReferences(GUID prefabGuid, params ObjectIdentifier[] references) { var asset = new AssetLoadInfo(); asset.address = prefabGuid.ToString(); asset.asset = prefabGuid; asset.includedObjects = new List <ObjectIdentifier> { ConstructObjectIdentifier(prefabGuid, 1326890503170502, FileType.SerializedAssetType, ""), // GameObject ConstructObjectIdentifier(prefabGuid, 4326504406238768, FileType.SerializedAssetType, ""), // Transform ConstructObjectIdentifier(prefabGuid, 114305515917122674, FileType.SerializedAssetType, "") // Monobehavior W/ Reference }; List <ObjectIdentifier> referencedObjects = new List <ObjectIdentifier>(references); referencedObjects.Add(ConstructObjectIdentifier(new GUID("206794ec26056d846b1615847cacd2cc"), 11500000, FileType.MetaAssetType, "")); // MonoScript asset.referencedObjects = referencedObjects; return(asset); }
IEnumerator LoadAssetCoroutine <T>(List <string> pathList, Action <List <AssetLoadInfo> > action, object arg) where T : Object { //foreach (var item in pathList) //{ // AddPrepareLoadDic(item); //} foreach (var item in pathList) { yield return(LoadAssetCoroutineHelper <T>(item)); } if (action != null) { List <AssetLoadInfo> list = new List <AssetLoadInfo>(); for (int i = 0; i < pathList.Count; i++) { list.Add(AssetLoadInfo.Create(pathList[i], arg)); } action.Invoke(list); } }
static IDependencyData GetDependencyData() { GUID guid; GUID.TryParse(AssetDatabase.AssetPathToGUID(k_CubePath), out guid); ObjectIdentifier[] oId = ContentBuildInterface.GetPlayerObjectIdentifiersInAsset(guid, EditorUserBuildSettings.activeBuildTarget); AssetLoadInfo loadInfo = new AssetLoadInfo() { asset = guid, address = k_CubePath, includedObjects = oId.ToList(), referencedObjects = oId.ToList() }; IDependencyData dep = new BuildDependencyData(); dep.AssetInfo.Add(guid, loadInfo); return(dep); }
public AssetLoadResultByLoader Load(AssetLoadInfo loadInfo) { // todo: use file system try { if (Path.GetExtension(loadInfo.LoadPath) == ".dcm") { return(LoadSingle(loadInfo)); } if (Path.GetExtension(loadInfo.LoadPath) == ".dcmf") { return(LoadFolder(loadInfo)); } return(AssetLoadResultByLoader.Failure("Neither .dcm nor .dcmf", null)); } catch (Exception ex) { return(AssetLoadResultByLoader.Failure(ex.GetType().Name, ex)); } }
/// <summary> /// Adds mapping and bundle information for a custom asset that contains a set of unity objects. /// </summary> /// <param name="includedObjects">Object Identifiers that belong to this custom asset</param> /// <param name="path">Path on disk for this custom asset</param> /// <param name="bundleName">Asset Bundle name where to add this custom asset</param> /// <param name="address">Load address to used to load this asset from the Asset Bundle</param> /// <param name="mainAssetType">Type of the main object for this custom asset</param> public void CreateAssetEntryForObjectIdentifiers(ObjectIdentifier[] includedObjects, string path, string bundleName, string address, Type mainAssetType) { AssetLoadInfo assetInfo = new AssetLoadInfo(); BuildUsageTagSet usageTags = new BuildUsageTagSet(); assetInfo.asset = HashingMethods.Calculate(address).ToGUID(); assetInfo.address = address; if (m_DependencyData.AssetInfo.ContainsKey(assetInfo.asset)) { throw new ArgumentException(string.Format("Custom Asset '{0}' already exists. Building duplicate asset entries is not supported.", address)); } assetInfo.includedObjects = new List <ObjectIdentifier>(includedObjects); var referencedObjects = ContentBuildInterface.GetPlayerDependenciesForObjects(includedObjects, m_Parameters.Target, m_Parameters.ScriptInfo); assetInfo.referencedObjects = new List <ObjectIdentifier>(referencedObjects); ContentBuildInterface.CalculateBuildUsageTags(referencedObjects, includedObjects, m_GlobalUsage, usageTags, m_DependencyData.DependencyUsageCache); SetOutputInformation(bundleName, assetInfo, usageTags); }
private IAsset BuildAsset(AssetLoadInfo loadInfo) { // todo: load from memory /* Get the data files: */ Irit.IPSetFlattenObjects(0); var pFileName = Marshal.StringToHGlobalAnsi(loadInfo.LoadPath); var pObjects = Irit.IPGetDataFiles((byte **)&pFileName, 1, TRUE, FALSE); Marshal.FreeHGlobal(pFileName); if (pObjects == NULL) { throw new Exception($"Failed to load '{loadInfo.LoadPath}' as an ITD model."); } pObjects = Irit.IPResolveInstances(pObjects); var viewMat = new IrtHmgnMatType {
private IAsset CreateAsset(AssetLoadInfo loadInfo) { var fileBytes = loadInfo.FileSystem.ReadAllBytes(loadInfo.LoadPath); int width, height; double duration; using (var stream = new MemoryStream(fileBytes)) using (var reader = new FFmpegMovieReader(stream)) { width = reader.Width; height = reader.Height; duration = reader.Duration; } var assetName = loadInfo.AssetName; var fileName = Path.GetFileName(loadInfo.LoadPath); var movie = new FFmpegFileMovie(width, height, duration, () => OpenAssetFile(assetName, fileName)); var hash = AssetHashMd5.FromSingleFile(fileBytes); return(new Asset(assetName, movie, loadInfo.StorageType, hash, loadInfo.ReferencePath, fileName)); }
private static SortedDictionary <string, AssetLoadInfo> GetScenePrefabNames(string filePath) { SortedDictionary <string, AssetLoadInfo> prefabs = new SortedDictionary <string, AssetLoadInfo>(); XmlReader reader = XmlReader.Create(filePath); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element && reader.Name.Equals("LoadItem")) { XElement ele = XElement.ReadFrom(reader) as XElement; int initialOrder = int.Parse(ele.Attribute("InitialOrder").Value); bool isActive = bool.Parse(ele.Attribute("IsActive").Value); string prefabABName = ele.Attribute("PrefabABPath").Value; string organizeDataABName = ele.Attribute("OrganizeDataABPath").Value; AssetLoadInfo loadItem = new AssetLoadInfo(prefabABName, organizeDataABName, initialOrder, isActive); prefabs.Add(loadItem.prefabABName, loadItem); } } reader.Close(); return(prefabs); }
internal static AssetLoadInfo CreateFBXWithMesh(GUID fbxGuid) { var asset = new AssetLoadInfo(); asset.address = fbxGuid.ToString(); asset.asset = fbxGuid; asset.includedObjects = new List <ObjectIdentifier> { ConstructObjectIdentifier(fbxGuid, 100000, FileType.MetaAssetType, ""), // GameObject ConstructObjectIdentifier(fbxGuid, 400000, FileType.MetaAssetType, ""), // Transform ConstructObjectIdentifier(fbxGuid, 2100000, FileType.MetaAssetType, ""), // Material ConstructObjectIdentifier(fbxGuid, 2300000, FileType.MetaAssetType, ""), // MeshRenderer ConstructObjectIdentifier(fbxGuid, 3300000, FileType.MetaAssetType, ""), // MeshFilter ConstructObjectIdentifier(fbxGuid, 4300000, FileType.MetaAssetType, "") // Mesh }; asset.referencedObjects = new List <ObjectIdentifier> { ConstructObjectIdentifier(new GUID("0000000000000000f000000000000000"), 6, FileType.NonAssetType, "resources/unity_builtin_extra"), // Shader ConstructObjectIdentifier(new GUID("0000000000000000f000000000000000"), 46, FileType.NonAssetType, "resources/unity_builtin_extra") // Shader }; return(asset); }
void CreateAssetBundleCommand(string bundleName, string internalName, List <GUID> assets) { var command = CreateWriteCommand(internalName, m_WriteData.FileToObjects[internalName], m_PackingMethod); var usageSet = new BuildUsageTagSet(); var referenceMap = new BuildReferenceMap(); var dependencyHashes = new List <Hash128>(); var bundleAssets = new List <AssetLoadInfo>(); referenceMap.AddMappings(command.internalName, command.serializeObjects.ToArray()); foreach (var asset in assets) { usageSet.UnionWith(m_DependencyData.AssetUsage[asset]); if (m_DependencyData.DependencyHash.TryGetValue(asset, out var hash)) { dependencyHashes.Add(hash); } AssetLoadInfo assetInfo = m_DependencyData.AssetInfo[asset]; assetInfo.address = m_BuildContent.Addresses[asset]; bundleAssets.Add(assetInfo); } bundleAssets.Sort(AssetLoadInfoCompare); var operation = new AssetBundleWriteOperation(); operation.Command = command; operation.UsageSet = usageSet; operation.ReferenceMap = referenceMap; operation.DependencyHash = !dependencyHashes.IsNullOrEmpty() ? HashingMethods.Calculate(dependencyHashes).ToHash128() : new Hash128(); operation.Info = new AssetBundleInfo(); operation.Info.bundleName = bundleName; operation.Info.bundleAssets = bundleAssets; m_WriteData.WriteOperations.Add(operation); m_WriteData.FileToUsageSet.Add(command.internalName, usageSet); m_WriteData.FileToReferenceMap.Add(command.internalName, referenceMap); }
// Sort function to ensure Asset Bundle's path container is ordered deterministically everytime internal static int AssetLoadInfoCompare(AssetLoadInfo x, AssetLoadInfo y) { if (x.asset != y.asset) { return(x.asset.CompareTo(y.asset)); } if (x.includedObjects.IsNullOrEmpty() && !y.includedObjects.IsNullOrEmpty()) { return(-1); } if (!x.includedObjects.IsNullOrEmpty() && y.includedObjects.IsNullOrEmpty()) { return(1); } if (!x.includedObjects.IsNullOrEmpty() && !y.includedObjects.IsNullOrEmpty()) { if (x.includedObjects[0] < y.includedObjects[0]) { return(-1); } if (x.includedObjects[0] > y.includedObjects[0]) { return(1); } } if (string.IsNullOrEmpty(x.address) && !string.IsNullOrEmpty(y.address)) { return(-1); } if (!string.IsNullOrEmpty(x.address) && string.IsNullOrEmpty(y.address)) { return(1); } if (!string.IsNullOrEmpty(x.address) && !string.IsNullOrEmpty(y.address)) { return(x.address.CompareTo(y.address)); } return(0); }
void PackAssetBundle(string bundleName, List <GUID> includedAssets, Dictionary <GUID, List <GUID> > assetToReferences) { var internalName = string.Format(CommonStrings.AssetBundleNameFormat, m_PackingMethod.GenerateInternalFileName(bundleName)); var allObjects = new HashSet <ObjectIdentifier>(); foreach (var asset in includedAssets) { AssetLoadInfo assetInfo = m_DependencyData.AssetInfo[asset]; allObjects.UnionWith(assetInfo.includedObjects); var references = new List <ObjectIdentifier>(); references.AddRange(assetInfo.referencedObjects); assetToReferences[asset] = FilterReferencesForAsset(asset, references); allObjects.UnionWith(references); m_WriteData.AssetToFiles[asset] = new List <string> { internalName }; } m_WriteData.FileToBundle.Add(internalName, bundleName); m_WriteData.FileToObjects.Add(internalName, allObjects.ToList()); }
public AssetLoadResultByLoader Load(AssetLoadInfo loadInfo) { try { var points = new List <Vector3>(); var loadPath = loadInfo.LoadPath; var fileData = loadInfo.FileSystem.ReadAllBytes(loadPath); using (var reader = new StreamReader(new MemoryStream(fileData))) while (true) { var line = reader.ReadLine(); if (line == null) { break; } var match = PointRegex.Match(line); if (!match.Success) { continue; } points.Add(new Vector3( float.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture), float.Parse(match.Groups[2].Value, CultureInfo.InvariantCulture), float.Parse(match.Groups[3].Value, CultureInfo.InvariantCulture) )); } var resource = new SpherePackingResult(points); var hash = AssetHashMd5.FromSingleFile(fileData); var asset = new Asset(loadInfo.AssetName, resource, loadInfo.StorageType, hash, loadInfo.ReferencePath, Path.GetFileName(loadInfo.ReferencePath)); return(AssetLoadResultByLoader.Success(asset)); } catch (Exception ex) { return(AssetLoadResultByLoader.Failure("EXCEPTION", ex)); } }
public static void LoadAsync <T>(string assetAddress, Action <T> callback) { AssetLoadInfo <T> loadInfo = new AssetLoadInfo <T>(assetAddress, callback); loadInfo.StartLoad(); }
//Add GameObjects to dictionary // Traverse function iterates the scene graph to build local branches on Unity GameObject Traverse(Node n, Material currentMaterial) { // We must be called in edit lock if (n == null || !n.IsValid()) { return(null); } // --------------------------- Add game object --------------------------------------- string name = n.GetName(); if (String.IsNullOrEmpty(name)) { name = n.GetNativeTypeName(); } GameObject gameObject = new GameObject(name); var nodeHandle = gameObject.AddComponent <NodeHandle>(); //nodeHandle.Renderer = Renderer; nodeHandle.node = n; nodeHandle.currentMaterial = currentMaterial; nodeHandle.ComputeShader = Settings.ComputeShader; // ---------------------------- Check material state ---------------------------------- if (n.HasState()) { State state = n.State; if (state.HasTexture(0) && state.GetMode(StateMode.TEXTURE) == StateModeActivation.ON) { gzTexture texture = state.GetTexture(0); if (!textureMaterialStorage.TryGetValue(texture.GetNativeReference(), out currentMaterial)) { if (texture.HasImage()) { ImageFormat image_format; ComponentType comp_type; uint components; uint depth; uint width; uint height; uint size; bool uncompress = false; Image image = texture.GetImage(); image_format = image.GetFormat(); image.Dispose(); switch (image_format) // Not yet { case ImageFormat.COMPRESSED_RGBA8_ETC2: if (!SystemInfo.SupportsTextureFormat(TextureFormat.ETC2_RGBA8)) { uncompress = true; } break; case ImageFormat.COMPRESSED_RGB8_ETC2: if (!SystemInfo.SupportsTextureFormat(TextureFormat.ETC2_RGB)) { uncompress = true; } break; case ImageFormat.COMPRESSED_RGBA_S3TC_DXT1: case ImageFormat.COMPRESSED_RGB_S3TC_DXT1: if (!SystemInfo.SupportsTextureFormat(TextureFormat.DXT1)) { uncompress = true; } break; case ImageFormat.COMPRESSED_RGBA_S3TC_DXT5: if (!SystemInfo.SupportsTextureFormat(TextureFormat.DXT5)) { uncompress = true; } break; } if (texture.GetMipMapImageArray(ref _image_texture_data, out size, out image_format, out comp_type, out components, out width, out height, out depth, true, uncompress)) { if (depth == 1) { if (n is Crossboard) { currentMaterial = new Material(Settings.CrossboardShader); } else { currentMaterial = new Material(Settings.DefaultShader); } TextureFormat format = TextureFormat.ARGB32; switch (comp_type) { case ComponentType.UNSIGNED_BYTE: { switch (image_format) { case ImageFormat.RGBA: format = TextureFormat.RGBA32; break; case ImageFormat.RGB: format = TextureFormat.RGB24; break; case ImageFormat.COMPRESSED_RGBA_S3TC_DXT1: case ImageFormat.COMPRESSED_RGB_S3TC_DXT1: format = TextureFormat.DXT1; break; case ImageFormat.COMPRESSED_RGBA_S3TC_DXT5: format = TextureFormat.DXT5; break; case ImageFormat.COMPRESSED_RGB8_ETC2: format = TextureFormat.ETC2_RGB; break; case ImageFormat.COMPRESSED_RGBA8_ETC2: format = TextureFormat.ETC2_RGBA8; break; default: // Issue your own error here because we can not use this texture yet return(null); } } break; default: // Issue your own error here because we can not use this texture yet return(null); } Texture2D tex = new Texture2D((int)width, (int)height, format, true); tex.LoadRawTextureData(_image_texture_data); switch (texture.MinFilter) { default: tex.filterMode = FilterMode.Point; break; case gzTexture.TextureMinFilter.LINEAR: case gzTexture.TextureMinFilter.LINEAR_MIPMAP_NEAREST: tex.filterMode = FilterMode.Bilinear; break; case gzTexture.TextureMinFilter.LINEAR_MIPMAP_LINEAR: tex.filterMode = FilterMode.Trilinear; break; } tex.Apply(texture.UseMipMaps, true); currentMaterial.mainTexture = tex; } } } // Add some kind of check for textures shared by many // Right now only for crossboards if (n is Crossboard) { textureMaterialStorage.Add(texture.GetNativeReference(), currentMaterial); } } nodeHandle.currentMaterial = currentMaterial; texture.Dispose(); } state.Dispose(); } // ---------------------------- Transform check ------------------------------------- gzTransform tr = n as gzTransform; if (tr != null) { Vec3 translation; if (tr.GetTranslation(out translation)) { Vector3 trans = new Vector3(translation.x, translation.y, translation.z); gameObject.transform.localPosition = trans; } // Notify subscribers of new Transform OnNewTransform?.Invoke(gameObject); } // ---------------------------- DynamicLoader check ------------------------------------- DynamicLoader dl = n as DynamicLoader; // Add dynamic loader as game object in dictionary // so other dynamic loaded data can parent them as child to loader if (dl != null) { List <GameObject> list; if (!NodeUtils.FindGameObjects(dl.GetNativeReference(), out list)) // We are not registered { NodeUtils.AddGameObjectReference(dl.GetNativeReference(), gameObject); nodeHandle.inNodeUtilsRegistry = true; // Added to registry // We shall continue to iterate as a group to see if we already have loaded children } else // We are already in list { return(list[0]); // Lets return first object wich is our main registered node } // Notify subscribers of new Loader OnNewLoader?.Invoke(gameObject); } // ---------------------------- Lod check ------------------------------------- Lod ld = n as Lod; if (ld != null) { foreach (Node child in ld) { GameObject go_child = Traverse(child, currentMaterial); if (go_child == null) { return(null); } NodeHandle h = go_child.GetComponent <NodeHandle>(); if (h != null) { if (!NodeUtils.HasGameObjects(h.node.GetNativeReference())) { NodeUtils.AddGameObjectReference(h.node.GetNativeReference(), go_child); h.inNodeUtilsRegistry = true; h.node.AddActionInterface(_actionReceiver, NodeActionEvent.IS_TRAVERSABLE); h.node.AddActionInterface(_actionReceiver, NodeActionEvent.IS_NOT_TRAVERSABLE); } } go_child.transform.SetParent(gameObject.transform, false); } // Notify subscribers of new Lod OnNewLod?.Invoke(gameObject); // Dont process group as group is already processed return(gameObject); } // ---------------------------- Roi check ------------------------------------- Roi roi = n as Roi; if (roi != null) { nodeHandle.updateTransform = true; nodeHandle.inNodeUpdateList = true; updateNodeObjects.AddLast(gameObject); foreach (Node child in roi) { GameObject go_child = Traverse(child, currentMaterial); if (go_child == null) { return(null); } NodeHandle h = go_child.GetComponent <NodeHandle>(); if (h != null) { if (!NodeUtils.HasGameObjects(h.node.GetNativeReference())) { NodeUtils.AddGameObjectReference(h.node.GetNativeReference(), go_child); h.inNodeUtilsRegistry = true; h.node.AddActionInterface(_actionReceiver, NodeActionEvent.IS_TRAVERSABLE); h.node.AddActionInterface(_actionReceiver, NodeActionEvent.IS_NOT_TRAVERSABLE); } } go_child.transform.SetParent(gameObject.transform, false); } // Dont process group return(gameObject); } // ---------------------------- RoiNode check ------------------------------------- RoiNode roinode = n as RoiNode; if (roinode != null) { nodeHandle.updateTransform = true; nodeHandle.inNodeUpdateList = true; updateNodeObjects.AddLast(gameObject); } // ---------------------------- Group check ------------------------------------- Group g = n as Group; if (g != null) { foreach (Node child in g) { GameObject go_child = Traverse(child, currentMaterial); if (go_child == null) { return(null); } go_child.transform.SetParent(gameObject.transform, false); } return(gameObject); } // ---------------------------ExtRef check ----------------------------------------- ExtRef ext = n as ExtRef; if (ext != null) { AssetLoadInfo info = new AssetLoadInfo(gameObject, ext.ResourceURL, ext.ObjectID); pendingAssetLoads.Push(info); } // ---------------------------- Crossboard check ----------------------------------- Crossboard cb = n as Crossboard; if (cb != null && GfxCaps.HasCapability(Capability.UseTreeCrossboards)) { // Scheduled for later build pendingBuilds.Enqueue(nodeHandle); } // ---------------------------- Geometry check ------------------------------------- Geometry geom = n as Geometry; if (geom != null) { nodeHandle.BuildGameObject(); // Notify subscribers of new Geometry OnNewGeometry?.Invoke(gameObject); // Later on we will identify types of geoemtry that will be scheduled later if they are extensive and not ground that covers other geometry // and build them in a later pass distributed over time // pendingBuilds.Enqueue(nodeHandle); } return(gameObject); }
public override BuildPipelineCodes Convert(BuildDependencyInfo input, BuildSettings settings, bool aggressive, out BuildDependencyInfo output) { StartProgressBar("Generated shared object bundles", 3); Hash128 hash = CalculateInputHash(input); if (UseCache && BuildCache.TryLoadCachedResults(hash, out output)) { EndProgressBar(); return(BuildPipelineCodes.SuccessCached); } // Mutating the input output = input; if (!UpdateProgressBar("Generate lookup of all objects")) { EndProgressBar(); return(BuildPipelineCodes.Canceled); } // Generate mapping of each object to the bundles it would be used by var objectToBundles = new Dictionary <ObjectIdentifier, HashSet <string> >(); var objectToAssets = new Dictionary <ObjectIdentifier, HashSet <GUID> >(); foreach (var asset in input.assetInfo.Values) { var dependencies = input.assetToBundles[asset.asset]; if (aggressive && !asset.includedObjects.IsNullOrEmpty()) { for (int i = 1; i < asset.includedObjects.Count; ++i) { var objectID = asset.includedObjects[i]; HashSet <string> bundles; objectToBundles.GetOrAdd(objectID, out bundles); bundles.Add(dependencies[0]); HashSet <GUID> assets; objectToAssets.GetOrAdd(objectID, out assets); assets.Add(asset.asset); } } foreach (var referenceID in asset.referencedObjects) { if (!aggressive && input.assetToBundles.ContainsKey(referenceID.guid)) { continue; } if (referenceID.filePath == BuildWriteProcessor.kUnityDefaultResourcePath) { continue; } HashSet <string> bundles; objectToBundles.GetOrAdd(referenceID, out bundles); bundles.Add(dependencies[0]); HashSet <GUID> assets; objectToAssets.GetOrAdd(referenceID, out assets); assets.Add(asset.asset); } } if (!UpdateProgressBar("Finding set of reused objects")) { EndProgressBar(); return(BuildPipelineCodes.Canceled); } // Generate the set of reused objects var hashToObjects = new Dictionary <Hash128, List <ObjectIdentifier> >(); foreach (var objectPair in objectToBundles) { if (objectPair.Value.Count <= 1) { continue; } var bundleHash = HashingMethods.CalculateMD5Hash(objectPair.Value.ToArray()); List <ObjectIdentifier> objectIDs; hashToObjects.GetOrAdd(bundleHash, out objectIDs); objectIDs.Add(objectPair.Key); } if (!UpdateProgressBar("Creating shared object bundles")) { EndProgressBar(); return(BuildPipelineCodes.Canceled); } // Generate Shared Bundles foreach (var hashPair in hashToObjects) { // Generate Dependency Information for virtual asset var assetInfo = new AssetLoadInfo(); assetInfo.asset = new GUID(hashPair.Key.ToString()); assetInfo.address = hashPair.Key.ToString(); assetInfo.includedObjects = hashPair.Value.ToList(); assetInfo.referencedObjects = new List <ObjectIdentifier>(); assetInfo.includedObjects.Sort((x, y) => { if (x < y) { return(-1); } if (x > y) { return(1); } return(0); }); // Add new AssetLoadInfo for virtual asset output.assetInfo.Add(assetInfo.asset, assetInfo); var assetBundles = new List <string>(); assetBundles.Add(assetInfo.address); // Add new bundle as dependency[0] for virtual asset output.assetToBundles.Add(assetInfo.asset, assetBundles); var bundleAssets = new List <GUID>(); bundleAssets.Add(assetInfo.asset); // Add virtual asset to the list of assets for new bundle output.bundleToAssets.Add(assetInfo.address, bundleAssets); // Add virtual asset to lookup output.virtualAssets.Add(assetInfo.asset); foreach (var objectID in assetInfo.includedObjects) { // Add objects in virtual asset to lookup output.objectToVirtualAsset.Add(objectID, assetInfo.asset); var assets = objectToAssets[objectID]; foreach (var asset in assets) { if (!output.assetToBundles.TryGetValue(asset, out assetBundles)) { continue; } if (assetBundles.Contains(assetInfo.address)) { continue; } // Add new bundle as dependency to assets referencing virtual asset objects assetBundles.Add(assetInfo.address); } } } // Generate Shared Bundle Build Dependencies foreach (var virtualAsset in output.virtualAssets) { var assetInfo = output.assetInfo[virtualAsset]; var dependencies = output.assetToBundles[virtualAsset]; var references = BundleBuildInterface.GetPlayerDependenciesForObjects(assetInfo.includedObjects.ToArray(), settings.target, settings.typeDB); foreach (var reference in references) { GUID dependency; List <string> bundles; string depStr = ""; // If the reference is to an object in a virtual asset, no major checks, just add it as a dependency if (output.objectToVirtualAsset.TryGetValue(reference, out dependency)) { if (dependency == virtualAsset) { continue; } depStr = dependency.ToString(); } // Otherwise if this reference is part of an asset assigned to a bundle, then set the bundle as a dependency to the virtual asset else if (output.assetToBundles.TryGetValue(reference.guid, out bundles)) { if (bundles.IsNullOrEmpty()) { continue; } depStr = bundles[0]; } if (dependencies.Contains(depStr)) { continue; } dependencies.Add(depStr); } } if (UseCache && !BuildCache.SaveCachedResults(hash, output)) { BuildLogger.LogWarning("Unable to cache SharedObjectProcessor results."); } if (!EndProgressBar()) { return(BuildPipelineCodes.Canceled); } return(BuildPipelineCodes.Success); }
private unsafe IAsset BuildAsset(AssetLoadInfo loadInfo) { var fileData = loadInfo.FileSystem.ReadAllBytes(loadInfo.LoadPath); var objLoaderFactory = new ObjLoaderFactory(); var objLoader = objLoaderFactory.Create(new MyMaterialStreamProvider(Path.GetDirectoryName(loadInfo.LoadPath), loadInfo.FileSystem)); LoadResult objLoadResult; using (var stream = new MemoryStream(fileData)) objLoadResult = objLoader.Load(stream); var anyTextures = objLoadResult.Textures.Any(); var initialMediatorIndices = new int?[objLoadResult.Vertices.Count]; var mediators = new List <VertexMediator>(); var faceMediatorIndices = new List <int>(); var indexList = new List <int>(); var materials = new List <IStandardMaterial>(); var modelParts = new List <FlexibleModelPart>(); foreach (var grp in objLoadResult.Groups) { var startIndexLocation = indexList.Count; foreach (var face in grp.Faces) { faceMediatorIndices.Clear(); foreach (var fv in face.EnumerateVertices()) { var newMediator = new VertexMediator { PositionIndex = fv.VertexIndex - 1, NormalIndex = fv.NormalIndex - 1, TexCoordIndex = anyTextures ? fv.TextureIndex - 1 : 0 }; var initialIndex = initialMediatorIndices[newMediator.PositionIndex]; if (!initialIndex.HasValue) { var mediatorIndex = mediators.Count; mediators.Add(newMediator); faceMediatorIndices.Add(mediatorIndex); initialMediatorIndices[newMediator.PositionIndex] = mediatorIndex; } else { var mediatorIndex = initialIndex.Value; var oldMediator = mediators[mediatorIndex]; while (true) { if (oldMediator.PositionIndex == newMediator.PositionIndex && oldMediator.NormalIndex == newMediator.NormalIndex && oldMediator.TexCoordIndex == newMediator.TexCoordIndex) { break; } if (!oldMediator.NextMediator.HasValue) { mediatorIndex = mediators.Count; mediators.Add(newMediator); oldMediator.NextMediator = mediatorIndex; break; } mediatorIndex = oldMediator.NextMediator.Value; oldMediator = mediators[mediatorIndex]; } faceMediatorIndices.Add(mediatorIndex); } } if (faceMediatorIndices.Count <= 3) { for (int i = 0; i < faceMediatorIndices.Count - 3; i++) { indexList.Add(faceMediatorIndices[0]); } foreach (var mi in faceMediatorIndices) { indexList.Add(mi); } } else { for (int i = 0; i < faceMediatorIndices.Count - 2; i++) { indexList.Add(faceMediatorIndices[0]); indexList.Add(faceMediatorIndices[i + 1]); indexList.Add(faceMediatorIndices[i + 2]); } } } var indexCount = indexList.Count - startIndexLocation; var color = grp.Material != null ? new Color4( grp.Material.DiffuseColor.X, grp.Material.DiffuseColor.Y, grp.Material.DiffuseColor.Z) : (Color4?)null; // todo: use material modelParts.Add(new FlexibleModelPart { VertexSetIndex = 0, ModelMaterialName = grp.Material?.Name ?? "DefaultMaterial", PrimitiveTopology = FlexibleModelPrimitiveTopology.TriangleList, IndexCount = indexCount, FirstIndex = startIndexLocation }); } VertexPosNormTex[] finalVertices; int[] finalIndices; if (objLoadResult.Normals.Count > 0) { var vertices = mediators.Select(m => new VertexPosNormTex()).ToArray(); for (int i = 0; i < mediators.Count; i++) { var mediator = mediators[i]; vertices[i].Position = objLoadResult.Vertices[mediator.PositionIndex].ToClarity(); vertices[i].Normal = objLoadResult.Normals[mediator.NormalIndex].ToClarity(); if (anyTextures) { vertices[i].TexCoord = objLoadResult.Textures[mediator.TexCoordIndex].ToClarity(); } } finalVertices = vertices; finalIndices = indexList.ToArray(); } else { var newIndices = Enumerable.Range(0, indexList.Count).ToArray(); var newVertices = new VertexPosNormTex[newIndices.Length]; for (int i = 0; i + 2 < indexList.Count; i += 3) { var mediator0 = mediators[indexList[i]]; var mediator1 = mediators[indexList[i + 1]]; var mediator2 = mediators[indexList[i + 2]]; var pos0 = objLoadResult.Vertices[mediator0.PositionIndex].ToClarity(); var pos1 = objLoadResult.Vertices[mediator1.PositionIndex].ToClarity(); var pos2 = objLoadResult.Vertices[mediator2.PositionIndex].ToClarity(); newVertices[i] = new VertexPosNormTex { Position = pos0, Normal = -Vector3.Cross(pos2 - pos0, pos1 - pos0).Normalize(), TexCoord = new Vector2(0.3f, 0.3f) }; newVertices[i + 1] = new VertexPosNormTex { Position = pos1, Normal = -Vector3.Cross(pos0 - pos1, pos2 - pos1).Normalize(), TexCoord = new Vector2(0.7f, 0.3f) }; newVertices[i + 2] = new VertexPosNormTex { Position = pos2, Normal = -Vector3.Cross(pos1 - pos2, pos0 - pos2).Normalize(), TexCoord = new Vector2(0.5f, 0.7f) }; } finalVertices = newVertices; finalIndices = newIndices; } var pack = new ResourcePack(ResourceVolatility.Immutable); IRawDataResource vertexRawData; fixed(VertexPosNormTex *pVertices = finalVertices) vertexRawData = new RawDataResource(ResourceVolatility.Immutable, (IntPtr)pVertices, sizeof(VertexPosNormTex) * finalVertices.Length); pack.AddSubresource("VertexRawData", vertexRawData); IRawDataResource indexRawData; fixed(int *pIndices = finalIndices) indexRawData = new RawDataResource(ResourceVolatility.Immutable, (IntPtr)pIndices, sizeof(int) * finalIndices.Length); pack.AddSubresource("IndexRawData", indexRawData); var arraySubranges = new [] { vertexRawData.GetSubrange(0), indexRawData.GetSubrange(0) }; var elementInfos = VertexPosNormTex.GetElementsInfos(0); var indicesInfo = new VertexIndicesInfo(1, CommonFormat.R32_UINT); var vertexSet = new FlexibleModelVertexSet(ResourceVolatility.Immutable, arraySubranges, elementInfos, indicesInfo); pack.AddSubresource("VertexSet", vertexSet); var sphere = Sphere.BoundingSphere(finalVertices, x => x.Position); var model = new FlexibleModel(ResourceVolatility.Immutable, new [] { vertexSet }, modelParts, sphere); pack.AddSubresource("Model", model); pack.MainSubresource = model; var hash = AssetHashMd5.FromSingleFile(fileData); var fileName = Path.GetFileName(loadInfo.LoadPath); return(new Asset(loadInfo.AssetName, pack, AssetStorageType.CopyLocal, hash, loadInfo.ReferencePath, fileName)); }
public ReturnCode Run() { var globalUsage = m_DependencyData.GlobalUsage; foreach (SceneDependencyInfo sceneInfo in m_DependencyData.SceneInfo.Values) { globalUsage |= sceneInfo.globalUsage; } if (m_SpriteData == null) { m_SpriteData = new BuildSpriteData(); } IList <CachedInfo> cachedInfo = null; List <CachedInfo> uncachedInfo = null; if (m_Parameters.UseCache && m_Cache != null) { IList <CacheEntry> entries = m_Content.Assets.Select(m_Cache.GetCacheEntry).ToList(); m_Cache.LoadCachedData(entries, out cachedInfo); uncachedInfo = new List <CachedInfo>(); } for (int i = 0; i < m_Content.Assets.Count; i++) { GUID asset = m_Content.Assets[i]; string assetPath = AssetDatabase.GUIDToAssetPath(asset.ToString()); AssetLoadInfo assetInfo; BuildUsageTagSet usageTags; SpriteImporterData importerData; if (cachedInfo != null && cachedInfo[i] != null) { if (!m_Tracker.UpdateInfoUnchecked(string.Format("{0} (Cached)", assetPath))) { return(ReturnCode.Canceled); } assetInfo = cachedInfo[i].Data[0] as AssetLoadInfo; usageTags = cachedInfo[i].Data[1] as BuildUsageTagSet; importerData = cachedInfo[i].Data[2] as SpriteImporterData; } else { if (!m_Tracker.UpdateInfoUnchecked(assetPath)) { return(ReturnCode.Canceled); } assetInfo = new AssetLoadInfo(); usageTags = new BuildUsageTagSet(); importerData = null; assetInfo.asset = asset; var includedObjects = ContentBuildInterface.GetPlayerObjectIdentifiersInAsset(asset, m_Parameters.Target); assetInfo.includedObjects = new List <ObjectIdentifier>(includedObjects); var referencedObjects = ContentBuildInterface.GetPlayerDependenciesForObjects(includedObjects, m_Parameters.Target, m_Parameters.ScriptInfo); assetInfo.referencedObjects = new List <ObjectIdentifier>(referencedObjects); ContentBuildInterface.CalculateBuildUsageTags(referencedObjects, includedObjects, globalUsage, usageTags, m_DependencyData.DependencyUsageCache); var importer = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (importer != null && importer.textureType == TextureImporterType.Sprite) { importerData = new SpriteImporterData(); importerData.PackedSprite = !string.IsNullOrEmpty(importer.spritePackingTag); importerData.SourceTexture = includedObjects.First(); } if (uncachedInfo != null) { uncachedInfo.Add(GetCachedInfo(asset, assetInfo, usageTags, importerData)); } } SetOutputInformation(asset, assetInfo, usageTags, importerData); } if (m_SpriteData.ImporterData.Count == 0) { m_SpriteData = null; } if (m_Parameters.UseCache && m_Cache != null) { m_Cache.SaveCachedData(uncachedInfo); } return(ReturnCode.Success); }
public ReturnCode Run() { var globalUsage = m_DependencyData.GlobalUsage; foreach (SceneDependencyInfo sceneInfo in m_DependencyData.SceneInfo.Values) { globalUsage |= sceneInfo.globalUsage; } if (m_SpriteData == null) { m_SpriteData = new BuildSpriteData(); } if (m_ExtendedAssetData == null) { m_ExtendedAssetData = new BuildExtendedAssetData(); } IList <CachedInfo> cachedInfo = null; List <CachedInfo> uncachedInfo = null; if (m_Parameters.UseCache && m_Cache != null) { IList <CacheEntry> entries = m_Content.Assets.Select(x => m_Cache.GetCacheEntry(x, Version)).ToList(); m_Cache.LoadCachedData(entries, out cachedInfo); uncachedInfo = new List <CachedInfo>(); } for (int i = 0; i < m_Content.Assets.Count; i++) { GUID asset = m_Content.Assets[i]; string assetPath = AssetDatabase.GUIDToAssetPath(asset.ToString()); AssetLoadInfo assetInfo; BuildUsageTagSet usageTags; SpriteImporterData importerData; ExtendedAssetData assetData; if (cachedInfo != null && cachedInfo[i] != null) { if (!m_Tracker.UpdateInfoUnchecked(string.Format("{0} (Cached)", assetPath))) { return(ReturnCode.Canceled); } assetInfo = cachedInfo[i].Data[0] as AssetLoadInfo; usageTags = cachedInfo[i].Data[1] as BuildUsageTagSet; importerData = cachedInfo[i].Data[2] as SpriteImporterData; assetData = cachedInfo[i].Data[3] as ExtendedAssetData; } else { if (!m_Tracker.UpdateInfoUnchecked(assetPath)) { return(ReturnCode.Canceled); } assetInfo = new AssetLoadInfo(); usageTags = new BuildUsageTagSet(); importerData = null; assetData = null; assetInfo.asset = asset; var includedObjects = ContentBuildInterface.GetPlayerObjectIdentifiersInAsset(asset, m_Parameters.Target); assetInfo.includedObjects = new List <ObjectIdentifier>(includedObjects); var referencedObjects = ContentBuildInterface.GetPlayerDependenciesForObjects(includedObjects, m_Parameters.Target, m_Parameters.ScriptInfo); assetInfo.referencedObjects = new List <ObjectIdentifier>(referencedObjects); var allObjects = new List <ObjectIdentifier>(includedObjects); allObjects.AddRange(referencedObjects); ContentBuildInterface.CalculateBuildUsageTags(allObjects.ToArray(), includedObjects, globalUsage, usageTags, m_DependencyData.DependencyUsageCache); var importer = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (importer != null && importer.textureType == TextureImporterType.Sprite) { // Legacy Sprite Packing Modes if (EditorSettings.spritePackerMode == SpritePackerMode.AlwaysOn || EditorSettings.spritePackerMode == SpritePackerMode.BuildTimeOnly) { importerData = new SpriteImporterData(); importerData.PackedSprite = !string.IsNullOrEmpty(importer.spritePackingTag); importerData.SourceTexture = includedObjects.First(); } else if (!referencedObjects.IsNullOrEmpty()) // Sprite is referencing packed data { importerData = new SpriteImporterData(); importerData.PackedSprite = EditorSettings.spritePackerMode != SpritePackerMode.Disabled; importerData.SourceTexture = includedObjects.First(); } } var representations = AssetDatabase.LoadAllAssetRepresentationsAtPath(assetPath); if (!representations.IsNullOrEmpty()) { assetData = new ExtendedAssetData(); foreach (var representation in representations) { if (AssetDatabase.IsMainAsset(representation)) { continue; } string guid; long localId; if (!AssetDatabase.TryGetGUIDAndLocalFileIdentifier(representation, out guid, out localId)) { continue; } assetData.Representations.AddRange(includedObjects.Where(x => x.localIdentifierInFile == localId)); } } if (uncachedInfo != null) { uncachedInfo.Add(GetCachedInfo(asset, assetInfo, usageTags, importerData, assetData)); } } SetOutputInformation(asset, assetInfo, usageTags, importerData, assetData); } if (m_SpriteData.ImporterData.Count == 0) { m_SpriteData = null; } if (m_ExtendedAssetData.ExtendedData.Count == 0) { m_SpriteData = null; } if (m_Parameters.UseCache && m_Cache != null) { m_Cache.SaveCachedData(uncachedInfo); } return(ReturnCode.Success); }
private static AssetLoadResultByLoader Load(AssetLoadInfo loadInfo, void *dicomManager) { int width, height, depth; CheckSuccess(DicomProject.AnalyzerGetDimensions(dicomManager, 1, &width, &height, &depth)); var lowerBuffer = new byte[width * height]; var higherBuffer = new byte[width * height]; var vertexList = new List <VertexPosNormTex>(); fixed(byte *pBuffer = higherBuffer) { int bufferSize = higherBuffer.Length; int bytesWritten; CheckSuccess(DicomProject.AnalyzerGetMonochromePixelDataBufferOfSlice(dicomManager, 1, pBuffer, &bufferSize, &bytesWritten)); } for (int z = 1; z < depth; z++) { CodingHelper.Swap(ref lowerBuffer, ref higherBuffer); fixed(byte *pBuffer = higherBuffer) { int bufferSize = higherBuffer.Length; int bytesWritten; CheckSuccess(DicomProject.AnalyzerGetMonochromePixelDataBufferOfSlice(dicomManager, z + 1, pBuffer, &bufferSize, &bytesWritten)); } for (int y = 0; y < height - 1; y++) { for (int x = 0; x < width - 1; x++) { var vx = (100f / width) * x - 50f; var vy = (100f / height) * y - 50f; var vz = (100f / depth) * z - 50f; var yStride = width; var mcCube = new MCCubeCornerScalarStruct { CubeDim = new IrtPtType(100.0 / width, 100.0 / height, 100.0 / depth), Vrtx0Lctn = new IrtPtType(vx, vy, vz) }; mcCube.Corners[0] = UNormToDouble(lowerBuffer[yStride * y + x]); mcCube.Corners[1] = UNormToDouble(lowerBuffer[yStride * y + (x + 1)]); mcCube.Corners[2] = UNormToDouble(lowerBuffer[yStride * (y + 1) + (x + 1)]); mcCube.Corners[3] = UNormToDouble(lowerBuffer[yStride * (y + 1) + x]); mcCube.Corners[4] = UNormToDouble(higherBuffer[yStride * y + x]); mcCube.Corners[5] = UNormToDouble(higherBuffer[yStride * y + (x + 1)]); mcCube.Corners[6] = UNormToDouble(higherBuffer[yStride * (y + 1) + (x + 1)]); mcCube.Corners[7] = UNormToDouble(higherBuffer[yStride * (y + 1) + x]); // todo: use ref instead EstimateGradient(&mcCube); var MCPolys = Irit.MCThresholdCube(&mcCube, 0.5); while (MCPolys != null) { var texCoord = new Vector2((float)x / width, (float)z / depth); var vertex0 = MCPolys->GetClarityVertex(0, texCoord); var vertexCurr = MCPolys->GetClarityVertex(1, texCoord); for (var i = 2; i < MCPolys->NumOfVertices; i++) { var vertexPrev = vertexCurr; vertexCurr = MCPolys->GetClarityVertex(i, texCoord); vertexList.Add(vertex0); vertexList.Add(vertexPrev); vertexList.Add(vertexCurr); } //Irit.IritFree(MCPolys); MCPolys = MCPolys->Pnext; } } } } var pack = new ResourcePack(ResourceVolatility.Immutable); var rawVerticesData = new RawDataResource(ResourceVolatility.Immutable, vertexList.Count * sizeof(VertexPosNormTex)); pack.AddSubresource("VertexData", rawVerticesData); var pRawData = (VertexPosNormTex *)rawVerticesData.Map(); for (int i = 0; i < vertexList.Count; i++) { pRawData[i] = vertexList[i]; } rawVerticesData.Unmap(true); var vertexSet = new FlexibleModelVertexSet(ResourceVolatility.Immutable, new[] { new RawDataResSubrange(rawVerticesData, 0) }, VertexPosNormTex.GetElementsInfos(0), null); pack.AddSubresource("ModelVertexSet", vertexSet); var modelPart = new FlexibleModelPart { IndexCount = vertexList.Count, PrimitiveTopology = FlexibleModelPrimitiveTopology.TriangleList, VertexSetIndex = 0 }; var model = new FlexibleModel(ResourceVolatility.Immutable, new[] { vertexSet }, new[] { modelPart }, new Sphere(Vector3.Zero, 50)); pack.AddSubresource("Model", model); pack.MainSubresource = model; CheckSuccess(DicomProject.AnalyzerKillDicomAnalyzer(&dicomManager)); // todo: calculate hash honestly var hash = AssetHashMd5.Random(new Random()); var fileName = Path.GetFileName(loadInfo.LoadPath); var asset = new Asset(loadInfo.AssetName, pack, AssetStorageType.ReferenceOriginal, hash, loadInfo.ReferencePath, fileName); return(AssetLoadResultByLoader.Success(asset)); }
// Traverse function iterates the scene graph to build local branches on Unity GameObject Traverse(Node n, Material currentMaterial) { if (n == null || !n.IsValid()) { return(null); } string name = n.GetName(); if (String.IsNullOrEmpty(name)) { name = n.GetNativeTypeName(); } GameObject gameObject = new GameObject(name); var nodeHandle = gameObject.AddComponent <NodeHandle>(); nodeHandle.node = n; nodeHandle.inObjectDict = false; // ---------------------------- Check material state ---------------------------------- if (n.HasState()) { State state = n.State; if (state.HasTexture(0) && state.GetMode(StateMode.TEXTURE) == StateModeActivation.ON) { gzTexture texture = state.GetTexture(0); if (texture.HasImage()) { gzImage image = texture.GetImage(); int depth = (int)image.GetDepth(); int width = (int)image.GetWidth(); int height = (int)image.GetHeight(); if (depth == 1) { if (currentMaterial == null) { currentMaterial = new Material(Shader); } TextureFormat format = TextureFormat.ARGB32; ImageType image_type = image.GetImageType(); switch (image_type) { case ImageType.RGB_8_DXT1: format = TextureFormat.DXT1; break; } Texture2D tex = new Texture2D(width, height, format, false); byte[] image_data; image.GetImageArray(out image_data); tex.LoadRawTextureData(image_data); tex.filterMode = FilterMode.Trilinear; tex.Apply(); currentMaterial.mainTexture = tex; } image.Dispose(); } texture.Dispose(); } state.Dispose(); } // ---------------------------- Transform check ------------------------------------- gzTransform tr = n as gzTransform; if (tr != null) { Vec3 translation; if (tr.GetTranslation(out translation)) { Vector3 trans = new Vector3(translation.x, translation.y, translation.z); gameObject.transform.localPosition = trans; } } // ---------------------------- DynamicLoader check ------------------------------------- DynamicLoader dl = n as DynamicLoader; if (dl != null) { if (!nodeHandle.inObjectDict) { AddGameObjectReference(dl.GetNativeReference(), gameObject); nodeHandle.inObjectDict = true; } } // ---------------------------- Lod check ------------------------------------- Lod ld = n as Lod; if (ld != null) { foreach (Node child in ld) { GameObject go_child = Traverse(child, currentMaterial); NodeHandle h = go_child.GetComponent <NodeHandle>(); if (h != null) { if (!h.inObjectDict) { AddGameObjectReference(h.node.GetNativeReference(), go_child); h.node.AddActionInterface(_actionReceiver, NodeActionEvent.IS_TRAVERSABLE); h.node.AddActionInterface(_actionReceiver, NodeActionEvent.IS_NOT_TRAVERSABLE); h.inObjectDict = true; } } go_child.transform.SetParent(gameObject.transform, false); } // Dont process group return(gameObject); } // ---------------------------- Roi check ------------------------------------- Roi roi = n as Roi; if (roi != null) { nodeHandle.updateTransform = true; foreach (Node child in roi) { GameObject go_child = Traverse(child, currentMaterial); NodeHandle h = go_child.GetComponent <NodeHandle>(); if (h != null) { if (!h.inObjectDict) { AddGameObjectReference(h.node.GetNativeReference(), go_child); h.node.AddActionInterface(_actionReceiver, NodeActionEvent.IS_TRAVERSABLE); h.node.AddActionInterface(_actionReceiver, NodeActionEvent.IS_NOT_TRAVERSABLE); h.inObjectDict = true; } } go_child.transform.SetParent(gameObject.transform, false); } // Dont process group return(gameObject); } // ---------------------------- RoiNode check ------------------------------------- RoiNode roinode = n as RoiNode; if (roinode != null) { nodeHandle.updateTransform = true; } // ---------------------------- Group check ------------------------------------- Group g = n as Group; if (g != null) { foreach (Node child in g) { GameObject go_child = Traverse(child, currentMaterial); go_child.transform.SetParent(gameObject.transform, false); } return(gameObject); } // ---------------------------ExtRef check ----------------------------------------- ExtRef ext = n as ExtRef; if (ext != null) { AssetLoadInfo info = new AssetLoadInfo(gameObject, ext.ResourceURL, ext.ObjectID); pendingAssetLoads.Push(info); } // ---------------------------- Geometry check ------------------------------------- Geometry geom = n as Geometry; if (geom != null) { float[] float_data; int[] indices; if (geom.GetVertexData(out float_data, out indices)) { MeshFilter filter = gameObject.AddComponent <MeshFilter>(); MeshRenderer renderer = gameObject.AddComponent <MeshRenderer>(); Mesh mesh = new Mesh(); Vector3[] vertices = new Vector3[float_data.Length / 3]; int float_index = 0; for (int i = 0; i < vertices.Length; i++) { vertices[i] = new Vector3(float_data[float_index], float_data[float_index + 1], float_data[float_index + 2]); float_index += 3; } mesh.vertices = vertices; mesh.triangles = indices; if (geom.GetColorData(out float_data)) { if (float_data.Length / 4 == vertices.Length) { float_index = 0; Color[] cols = new Color[vertices.Length]; for (int i = 0; i < vertices.Length; i++) { cols[i] = new Color(float_data[float_index], float_data[float_index + 1], float_data[float_index + 2], float_data[float_index + 3]); float_index += 4; } mesh.colors = cols; } } if (geom.GetNormalData(out float_data)) { if (float_data.Length / 3 == vertices.Length) { float_index = 0; Vector3[] normals = new Vector3[vertices.Length]; for (int i = 0; i < vertices.Length; i++) { normals[i] = new Vector3(float_data[float_index], float_data[float_index + 1], float_data[float_index + 2]); float_index += 3; } mesh.normals = normals; } } //else // mesh.RecalculateNormals(); uint texture_units = geom.GetTextureUnits(); if (texture_units > 0) { if (geom.GetTexCoordData(out float_data, 0)) { if (float_data.Length / 2 == vertices.Length) { float_index = 0; Vector2[] tex_coords = new Vector2[vertices.Length]; for (int i = 0; i < vertices.Length; i++) { tex_coords[i] = new Vector2(float_data[float_index], float_data[float_index + 1]); float_index += 2; } mesh.uv = tex_coords; } } if ((texture_units > 1) && geom.GetTexCoordData(out float_data, 1)) { if (float_data.Length / 2 == vertices.Length) { float_index = 0; Vector2[] tex_coords = new Vector2[vertices.Length]; for (int i = 0; i < vertices.Length; i++) { tex_coords[i] = new Vector2(float_data[float_index], float_data[float_index + 1]); float_index += 2; } mesh.uv2 = tex_coords; } } if ((texture_units > 2) && geom.GetTexCoordData(out float_data, 2)) { if (float_data.Length / 2 == vertices.Length) { float_index = 0; Vector2[] tex_coords = new Vector2[vertices.Length]; for (int i = 0; i < vertices.Length; i++) { tex_coords[i] = new Vector2(float_data[float_index], float_data[float_index + 1]); float_index += 2; } mesh.uv3 = tex_coords; } } if ((texture_units > 3) && geom.GetTexCoordData(out float_data, 3)) { if (float_data.Length / 2 == vertices.Length) { float_index = 0; Vector2[] tex_coords = new Vector2[vertices.Length]; for (int i = 0; i < vertices.Length; i++) { tex_coords[i] = new Vector2(float_data[float_index], float_data[float_index + 1]); float_index += 2; } mesh.uv4 = tex_coords; } } } filter.sharedMesh = mesh; renderer.sharedMaterial = currentMaterial; } } return(gameObject); }