public void CanWriteCustomData() { // Populate Values. var value = new MyCustomData(); value.aString = "IT'S ALIIIIIIIIIIIIIVE!"; value.anArrayOfInts = new int[] { 1, 2, 3, 4 }; value.aBoundingBox = new UnityEngine.Bounds(); // Writing the value. string usdFile = CreateTmpUsdFile("sceneFile.usda"); var scene = ImportHelpers.InitForOpen(usdFile); scene.Time = 1.0; scene.Write("/someValue", value); Debug.Log(scene.Stage.GetRootLayer().ExportToString()); scene.Save(); scene.Close(); Assert.IsTrue(File.Exists(usdFile), "File not found."); // Reading the value. Debug.Log(usdFile); var newValue = new MyCustomData(); scene = Scene.Open(usdFile); scene.Time = 1.0; scene.Read("/someValue", newValue); Assert.AreEqual(value.aString, newValue.aString, "Serialized data don't match the original data."); scene.Close(); }
public static void ExportModelTextures() { var rootDestinationDirPath = "TextureExport"; ImportHelpers.EnsureDirectoryExists(rootDestinationDirPath); var relativeModelsDirPath = Path.Combine("Assets", "GameAssets", "Models"); var modelsDir = new DirectoryInfo(relativeModelsDirPath); foreach (var subDir in modelsDir.EnumerateDirectories()) { var texturesDir = subDir.GetDirectories().FirstOrDefault(dir => dir.Name.ToLower() == "textures"); if (texturesDir == null) { continue; } var destinationDir = Path.Combine(rootDestinationDirPath, subDir.Name); ImportHelpers.EnsureDirectoryExists(destinationDir); foreach (var file in texturesDir.GetFiles().Where(file => file.Name.EndsWith(".asset"))) { string relativeAssetPath = Path.Combine(relativeModelsDirPath, subDir.Name, texturesDir.Name, file.Name) .ToAssetPath(); var asset = AssetDatabase.LoadAssetAtPath <Texture2D>(relativeAssetPath); if (asset == null) { continue; } File.WriteAllBytes(Path.Combine(destinationDir, asset.name + ".png"), asset.EncodeToPNG()); } } }
public void ImportAsGameObjects_SceneClosedAfterImport() { var scene = CreateTmpUsdWithData("dummyUsd.usda"); var root = ImportHelpers.ImportSceneAsGameObject(scene); Assert.IsNull(scene.Stage, "Scene was not closed after import."); }
private Material CreateMaterial(H3DMaterial spicaMaterial, List <Texture> unityTextures) { var material = ImportHelpers.CreateCharacterMaterial(ImportHelpers.GuessCharacterMaterialType(spicaMaterial.Name)); material.name = spicaMaterial.Name; material.mainTexture = unityTextures.First(t => t.name == spicaMaterial.Texture0Name); return(material); }
public void ImportAsGameObjects_ImportUnderParent() { var root = new GameObject("thisIsTheRoot"); var scene = CreateTmpUsdWithData("dummyUsd.usda"); var usdRoot = ImportHelpers.ImportSceneAsGameObject(scene, root); Assert.AreEqual(root.transform, usdRoot.transform.root, "UsdAsset is not a children of the given parent."); }
public void InitForOpenTest_InvalidPath_ThrowsAndLogs() { var ex = Assert.Throws <NullReferenceException>( delegate { ImportHelpers.InitForOpen("/this/is/an/invalid/path.usd"); }, "Opening a non existing file should throw an NullReferenceException"); Assert.That(ex.Message, Is.EqualTo("Null stage")); UnityEngine.TestTools.LogAssert.Expect(LogType.Exception, "ApplicationException: USD ERROR: Failed to open layer @/this/is/an/invalid/path.usd@"); }
public void ImportAsGameObjects_ImportAtRoot() { var scene = CreateTmpUsdWithData("dummyUsd.usda"); var root = ImportHelpers.ImportSceneAsGameObject(scene); bool usdRootIsRoot = Array.Find(SceneManager.GetActiveScene().GetRootGameObjects(), r => r == root); Assert.IsTrue(usdRootIsRoot, "UsdAsset GameObject is not a root GameObject."); }
public void ImportModel(PSMDImportManifest.Model modelManifest) { string path = Path.Combine(_manifest.PsmdPkGraphicPath, modelManifest.PsmdModel); var spicaHandle = H3D.Open(File.ReadAllBytes(path)); string targetDir = ImportHelpers.CreateDirectoryForImport(modelManifest.TargetName); string targetTexturesDir = Path.Combine(targetDir, "Textures"); string targetMaterialsDir = Path.Combine(targetDir, "Materials"); string targetMeshesDir = Path.Combine(targetDir, "Meshes"); ImportHelpers.EnsureDirectoryExists(targetTexturesDir); ImportHelpers.EnsureDirectoryExists(targetMaterialsDir); string modelPath = Path.Combine(targetDir, $"{modelManifest.TargetName}.dae"); new DAE(spicaHandle, 0).Save(modelPath); AssetDatabase.ImportAsset(modelPath.ToAssetPath()); var unityTextures = new List <Texture>(); foreach (var spicaTexture in spicaHandle.Textures) { var tempTexture = new Texture2D(spicaTexture.Width, spicaTexture.Height, TextureFormat.RGBA32, false); tempTexture.LoadRawTextureData(spicaTexture.ToRGBA()); var unityTexture = new Texture2D(tempTexture.width, tempTexture.height, TextureFormat.RGBA32, true); unityTexture.SetPixels(tempTexture.GetPixels()); // Workaround to get mipmaps unityTexture.Apply(true); AssetDatabase.CreateAsset(unityTexture, Path.Combine(targetTexturesDir, $"{spicaTexture.Name}.asset").ToAssetPath()); unityTextures.Add(unityTexture); } var modelImporter = AssetImporter.GetAtPath(modelPath.ToAssetPath()) as ModelImporter; if (modelImporter == null) { throw new Exception("Couldn't import model."); } var spicaMaterials = spicaHandle.Models[0].Materials; foreach (var spicaMaterial in spicaMaterials) { var material = CreateMaterial(spicaMaterial, unityTextures); AssetDatabase.CreateAsset(material, Path.Combine(targetMaterialsDir, $"{spicaMaterial.Name}.asset").ToAssetPath()); modelImporter.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(Material), material.name + "_mat"), material); } modelImporter.SaveAndReimport(); string prefabPath = Path.Combine(targetDir, $"{modelManifest.TargetName}.prefab").ToAssetPath(); ImportHelpers.GeneratePrefabForModel(modelPath, prefabPath, targetMeshesDir); AssetImporter.GetAtPath(prefabPath).assetBundleName = modelManifest.TargetName; }
public void InitForOpenTest_ValidPath_Succeeds() { var dummyUsdPath = CreateTmpUsdFile("dummyUsd.usda"); var scene = ImportHelpers.InitForOpen(dummyUsdPath); Assert.NotNull(scene); Assert.NotNull(scene.Stage); scene.Close(); }
public void SetUp() { InitUsd.Initialize(); var usdPath = Path.GetFullPath(AssetDatabase.GUIDToAssetPath(m_usdGUID)); var stage = pxr.UsdStage.Open(usdPath, pxr.UsdStage.InitialLoadSet.LoadNone); var scene = Scene.Open(stage); m_usdRoot = ImportHelpers.ImportSceneAsGameObject(scene); scene.Close(); }
Scene CreateTmpUsdWithData(string fileName) { var dummyUsdPath = CreateTmpUsdFile(fileName); var scene = ImportHelpers.InitForOpen(dummyUsdPath); scene.Write("/root", new XformSample()); scene.Write("/root/sphere", new SphereSample()); scene.Save(); return(scene); }
public void ImportAsGameObjects_ImportClosedScene_LogsError() { var rootGOsBefore = SceneManager.GetActiveScene().GetRootGameObjects(); var scene = CreateTmpUsdWithData("dummyUsd.usda"); scene.Close(); var root = ImportHelpers.ImportSceneAsGameObject(scene); Assert.IsNull(root); UnityEngine.TestTools.LogAssert.Expect(LogType.Error, "The USD Scene needs to be opened before being imported."); }
public void SetUp() { InitUsd.Initialize(); var usdPath = Path.GetFullPath(AssetDatabase.GUIDToAssetPath(m_usdGUID)); var stage = pxr.UsdStage.Open(usdPath, pxr.UsdStage.InitialLoadSet.LoadNone); var scene = Scene.Open(stage); var importOptions = new SceneImportOptions(); importOptions.materialImportMode = MaterialImportMode.ImportPreviewSurface; m_usdRoot = ImportHelpers.ImportSceneAsGameObject(scene, importOptions: importOptions); scene.Close(); }
private void Save() { var fileName = _file.DestinationFile.FullName; if (_file.DestinationFile.Exists) { ((FileInfo)_file.DestinationFile).CopyTo(fileName + ".bak", true); } ImportHelpers.EnsureDirectoryExists(Path.GetDirectoryName(fileName)); File.WriteAllText(fileName, _script.ToString()); Debug.Log("Saved to " + fileName); }
public void Setup() { InitUsd.Initialize(); var usdPath = Path.GetFullPath(AssetDatabase.GUIDToAssetPath(k_USDGUID)); var stage = pxr.UsdStage.Open(usdPath, pxr.UsdStage.InitialLoadSet.LoadNone); var scene = Scene.Open(stage); m_usdRoot = ImportHelpers.ImportSceneAsGameObject(scene); scene.Close(); m_usdAsset = m_usdRoot.GetComponent <UsdAsset>(); Assume.That(m_usdAsset, Is.Not.Null, "Could not find USDAsset component on root gameobject."); }
public override void OnImportAsset(AssetImportContext ctx) { Debug.Log($"Importing G3D file: {ctx.assetPath}"); ImportHelpers.TimeBlockingOperation(); var baseName = Path.GetFileNameWithoutExtension(ctx.assetPath); var g3d = G3D.Read(ctx.assetPath); g3d.OutputStats(); var obj = ctx.ImportG3D(g3d, baseName); ctx.AddRandomMaterial(obj); ctx.SetMainObject(obj); }
/// <summary> /// Processes request to upload a CSV file of deals to be imported /// </summary> public static ImportSummary ImportFileData(ImportData fileData) { var jobStartTime = DateTime.Now; var importSummary = new ImportSummary(); IList <ImportError> importErrors = new List <ImportError>(); IList <ImportResult> importResults = new List <ImportResult>(); var importProperties = new Dictionary <string, object> { { "NoOfDeals", fileData.DealData.Count }, { "TotalSales", fileData.DealData.Count }, { "TopCar", fileData.DealData.Count }, { "TopDealership", fileData.DealData.Count } }; LogManager.WriteLog("Starting CSV Import", importProperties); var rowCount = 0; foreach (var deal in fileData.DealData) { rowCount++; try { //We can save Deal in DB here var properties = new Dictionary <string, object>(deal.ColumnData.ToDictionary(k => k.Key, k => (object)k.Value)); LogManager.WriteLog("Created deal from CSV", deal); deal.Status = ImportDealStatus.Success; var newDeal = ImportHelpers.ConvertDictionaryTo <Deal>(deal.ColumnData); ImportHelpers.AddImportResultToList(ref importResults, rowCount, "Import", "Deal Added", newDeal); } catch (Exception e) { deal.Status = ImportDealStatus.Exception; deal.Disposition.Add(e.Message); ImportHelpers.AddImportErrorToList(ref importErrors, 0, "Import", e.Message); } } LogManager.WriteLog("Stopping CSV Import", importProperties); var jobEndTime = DateTime.Now; importSummary.ImportErrors = importErrors; importSummary.ImportResults = importResults; return(importSummary); }
private GameObject LoadUSD(Object usdObject, BasisTransformation changeHandedness = BasisTransformation.SlowAndSafeAsFBX) { InitUsd.Initialize(); var usdPath = Path.GetFullPath(AssetDatabase.GetAssetPath(usdObject)); var stage = pxr.UsdStage.Open(usdPath, pxr.UsdStage.InitialLoadSet.LoadNone); var scene = Scene.Open(stage); var importOptions = new SceneImportOptions(); importOptions.changeHandedness = changeHandedness; importOptions.scale = 0.01f; importOptions.materialImportMode = MaterialImportMode.ImportDisplayColor; var usdRoot = ImportHelpers.ImportSceneAsGameObject(scene, importOptions: importOptions); scene.Close(); return(usdRoot); }
public IActionResult ImportFileData() { var uploadFile = HttpContext.Request.Form.Files.GetFile("file"); var importSummary = new ImportSummary(); IList <ImportError> importErrors = new List <ImportError>(); if (ModelState.IsValid) { if (uploadFile != null) { try { var stream = uploadFile.OpenReadStream(); if (!uploadFile.FileName.EndsWith(".csv")) { //Shows error if uploaded file is not csv file ModelState.AddModelError("File", "This file format is not supported"); ImportHelpers.AddImportErrorToList(ref importErrors, 0, "Reading CSV", "This file format is not supported"); importSummary.ImportErrors = importErrors; return(Ok(importSummary)); } LogManager.WriteLog("CSV importing started..."); //Validate and excecute the complete csv file importSummary = _importService.ImportFileData(stream); LogManager.WriteLog("CSV importing completed..."); //Sending result data to View return(Ok(importSummary)); } catch (Exception e) { LogManager.WriteLog("CSV importing closing with errors...", e); ImportHelpers.AddImportErrorToList(ref importErrors, 0, "Reading CSV", "Could not read the file"); importSummary.ImportErrors = importErrors; return(Ok(importSummary)); } } } ModelState.AddModelError("File", "No file is selected"); ImportHelpers.AddImportErrorToList(ref importErrors, 0, "Reading CSV", "No file is selected"); return(Ok(importSummary)); }
public void ImportAsTimelineClipTest_ContentOk() { // Import as timeline clip should not create a hierarchy, only the root and the playable var scene = CreateTestAsset("dummyUsd.usda"); var assetPath = ImportHelpers.ImportAsTimelineClip(scene); Assert.IsNull(scene.Stage, "Scene was not closed after import."); m_assetsToDelete.Add(assetPath); Assert.IsTrue(File.Exists(assetPath)); var allObjects = AssetDatabase.LoadAllAssetsAtPath(assetPath); Assert.NotZero(allObjects.Length); bool playableAssetFound = false; int goCount = 0; int materialCount = 0; foreach (Object thisObject in allObjects) { Debug.Log(thisObject.name); Debug.Log(thisObject.GetType().Name); string myType = thisObject.GetType().Name; if (myType == "UsdPlayableAsset") { playableAssetFound = true; } else if (myType == "GameObject") { goCount += 1; } else if (myType == "Material") { materialCount += 1; } } Assert.IsTrue(playableAssetFound, "No PlayableAssset was found in the prefab."); Assert.AreEqual(1, goCount, "Wrong GameObjects count in the prefab."); // Only 3 default materials and no meshRenderer Assert.AreEqual(3, materialCount, "Wrong Materials count in the prefab"); }
public ImportSummary ImportFileData(Stream inputStream) { var fileData = ImportCSV.Parse(inputStream); var csvColumns = GetColumnSpec(CultureInfo.CurrentCulture.Name); //if (!PreValidate(csvColumns, fileData)) if (!PreValidate(csvColumns, fileData)) { IList <ImportError> importErrors = new List <ImportError>(); try { var rowCount = 0; var strErrors = ""; foreach (var deal in fileData.DealData.Where(l => l.Status == ImportDealStatus.Validation)) { rowCount++; strErrors = deal.Disposition.Aggregate(strErrors, (current, disposition) => current + ". " + disposition); } ImportHelpers.AddImportErrorToList(ref importErrors, rowCount, "Import", strErrors); } catch (Exception e) { LogManager.WriteLog("Error adding import validation erros", e); ImportHelpers.AddImportErrorToList(ref importErrors, 0, "Import", e.Message); } var importSummary = new ImportSummary { ImportErrors = importErrors }; return(importSummary); } else { var importSummary = ImportCSV.ImportFileData(fileData); importSummary.Summary = GetImportDBSummary(importSummary.ImportResults); return(importSummary); } }
public void ImportAsPrefabTest_ContentOk() { var scene = CreateTestAsset("dummyUsd.usda"); var assetPath = ImportHelpers.ImportAsPrefab(scene); Assert.IsNull(scene.Stage, "Scene was not closed after import."); m_assetsToDelete.Add(assetPath); Assert.IsTrue(File.Exists(assetPath)); var allObjects = AssetDatabase.LoadAllAssetsAtPath(assetPath); Assert.NotZero(allObjects.Length); bool playableAssetFound = false; int goCount = 0; int materialCount = 0; foreach (Object thisObject in allObjects) { string myType = thisObject.GetType().Name; if (myType == "UsdPlayableAsset") { playableAssetFound = true; } else if (myType == "GameObject") { goCount += 1; } else if (myType == "Material") { materialCount += 1; } } Assert.IsTrue(playableAssetFound, "No PlayableAssset was found in the prefab."); Assert.AreEqual(2, goCount, "Wrong GameObjects count in the prefab."); // The 3 default materials + 1 material per meshRender Assert.AreEqual(4, materialCount, "Wrong Materials count in the prefab"); }
public async Task <CommerceCommand> Process(CommerceContext commerceContext, List <MembershipPriceModel> model) { var policy = commerceContext.GetPolicy <TransactionsPolicy>(); policy.TransactionTimeOut = 10800000; // 3 * 3600 * 1000 = 3 hours in millis ImportMembershipPricesArgument result = null; using (CommandActivity.Start(commerceContext, this)) { var options = commerceContext.GetPipelineContextOptions(); var context = ImportHelpers.OptimizeContextForImport(new CommercePipelineExecutionContext(options, commerceContext.Logger)); var importMembershipPricesPolicy = commerceContext.GetPolicy <ImportMembershipPricesPolicy>(); await PerformTransaction( commerceContext, async() => { result = await importMembershipPricesPipeline.Run(new ImportMembershipPricesArgument(importMembershipPricesPolicy.PriceBookName, model, importMembershipPricesPolicy.CurrencySetId), commerceContext.GetPipelineContextOptions()) .ConfigureAwait(false); }).ConfigureAwait(false); } return(this); }
private void Save() { var sb = new StringBuilder(); foreach (var entry in _entries) { var asset = entry as PlacementDataAsset; string fullIdentifier = asset != null ? $"{asset.Type}:{asset.AssetType}:{asset.Name}" : entry.Type; string dataString = entry.Data.ToString(Formatting.None); sb.AppendLine($"{fullIdentifier}:{dataString}"); } var fileName = _file.DestinationFile.FullName; if (_file.DestinationFile.Exists) { ((FileInfo)_file.DestinationFile).CopyTo(fileName + ".bak", true); } ImportHelpers.EnsureDirectoryExists(Path.GetDirectoryName(fileName)); File.WriteAllText(fileName, sb.ToString()); Debug.Log("Saved to " + fileName); }
public void ImportListing(RestClient RestClient) { var dictListings = ImportHelpers.ImportTabDelimitedFile(@"C:\Internal\Etsy\listingimport.txt"); var gclient = InternalClientService.GetInternalClientByID(dictListings.Where(x => x.Key == 2).First().Value[0].ToString()); //GETTING SHIPPING TEMPLATE string shiptempId = ShippingTemplateService.GetShippingTemplateId(RestClient, gclient.EtsyUserName); //string status = ShippingTemplateService.CreateShippingTemplate(RestClient, "Test Shipping Template", countries.Where(x => x.Value == "United States").FirstOrDefault().Key.ToString(), "2.00", "1.00"); var countries = CountryService.GetCountryMapping(RestClient); foreach (var row in dictListings.Skip(1)) { if (row.Key != 1) { Console.WriteLine("CREATING A DRAFT LISTING"); var obj = row.Value; Listing testListing = new Listing { title = obj[1].ToString(), description = obj[2].ToString(), price = obj[3].ToString(), quantity = obj[7].ToString(), shipping_template_id = shiptempId, state = "draft", is_supply = "false", who_made = "i_did", when_made = "made_to_order", }; //var listing = CreateListing(RestClient, testListing); Console.WriteLine("CREATING A LISTING IMAGE"); string filepath = string.Format(@"C:\Internal\EtsyProductImages\{0}", obj[4].ToString()); //CreateListingItemImage(RestClient, listing, obj[4].ToString(), filepath); Console.WriteLine("CREATE LISTING VARIATIONS"); List <ListingVariation> variations = new List <ListingVariation>(); ListingVariation variation; List <string> sizes = new List <string> { "S", "M", "L", "XL", "XXL" }; string style = obj[6].ToString(); foreach (var size in sizes) { variation = new ListingVariation(); variation.property_id = "513"; //variation.is_available = "TRUE"; variation.value = string.Format("{0}-{1}", size, style); variations.Add(variation); } List <string> designs = obj[5].ToString().Split(';').ToList(); foreach (var design in designs) { string[] designcolor = design.Split(':'); variation = new ListingVariation(); variation.property_id = "200"; variation.value = string.Format("{0}-{1}", designcolor[0], designcolor[1]); variations.Add(variation); } string output = JsonConvert.SerializeObject(variations.ToArray()); //UpdateListingVariations(RestClient, listing, output); Console.WriteLine("Listing Created"); Thread.Sleep(1000); } } }
static void Main(string[] args) { //Just here for the purposes of alpha prototype stuff //UserService US = new UserService(); //User ushi = US.GetUser(client, "ushi84", true, false); const string consumerKey = ""; const string consumerSecret = ""; const string accessToken = ""; const string accessTokenSecret = ""; var client = new RestClient(); client.BaseUrl = AppKeys.GetBaseUri(); client.Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, accessToken, accessTokenSecret); ShopService SS = new ShopService(); ListingService LS = new ListingService(); UserService US = new UserService(); var Company = InternalClientService.GetInternalClientByID("646"); bool consoleApp = false; if (consoleApp) { //RestRequest request = new RestRequest("/oauth/scopes", Method.GET); //IRestResponse response = client.Execute(request); //JObject oq = JObject.Parse(response.Content); //Console.WriteLine(oq.ToString()); var command = Console.ReadLine(); var user = US.GetUser(client, "threadedtees", true, false); if (command.ToLower() == "getlistings") { RestRequest request = new RestRequest(); request.Resource = string.Format("/taxonomy/seller/get"); IRestResponse response = client.Execute(request); JObject o = JObject.Parse(response.Content); Console.WriteLine(o.ToString()); LS.ImportListing(client); Authorization.GetAccessToken(); var listings = SS.GetShopListings(client, Company.EtsyShopIDs.First()); //listring id //title //variation name //variation value ExportHelpers.ExportListingIdAndVariations(user.shops.FirstOrDefault().listings, @"C:\Internal\Etsy\ListingIdAndVariation.txt", true); } if (command.ToLower() == "createlistings") { ListingHelper.CreateEtsyListingFromCustomMapping(client, Company, @"C:\Internal\Etsy\CalculatedFailure_FirstTest_Amazon_Feed.txt"); } #region Listing Tool Code #endregion if (command.ToLower() == "download") { string path = @"C:\Internal\Etsy.txt"; var receipts = SS.GetOpenShopReceipts(client, Company.EtsyShopIDs.FirstOrDefault()); Console.WriteLine("Exporting..."); ExportHelpers.ExtractionExport(receipts, path, CountryService.GetCountryMapping(client), true); Console.Write("Export Complete"); } if (command.ToLower() == "upload") { ImportHelpers.ShippingSummaries(); Console.Write("Upload Complete"); Console.ReadLine(); } } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new DownloadUploadForm()); } #region Listing Creation Stuff #endregion }
public void InitForOpenTest_EmptyPath() { var scene = ImportHelpers.InitForOpen(""); Assert.IsNull(scene); }