LegacyRenderer.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using UnityEngine;
  6. namespace Screencap
  7. {
  8. public static class LegacyRenderer
  9. {
  10. public static byte[] RenderCamera(int ResolutionX, int ResolutionY, int DownscalingRate, int AntiAliasing)
  11. {
  12. var go = new GameObject();
  13. Camera renderCam = go.AddComponent<Camera>();
  14. renderCam.CopyFrom(Camera.main);
  15. CopyComponents(Camera.main.gameObject, renderCam.gameObject);
  16. renderCam.targetTexture = new RenderTexture(ResolutionX * DownscalingRate, ResolutionY * DownscalingRate, 32); //((int)cam.pixelRect.width, (int)cam.pixelRect.height, 32);
  17. renderCam.aspect = renderCam.targetTexture.width / (float)renderCam.targetTexture.height;
  18. renderCam.targetTexture.antiAliasing = AntiAliasing;
  19. RenderTexture currentRT = RenderTexture.active;
  20. RenderTexture.active = renderCam.targetTexture;
  21. renderCam.clearFlags = CameraClearFlags.Skybox;
  22. renderCam.Render();
  23. Texture2D image = new Texture2D(ResolutionX * DownscalingRate, ResolutionY * DownscalingRate);
  24. image.ReadPixels(new Rect(0, 0, ResolutionX * DownscalingRate, ResolutionY * DownscalingRate), 0, 0);
  25. TextureScale.Bilinear(image, ResolutionX, ResolutionY);
  26. image.Apply();
  27. RenderTexture.active = currentRT;
  28. GameObject.Destroy(renderCam.targetTexture);
  29. GameObject.Destroy(renderCam);
  30. byte[] result = image.EncodeToPNG();
  31. GameObject.Destroy(image);
  32. return result;
  33. }
  34. static void CopyComponents(GameObject original, GameObject target)
  35. {
  36. foreach (Component component in original.GetComponents<Component>())
  37. {
  38. var newComponent = CopyComponent(component, target);
  39. if (component is MonoBehaviour)
  40. {
  41. var behavior = (MonoBehaviour)component;
  42. (newComponent as MonoBehaviour).enabled = behavior.enabled;
  43. }
  44. }
  45. }
  46. //https://answers.unity.com/questions/458207/copy-a-component-at-runtime.html
  47. static Component CopyComponent(Component original, GameObject destination)
  48. {
  49. System.Type type = original.GetType();
  50. Component copy = destination.AddComponent(type);
  51. // Copied fields can be restricted with BindingFlags
  52. System.Reflection.FieldInfo[] fields = type.GetFields();
  53. foreach (System.Reflection.FieldInfo field in fields)
  54. {
  55. field.SetValue(copy, field.GetValue(original));
  56. }
  57. return copy;
  58. }
  59. }
  60. }