You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

256 lines
7.1 KiB

using System.Collections;
using UnityEngine;
using TMPro;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using System;
public class MotyUploadToGoogleDrive : MonoBehaviour
{
public float PrintBrightnessMultiplier = 1.2f;
public class UploadRequestMoty
{
public string id;
public string filename;
public bool default_image;
}
public RenderTexture renderTexture_share;
public string OutputFolder = "output";
public TextMeshProUGUI TextNumber;
public TextMeshProUGUI TextSummary;
// public GameObject BackgroundDefault;
public GameObject ImageDiscardPostcard;
public GameObject ImageGeneratePostcard;
// Start is called before the first frame update
public string GoogleDriveFolderId = "1lZ_dJkr4qrIWG1IFd-nPCv__LHALUv0J";
UploadRequestMoty latest_input;
// DriveService service;
void Start()
{
setupService();
}
// Update is called once per frame
void Update()
{
}
public void Save(string input_text)
{
var parmas = input_text.Split('#');
if (parmas.Length < 2)
{
Debug.LogError("Input text must contain at least two parts separated by '#'.");
return;
}
string id = parmas[0].Trim();
// string summary = parmas[2].Trim();
string filename = id;
bool default_image = parmas[1].Trim().ToLower() == "default";
Debug.Log("/export id=" + id + " default:" + default_image);
if (default_image)
{
ImageGeneratePostcard.SetActive(false);
}
else
{
ImageGeneratePostcard.SetActive(true);
}
TextNumber.SetText(id);
// TextSummary.SetText(summary);
TextNumber.ForceMeshUpdate();
TextSummary.ForceMeshUpdate();
latest_input = new UploadRequestMoty()
{
id = id,
filename = filename,
default_image = default_image,
};
if (!this.enabled || !gameObject.activeInHierarchy){
Debug.LogError("Cannot start coroutine: Host is not active or enabled!");
return;
}
StartCoroutine(ExportAfterFrame(latest_input));
// Export(latest_input);
}
private IEnumerator ExportAfterFrame(UploadRequestMoty uploadRequest)
{
Debug.Log("Waiting for end of frame before exporting...");
// yield return new WaitForEndOfFrame();
yield return null;
Debug.Log("End of frame reached, starting export...");
Export(uploadRequest);
}
public void Export(UploadRequestMoty uploadRequest = null)
{
if (uploadRequest == null)
{
Debug.LogError("UploadRequest is null.");
return;
}
string id = uploadRequest.id;
string filename = uploadRequest.filename;
Debug.Log("Saving image to: filename=" + filename + " id=" + id);
if (string.IsNullOrEmpty(filename))
{
Debug.LogError("Filename cannot be null or empty.");
filename = "untitled_" + System.DateTime.Now.ToString("yyyyMMdd_HHmmss");
// return;
}
Debug.Log("Saving image to: filename=" + filename + " id=" + id);
// string timestamp = System.DateTime.Now.ToString("yyyyMMdd");
// if (!System.IO.Directory.Exists(OutputFolder + "/" + uploadDest))
// {
// System.IO.Directory.CreateDirectory(OutputFolder + "/" + uploadDest);
// }
SaveRenderTextureToPNG(renderTexture_share, System.IO.Path.Combine(OutputFolder, filename + ".png"));
Debug.Log("Image saved to " + filename);
string share_fullPath = System.IO.Path.Combine(OutputFolder + "/", filename + ".png");
Debug.Log("share_path: " + share_fullPath);
upload(share_fullPath, id, "share");
}
void SaveRenderTextureToPNG(RenderTexture rt, string filePath)
{
Debug.Log("Saving RenderTexture to PNG at " + filePath);
RenderTexture currentRT = RenderTexture.active;
RenderTexture.active = rt;
Texture2D tex = new Texture2D(rt.width, rt.height, TextureFormat.RGBA32, false);
tex.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
// Apply gamma correction (sRGB conversion) to each pixel
for (int y = 0; y < tex.height; y++)
{
for (int x = 0; x < tex.width; x++)
{
Color linearColor = tex.GetPixel(x, y);
Color sRGBColor = new Color(
Mathf.LinearToGammaSpace(linearColor.r),
Mathf.LinearToGammaSpace(linearColor.g),
Mathf.LinearToGammaSpace(linearColor.b),
linearColor.a
);
sRGBColor.r *= PrintBrightnessMultiplier;
                sRGBColor.g *= PrintBrightnessMultiplier;
sRGBColor.b *= PrintBrightnessMultiplier;
tex.SetPixel(x, y, sRGBColor);
}
}
tex.Apply();
byte[] bytes = tex.EncodeToPNG();
System.IO.File.WriteAllBytes(filePath, bytes);
Debug.Log("Saved RenderTexture to PNG at " + filePath + " with size: " + bytes.Length + " bytes");
RenderTexture.active = currentRT;
Destroy(tex);
}
void setupService()
{
// Debug.Log("Setting up Google Drive service...");
// // Initialize Google Drive API service
// service = new DriveService(new BaseClientService.Initializer()
// {
// HttpClientInitializer = GoogleCredential.FromFile("../Material/tech-277909-8bd38efb7464.json").CreateScoped(DriveService.Scope.DriveFile),
// ApplicationName = "24070-Upload",
// });
GoogleDriveUtils.setupService();
}
void upload(string _uploadFile, string _fileId, string type, bool needToPrint = true)
{
if (GoogleDriveUtils.service == null)
{
Debug.Log("service is null, setting up service again.");
setupService();
}
// string path = "";
// int lastSlash = path.LastIndexOf('/');
// Debug.Log("Extracted path: " + path + ", lastSlash=" + lastSlash);
// if (lastSlash >= 0)
// {
// // path = path[..lastSlash];
// path=path.Substring(0, lastSlash);
// }
Debug.Log("Uploading file to Google Drive: " + _uploadFile);
string folderId = GoogleDriveUtils.getFolder(GoogleDriveUtils.service, "", GoogleDriveFolderId);
StartCoroutine(GoogleDriveUtils.UploadCoroutine(GoogleDriveUtils.service, _uploadFile, folderId, _fileId, type,
(response) =>
{
if (response != null)
{
var url = response;
Debug.Log("Upload successful:" + url);
// TODO: back to standby
}
else
{
Debug.LogError("Upload failed: " + response);
}
}
));
}
}