void handleFetchThumbnailCallback(PolyAsset asset, PolyStatus status) { if (status.ok) { Debug.Log("handleFetchThumbnailCallback handled"); Debug.Log(asset.thumbnail); //RawImage newObj = (RawImage)Instantiate(img1,transform); //// newObj.SetActive(false); //Debug.Log(asset.name); //newObj.material.mainTexture = asset.thumbnailTexture; ////newObj.SetNativeSize(); Button newObj; newObj = (Button)Instantiate(b, transform); // newObj.AddComponent<ObjectClick>()=newObj; newObj.GetComponentInChildren <RawImage>().material.mainTexture = asset.thumbnailTexture; newObj.GetComponentInChildren <Text>().text = asset.displayName; newObj.name = asset.name; newObj.onClick.AddListener(() => getAssetByID(newObj.name)); newObj.gameObject.SetActive(true); } }
void handleFetchThumbnailCallback(PolyAsset asset, PolyStatus status) { if (status.ok) { Debug.Log("handleFetchThumbnailCallback handled"); Debug.Log(asset.thumbnail); GameObject newThumbnail = (GameObject)Instantiate(buttonPrefab, transform); //newThumbnail.tag = ""; Button[] buttonComponents = newThumbnail.GetComponentsInChildren <Button>(); Text[] textComponents = newThumbnail.GetComponentsInChildren <Text>(); Image[] imgComponents = newThumbnail.GetComponentsInChildren <Image>(); RawImage[] rawImgcomponent = newThumbnail.GetComponentsInChildren <RawImage>(); Debug.Log("Button components::::" + buttonComponents[0]); // shrink // Debug.Log("Text Components::::" + textComponents[0] + textComponents[1]); //expandtext, itemContentText Debug.Log("Text Components::::" + textComponents[0]); Debug.Log("Image Components::::" + imgComponents[0] + imgComponents[1] + imgComponents[2]); // Debug.Log("Image Components::::" + imgComponents[0] + imgComponents[1]+ imgComponents[2]+imgComponents[3]); // ListItem, Header, Shrink, ItemContent Debug.Log("Raw Image Components::::" + rawImgcomponent[0]); textComponents[0].text = asset.displayName; // textComponents[1].text = null; rawImgcomponent[0].material.mainTexture = asset.thumbnailTexture; rawImgcomponent[0].name = asset.name; rawImgcomponent[0].gameObject.AddComponent <ThumbnailMenuPerCategory>(); rawImgcomponent[0].gameObject.AddComponent <ClickImg>().thumbnailMenuBackgroundImg = this.thumbnailMenuBackgroundImage; rawImgcomponent[0].gameObject.AddComponent <ClickImg>().modelbackGroundImg = this.modelbackGroundImg; newThumbnail.gameObject.SetActive(true); } }
// Callback invoked when a thumbnail has just been fetched. private void FetchThumbnailCallback(PolyAsset asset, PolyStatus result) { if (!result.ok) { Debug.LogError("Failed to import thumbnail. :( Reason: " + result.errorMessage); return; } switch (thumbnailCount) // grab thumbnails of assets, assign as the UISprites to the buttons { case 0: Texture2D tex2D1 = assetsInPalette[0].thumbnailTexture; button1.image.sprite = Sprite.Create(tex2D1, new Rect(0.0f, 0.0f, tex2D1.width, tex2D1.height), new Vector2(0.5f, 0.5f)); break; case 1: Texture2D tex2D2 = assetsInPalette[1].thumbnailTexture; button2.image.sprite = Sprite.Create(tex2D2, new Rect(0.0f, 0.0f, tex2D2.width, tex2D2.height), new Vector2(0.5f, 0.5f)); break; case 2: Texture2D tex2D3 = assetsInPalette[2].thumbnailTexture; button3.image.sprite = Sprite.Create(tex2D3, new Rect(0.0f, 0.0f, tex2D3.width, tex2D3.height), new Vector2(0.5f, 0.5f)); break; case 3: Texture2D tex2D4 = assetsInPalette[3].thumbnailTexture; button4.image.sprite = Sprite.Create(tex2D4, new Rect(0.0f, 0.0f, tex2D4.width, tex2D4.height), new Vector2(0.5f, 0.5f)); break; } thumbnailCount++; statusText.text = "pick an asset to import"; }
void callback(PolyAsset asset, PolyStatus status) { if (status.ok) { CreateItems(asset); } }
void MyCallback_FetchThumbnail(PolyAsset asset, PolyStatus status) { if (!status.ok) { // Handle error; return; } Debug.Log("Hiiiiiiiiiiiiiiiiiiiiiiiiiiiii"); // Display the asset.thumbnailTexture. img = asset.thumbnailTexture; // get the asset // Request the asset. var buttonObj = Instantiate(ButtonPrefab); // buttonObj.gameObject.AddComponent<Collider>(); buttonObj.transform.SetParent(UiPanel, false); buttonObj.GetComponentInChildren <Text>().text = asset.displayName; Sprite s = Sprite.Create(img, new Rect(0.0f, 0.0f, img.width, img.height), new Vector2(0.5f, 0.5f), 100.0f); buttonObj.transform.GetChild(1).GetComponent <Image>().sprite = s; buttonObj.GetComponent <Button>().onClick.AddListener( () => buttonPressed(asset)); }
void PolyThumbnailCallback(PolyAsset asset, PolyStatus status, OnActorableSearchResult resultCallback) { if (!status.ok) { Debug.Log("There is a problem with poly stuff"); return; } ActorableSearchResult _newresult = new ActorableSearchResult(); _newresult.forceConcave = true; // Do this for Poly models, for now. _newresult.preferredRotation = Quaternion.identity; // Don't do any actor-level scaling for any of these hash tags if (asset.description.Contains(TerrainBlockHashtag) || asset.description.Contains(NoAutoFitHashtag)) { _newresult.preferredScaleFunction = _ => new Vector3(1f, 1f, 1f); } else { // Do some custom tuned actor scale. _newresult.preferredScaleFunction = CalculatePreferredScale; } _newresult.renderableReference.assetType = AssetType.Poly; _newresult.name = asset.displayName; _newresult.renderableReference.uri = new PolyVoosAsset(asset.name).GetUri(); _newresult.thumbnail = asset.thumbnailTexture; resultCallback(_newresult); }
/// <summary> /// Called when sign in finishes. /// </summary> /// <param name="wasInteractive">If true, this was the interactive (browser-based) sign-in flow.</param> /// <param name="status">The result of the sign in process.</param> private void OnSignInFinished(bool wasInteractive, PolyStatus status) { if (status.ok) { string tok = PolyApi.AccessToken; PtDebug.LogFormat("ABM: Sign in success. Access token: {0}", (tok != null && tok.Length > 6) ? tok.Substring(0, 6) + "..." : "INVALID"); PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_SIGN_IN_SUCCESS); } else if (wasInteractive) { Debug.LogErrorFormat("Failed to sign in. Please try again: " + status); PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_SIGN_IN_FAILURE, status.ToString()); } if (null != refreshCallback) { refreshCallback(); } // If we had a deferred request that was waiting for auth, send it now. if (requestToSendAfterAuth != null) { PtDebug.Log("Sending deferred request that was waiting for auth."); PolyRequest request = requestToSendAfterAuth; requestToSendAfterAuth = null; StartRequest(request); } }
private void GetThumbnailCallback(PolyAsset asset, PolyStatus status) { if (!status.ok) { Debug.LogError("Failed to import thumbnail. :( Reason: " + status); return; } //Debug.Log("Successfully imported thumbnail!"); // add thumbnail textures to list asset_thumbnail_list.Add(new KeyValuePair <string, Texture2D>(asset.name, asset.thumbnailTexture)); //Debug.Log("thumb list size " + asset_thumbnail_list.Count + " result count " + resultCount); if (asset_thumbnail_list.Count == resultCount) { //Debug.Log("THIS IS GETTING CALLED EACH SEARCH"); asset_thumbnail_list.Sort((x, y) => string.Compare(x.Key, y.Key, StringComparison.Ordinal)); if (onPolyThumbLoaded != null) { onPolyThumbLoaded.Invoke(); } } }
/// <summary> /// Imports the given format of the given asset, asynchronously in a background thread. /// Calls the supplied callback when done. /// </summary> public void ImportAsync(PolyAsset asset, PolyFormat format, PolyImportOptions options, AsyncImportCallback callback = null) { ImportOperation operation = new ImportOperation(); operation.instance = this; operation.asset = asset; operation.format = format; operation.options = options; operation.callback = callback; operation.status = PolyStatus.Success(); operation.loader = new FormatLoader(format); if (Application.isPlaying) { Task.Run(() => BackgroundThreadProc(operation)); //ThreadPool.QueueUserWorkItem(new WaitCallback(BackgroundThreadProc), operation); } else { // If we are in the editor, don't do this in a background thread. Do it directly // here on the main thread. BackgroundThreadProc(operation); Update(); } }
/// <summary> /// Processes the result of fetching an individual file. /// </summary> /// <param name="state">Indicates the state of the ongoing fetch operation (as set up in FetchObj).</param> /// <param name="index">If ROOT_FILE_INDEX, then this is a result for the main file; else this is a result for /// the resource file with that index.</param> /// <param name="status">The status indicating if the download succeed</param> /// <param name="data">The data that was downloaded.</param> private void ProcessFileFetchResult(FetchOperationState state, int index, PolyStatus status, byte[] data) { if (state.pendingFiles == 0) { // Another request for this format failed, so we ignore any further responses. return; } if (!status.ok) { // This request failed, so we set pendingFiles to 0 so we ignore any further responses, and callback with // an error message. state.pendingFiles = 0; state.completionCallback(state.asset, PolyStatus.Error(status, "Failed to fetch file #{0}", index)); return; } PolyFormat package = state.packageBeingFetched; PolyFile file = index == ROOT_FILE_INDEX ? package.root : package.resources[index]; file.contents = data; --state.pendingFiles; if (state.progressCallback != null) { state.progressCallback(state.asset, 1.0f - ((float)state.pendingFiles / state.totalFiles)); } if (state.pendingFiles <= 0) { // All files done, call callback indicating success. state.completionCallback(state.asset, PolyStatus.Success()); } }
/// <summary> /// Checks if the asset has the contents of the format to import, fetching them if need be; then imports /// the asset. /// </summary> /// <param name="asset">The asset who's format is being imported.</param> /// <param name="format">The format to import.</param> /// <param name="options">The import options for this asset.</param> /// <param name="callback">The callback to call when this is finished.</param> private void FetchAndImportFormat(PolyAsset asset, PolyFormat format, PolyImportOptions options, PolyApi.ImportCallback callback = null) { if (format.root.contents != null) { // If asset already has the gltf package, proceed directly to importing it. ImportFormat(asset, format, options, callback); } else { // Otherwise, first fetch the package and then import the model. FetchFormatFiles(asset, format.formatType, (PolyAsset resultAsset, PolyStatus status) => { PolyFormat fetchedFormat = resultAsset.GetFormatIfExists(format.formatType); if (fetchedFormat != null) { ImportFormat(asset, fetchedFormat, options, callback); } else { if (callback != null) { callback(asset, new PolyStatusOr <PolyImportResult>( PolyStatus.Error("Could not fetch format files for asset"))); } } }); } }
private void GetThumbCallback(PolyAsset asset, PolyStatus status) { Texture2D t = asset.thumbnailTexture; Sprite mySprite = Sprite.Create(t, new Rect(0.0f, 0.0f, t.width, t.height), new Vector2(0.5f, 0.5f), 100.0f); thumb.sprite = mySprite; thumb.preserveAspect = true; }
public void BackgroundWork() { JObject result; status = PolyClient.ParseResponse(response, out result); if (status.ok) { status = PolyClient.ParseAsset(result, out polyAsset); } }
public void BackgroundWork() { JObject result; status = PolyClient.ParseResponse(response, out result); if (status.ok) { status = PolyClient.ParseReturnedAssets(Encoding.UTF8.GetString(response), out polyListAssetsResult); } }
private void SetThumbnail(PolyAsset asset, PolyStatus status) { if (!status.ok) { Debug.Log("Fetching Thumbnail Error: " + status.errorMessage); return; } modelThumbnail.texture = asset.thumbnailTexture; }
private void CallFetchThumbnailEvent(PolyAsset result, PolyStatus status) { Debug.Log("CallFetchThumbnailEvent::::::::::::::::::::::::::"); if (status.ok) { Debug.Log("EVENTS::::::::::"); //event fetchThumbnailCallback(result, status); } }
/// <summary> /// Attempts to authenticate. /// </summary> /// <param name="interactive">If true, launch the sign in flow (browser) if necessary. If false, /// attempt to authenticate silently.</param> /// <param name="callback">Callback to call when authentication completes.</param> public void Authenticate(bool interactive, Action <PolyStatus> callback) { if (!instance.IsAuthenticationSupported) { callback(PolyStatus.Error("Authentication is not supported on this platform.")); } oauth2Identity.Login( () => { callback(PolyStatus.Success()); }, () => { callback(PolyStatus.Error("Authentication failed.")); }, interactive); }
void callback(PolyAsset asset, PolyStatus status) { GameObject newAnimal = Instantiate(ListItemPrefab) as GameObject; ListItemController controller = newAnimal.GetComponent<ListItemController>(); controller.Icon.GetComponent<Renderer>().material.mainTexture = asset.thumbnailTexture; controller.Name.GetComponent<TextMesh>().text = asset.displayName; newAnimal.transform.parent = ContentPanel.transform; newAnimal.transform.localScale = Vector3.one; }
/// <summary> /// Attempts to authenticate using the provided tokens. /// This will NOT launch a sign-in flow. It will use the given tokens directly. /// </summary> /// <param name="accessToken">The access token to use.</param> /// <param name="refreshToken">The refresh token to use.</param> /// <param name="callback">The callback to call when authentication completes.</param> public void Authenticate(string accessToken, string refreshToken, Action <PolyStatus> callback) { if (!instance.IsAuthenticationSupported) { callback(PolyStatus.Error("Authentication is not supported on this platform.")); } oauth2Identity.LoginWithTokens( () => { callback(PolyStatus.Success()); }, () => { callback(PolyStatus.Error("Authentication failed (with tokens).")); }, accessToken, refreshToken); }
/// <summary> /// Refreshes an access token, if a given refresh token is valid, and then calls one of the given callbacks. /// </summary> public void Reauthorize(Action <PolyStatus> callback) { if (!instance.IsAuthenticationSupported) { callback(PolyStatus.Error("Authentication is not supported on this platform.")); } CoroutineRunner.StartCoroutine(this, oauth2Identity.Reauthorize( successCallback: () => { callback(PolyStatus.Success()); }, failureCallback: (string error) => { callback(PolyStatus.Error(error)); } )); }
// Returns true if it is an error and it was logged. static bool MaybeLogError(string assetName, PolyStatus status) { if (status.ok) { return(false); } else { Debug.LogError($"Error trying to get Poly asset '{assetName}': {status.errorMessage}"); return(true); } }
/// <summary> /// Takes a string, representing either a ListAssetsResponse or ListUserAssetsResponse proto, and /// fills polyListResult with relevant fields from the response and returns a success status /// if the response is of the expected format, or a failure status if it's not. /// </summary> public static PolyStatus ParseReturnedAssets(string response, out PolyListAssetsResult polyListAssetsResult) { // Try and actually parse the string. JObject results = JObject.Parse(response); IJEnumerable <JToken> assets = results["assets"].AsJEnumerable(); // If assets is null, check for a userAssets object, which would be present if the response was // a ListUserAssets response. if (assets == null) { assets = results["userAssets"].AsJEnumerable(); } if (assets == null) { // Empty response means there were no assets that matched the request parameters. polyListAssetsResult = new PolyListAssetsResult(PolyStatus.Success(), /*totalSize*/ 0); return(PolyStatus.Success()); } List <PolyAsset> polyAssets = new List <PolyAsset>(); foreach (JToken asset in assets) { PolyAsset polyAsset; if (!(asset is JObject)) { Debug.LogWarningFormat("Ignoring asset since it's not a JSON object: " + asset); continue; } JObject jObjectAsset = (JObject)asset; if (asset["asset"] != null) { // If this isn't null, means we are parsing a ListUserAssets response, which has an added // layer of nesting. jObjectAsset = (JObject)asset["asset"]; } PolyStatus parseStatus = ParseAsset(jObjectAsset, out polyAsset); if (parseStatus.ok) { polyAssets.Add(polyAsset); } else { Debug.LogWarningFormat("Failed to parse a returned asset: {0}", parseStatus); } } var totalSize = results["totalSize"] != null?int.Parse(results["totalSize"].ToString()) : 0; var nextPageToken = results["nextPageToken"] != null ? results["nextPageToken"].ToString() : null; polyListAssetsResult = new PolyListAssetsResult(PolyStatus.Success(), totalSize, polyAssets, nextPageToken); return(PolyStatus.Success()); }
void FetchThumbnailCallback(PolyAsset asset, PolyStatus status) { if (!status.ok) { Debug.LogError("Failed to Fetch Thumbnail. Reason: " + status.errorMessage); statusText.text = "ERROR: " + status.errorMessage; return; } buttons[thumbnailCount].GetComponent <RawImage>().texture = asset.thumbnailTexture; buttons[thumbnailCount].GetComponent <Button>().onClick.AddListener(() => OnClickImportAsset(asset)); thumbnailCount++; //print(asset.displayName); }
private void AuthCallback(PolyStatus status) { if (status.ok) { PrintLn("Signed in successfully as {0}.", PolyApi.UserName); userProfileImage.sprite = PolyApi.UserIcon; userProfileImage.gameObject.SetActive(true); } else { PrintLn("Sign in FAILED: {0}", status); } }
/// <summary> /// As documented in PolyClient.ListUserAssets. /// </summary> public void ListLikedAssets(PolyListLikedAssetsRequest listLikedAssetsRequest, PolyApi.ListAssetsCallback callback) { polyClient.SendRequest(listLikedAssetsRequest, (PolyStatus status, PolyListAssetsResult polyListResult) => { if (status.ok) { ProcessRequestResult(polyListResult, callback); } else { callback(new PolyStatusOr <PolyListAssetsResult>(PolyStatus.Error(status, "Request failed"))); } }, /*maxCacheAge*/ WebRequestManager.CACHE_NONE); }
/// <summary> /// Fetch a specific Poly asset. /// </summary> /// <param name="id">The ID of the sought asset.</param> /// <param name="callback">The callback.</param> public void GetAsset(string id, PolyApi.GetAssetCallback callback) { polyClient.GetAsset(id, (PolyStatus status, PolyAsset result) => { if (status.ok) { callback(new PolyStatusOr <PolyAsset>(result)); } else { callback(new PolyStatusOr <PolyAsset>(PolyStatus.Error(status, "Failed to get asset {0}", id))); } }); }
/// <summary> /// As documented in PolyClient.ListAssets. /// </summary> public void ListAssets(PolyListAssetsRequest listAssetsRequest, PolyApi.ListAssetsCallback callback) { polyClient.SendRequest(listAssetsRequest, (PolyStatus status, PolyListAssetsResult polyListResult) => { if (status.ok) { ProcessRequestResult(polyListResult, callback); } else { callback(new PolyStatusOr <PolyListAssetsResult>(PolyStatus.Error(status, "Request failed"))); } }); }
/// <summary> /// Fetch a specific asset. /// </summary> /// <param name="assetId">The asset to be fetched.</param> /// <param name="callback">A callback to call with the result of the operation.</param> /// <param name="isRecursion"> /// If true, this is a recursive call to this function, and no further retries should be attempted. /// </param> public void GetAsset(string assetId, Action <PolyStatus, PolyAsset> callback, bool isRecursion = false) { // If the user passed in a raw asset ID (no "assets/" prefix), fix it. if (!assetId.StartsWith("assets/")) { assetId = "assets/" + assetId; } PolyMainInternal.Instance.webRequestManager.EnqueueRequest( () => { string url = String.Format("{0}/v1/{1}?key={2}", BASE_URL, assetId, PolyMainInternal.Instance.apiKey); return(GetRequest(url, "text/text")); }, (PolyStatus status, int responseCode, byte[] response) => { if (responseCode == 401 || !status.ok) { if (isRecursion /* || !Authenticator.IsInitialized*/) { callback(PolyStatus.Error("Get asset error ({0})", responseCode), null); return; } //else //{ // Authenticator.Instance.Reauthorize((PolyStatus reauthStatus) => // { // if (reauthStatus.ok) // { // GetAsset(assetId, callback, isRecursion: true); // } // else // { // callback(PolyStatus.Error(reauthStatus, "Failed to reauthenticate to get asset {0}", assetId), null); // } // }); //} } else { string text = Encoding.UTF8.GetString(response); PolyStatus responseStatus = CheckResponseForError(text); if (!responseStatus.ok) { callback(responseStatus, null); return; } PolyMainInternal.Instance.DoBackgroundWork(new ParseAssetBackgroundWork(text, callback)); } }, DEFAULT_QUERY_CACHE_MAX_AGE_MILLIS); }
//event callback handlers void handleFetchThumbnailCallback(PolyAsset asset, PolyStatus status) { if (status.ok) { Debug.Log("handleFetchThumbnailCallback handled"); Debug.Log(asset.thumbnail); gameObj.GetComponent <Renderer>().material.mainTexture = asset.thumbnailTexture; Debug.Log(asset.name); gameObj.AddComponent <Pojo>().id = asset.name.ToString(); Debug.Log(gameObj.GetComponent <Pojo>().id); gameObj.SetActive(true); } }
/// <summary> /// Callback invoked when an asset thumbnail is fetched. /// </summary> private void OnThumbnailFetched(PolyAsset asset, PolyStatus status) { if (status.ok) { thumbnailCache.Put(asset.name, asset.thumbnailTexture); // Preserve the texture so it survives round-trips to play mode and back. asset.thumbnailTexture.hideFlags = HideFlags.HideAndDontSave; } if (null != refreshCallback) { refreshCallback(); } thumbnailCache.TrimCacheWithExceptions(assetsInUse); }