예제 #1
0
 protected void OnRenderImage(RenderTexture src, RenderTexture dst)
 {
     if (!this.CheckResources())
     {
         Graphics.Blit(src, dst);
         return;
     }
     int num = src.width;
     int num1 = src.height;
     int num2 = src.depth;
     RenderTextureFormat renderTextureFormat = src.format;
     if (num != this.w || num1 != this.h || num2 != this.d || renderTextureFormat != this.fmt)
     {
         this.CleanupCaptureRT();
         RenderTexture renderTexture = new RenderTexture(num, num1, num2, renderTextureFormat)
         {
             hideFlags = HideFlags.DontSave
         };
         this.captureRT = renderTexture;
         if (!this.captureRT.Create() && !this.captureRT.IsCreated())
         {
             Graphics.Blit(src, dst);
             return;
         }
         this.captureRT.SetGlobalShaderProperty("_OpaqueFrame");
         this.w = num;
         this.h = num1;
         this.d = num2;
         this.fmt = renderTextureFormat;
     }
     Graphics.Blit(src, this.captureRT);
     Graphics.Blit(src, dst);
 }
        //--------------- Dispose --------------------
        //--------------- TEXTURE 2D --------------------
        public static Texture2D GetTexture2D(int width, int height, bool linear, RenderTextureFormat rtMatchFormat = RenderTextureFormat.Default)
        {
            Texture2D result = null;
            int i = texture2DBuffers.Count;
            while (--i > -1){
                if (texture2DBuffers[i] == null){
                    texture2DBuffers.RemoveAt(i);
                }
            }

            TextureFormat format = GetBest2DFormat(rtMatchFormat);
            int idx = texture2DBuffers.FindIndex(item => item.width == width && item.height == height && item.format == format);
            if (idx != -1){
                result = texture2DBuffers[idx];
                texture2DBuffers.RemoveAt(idx);
            }

            if (result == null) {
                result = new Texture2D(width, height, format, false, linear);
                result.name = "vBug_PoolTexture";
                result.filterMode = FilterMode.Point;
                result.anisoLevel = 0;
            }

            return result;
        }
예제 #3
0
 protected virtual void Awake() {
   Assert.SupportsRenderTextures(this);
   Assert.NotNull<Shader>(this, replacementShader, "replacementShader");
   if (!Assert.SupportsRenderTextureFormats(this, rtFormat)) {
     rtFormat = RenderTextureFormat.Default;
   }
 }
예제 #4
0
 public RenderTexture GetTemporaryRenderTexture(int width, int height, int depthBuffer = 0, RenderTextureFormat format = RenderTextureFormat.ARGBHalf, FilterMode filterMode = FilterMode.Bilinear)
 {
     var rt = RenderTexture.GetTemporary(width, height, depthBuffer, format);
     rt.filterMode = filterMode;
     rt.wrapMode = TextureWrapMode.Clamp;
     rt.name = "RenderTextureUtilityTempTexture";
     m_TemporaryRTs.Add(rt);
     return rt;
 }
예제 #5
0
 public RenderTexture GetTemporaryRenderTexture(int width, int height, int depthBuffer = 0, RenderTextureFormat format = RenderTextureFormat.ARGBHalf, FilterMode filterMode = FilterMode.Bilinear)
 {
     RenderTexture temporary = RenderTexture.GetTemporary(width, height, depthBuffer, format);
     temporary.filterMode = filterMode;
     temporary.wrapMode = TextureWrapMode.Clamp;
     temporary.name = "RenderTextureUtilityTempTexture";
     this.m_TemporaryRTs.Add(temporary);
     return temporary;
 }
예제 #6
0
 public RenderTexture Get(int width, int height, int depthBuffer = 0, RenderTextureFormat format = RenderTextureFormat.ARGBHalf, RenderTextureReadWrite rw = RenderTextureReadWrite.Default, FilterMode filterMode = FilterMode.Bilinear, TextureWrapMode wrapMode = TextureWrapMode.Clamp, string name = "FactoryTempTexture")
 {
     var rt = RenderTexture.GetTemporary(width, height, depthBuffer, format);
     rt.filterMode = filterMode;
     rt.wrapMode = wrapMode;
     rt.name = name;
     m_TemporaryRTs.Add(rt);
     return rt;
 }
 static RenderTexture CreateDataTexture(int w, int h, RenderTextureFormat f)
 {
     RenderTexture r = new RenderTexture(w, h, 0, f);
     r.filterMode = FilterMode.Point;
     r.useMipMap = false;
     r.generateMips = false;
     r.Create();
     return r;
 }
예제 #8
0
 /// <summary>
 /// <para>Creates a new RenderTexture object.</para>
 /// </summary>
 /// <param name="width">Texture width in pixels.</param>
 /// <param name="height">Texture height in pixels.</param>
 /// <param name="depth">Number of bits in depth buffer (0, 16 or 24). Note that only 24 bit depth has stencil buffer.</param>
 /// <param name="format">Texture color format.</param>
 /// <param name="readWrite">How or if color space conversions should be done on texture read/write.</param>
 public RenderTexture(int width, int height, int depth, RenderTextureFormat format)
 {
     Internal_CreateRenderTexture(this);
     this.width = width;
     this.height = height;
     this.depth = depth;
     this.format = format;
     Internal_SetSRGBReadWrite(this, QualitySettings.activeColorSpace == ColorSpace.Linear);
 }
예제 #9
0
 bool CheckSupport()
 {
     if (!Supported ()) {
         enabled = false;
         return false;
     }
     rtFormat = SystemInfo.SupportsRenderTextureFormat (RenderTextureFormat.RGB565) ? RenderTextureFormat.RGB565 : RenderTextureFormat.Default;
     return true;
 }
예제 #10
0
 RenderTexture CreateGBufferRT(RenderTextureFormat format, int depth = 0)
 {
     var ret = new RenderTexture(m_camera.pixelWidth, m_camera.pixelHeight, depth, format);
     ret.filterMode = FilterMode.Point;
     ret.useMipMap = false;
     ret.generateMips = false;
     ret.enableRandomWrite = m_enable_uav;
     ret.Create();
     return ret;
 }
예제 #11
0
            public FrameBlendingFilter()
            {
                _useCompression = CheckSupportCompression();
                _rawTextureFormat = GetPreferredRenderTextureFormat();

                _material = new Material(Shader.Find("Hidden/Image Effects/Cinematic/MotionBlur/FrameBlending"));
                _material.hideFlags = HideFlags.DontSave;

                _frameList = new Frame[4];
            }
예제 #12
0
 public static RenderTexture CreateDataTexture(int num_data, int num_elements, RenderTextureFormat format)
 {
     if (num_data == 0) { return null; }
     int width = MeshTextureWidth * num_elements;
     int height = AlembicUtils.ceildiv(num_data, MeshTextureWidth);
     //Debug.Log("CreateDataTexture(): " + width + " x " + height + " " + format);
     var r = new RenderTexture(width, height, 0, format);
     r.filterMode = FilterMode.Point;
     r.wrapMode = TextureWrapMode.Repeat;
     r.enableRandomWrite = true;
     r.Create();
     return r;
 }
예제 #13
0
 public MRT(int width, int height, RenderTextureFormat format = RenderTextureFormat.ARGBFloat, FilterMode filterMode = FilterMode.Point, TextureWrapMode wrapMode = TextureWrapMode.Repeat)
 {
     RTs = new RenderTexture[3];
     for(int i = 0, n = RTs.Length; i < n; i++) {
         int depth = (i == 0) ? 24 : 0;
         RTs[i] = new RenderTexture(width, height, depth);
         RTs[i].hideFlags = HideFlags.DontSave;
         RTs[i].format = format;
         RTs[i].filterMode = filterMode;
         RTs[i].wrapMode = wrapMode;
         RTs[i].Create();
     }
 }
예제 #14
0
 public void EnsureRenderTarget(ref RenderTexture rt, int width, int height, RenderTextureFormat format, FilterMode filterMode, int depthBits = 0)
 {
     if (rt != null && (rt.width != width || rt.height != height || rt.format != format || rt.filterMode != filterMode))
     {
         RenderTexture.ReleaseTemporary(rt);
         rt = null;
     }
     if (rt == null)
     {
         rt = RenderTexture.GetTemporary(width, height, depthBits, format);
         rt.filterMode = filterMode;
         rt.wrapMode = TextureWrapMode.Clamp;
     }
 }
예제 #15
0
 /// <summary>
 /// <para>Creates a new RenderTexture object.</para>
 /// </summary>
 /// <param name="width">Texture width in pixels.</param>
 /// <param name="height">Texture height in pixels.</param>
 /// <param name="depth">Number of bits in depth buffer (0, 16 or 24). Note that only 24 bit depth has stencil buffer.</param>
 /// <param name="format">Texture color format.</param>
 /// <param name="readWrite">How or if color space conversions should be done on texture read/write.</param>
 public RenderTexture(int width, int height, int depth, RenderTextureFormat format, RenderTextureReadWrite readWrite)
 {
     Internal_CreateRenderTexture(this);
     this.width = width;
     this.height = height;
     this.depth = depth;
     this.format = format;
     bool sRGB = readWrite == RenderTextureReadWrite.sRGB;
     if (readWrite == RenderTextureReadWrite.Default)
     {
         sRGB = QualitySettings.activeColorSpace == ColorSpace.Linear;
     }
     Internal_SetSRGBReadWrite(this, sRGB);
 }
예제 #16
0
 /// <summary>
 /// Creates a GameObject with an OffscreenBuffer and required Camera with the specified properties.
 /// </summary>
 public static OffscreenBuffer Create(int width, int height, int depth,
                                      RenderTextureFormat format, DepthTextureMode depthMode,
                                      LayerMask layerMask, CameraClearFlags clearFlags,
                                      Color clearColor, Shader replacementShader,
                                      string replacementTag) {
   GameObject tmp = new GameObject("Offscreen Buffer Camera");
   // we want to do some setup before we activate so things adhere to Monobehaviour execution order.
   tmp.SetActive(false);
   tmp.AddComponent<Camera>();
   OffscreenBuffer c = tmp.AddComponent<OffscreenBuffer>();
   c.width = width;
   c.height = height;
   c.depth = depth;
   c.format = format;
   c.cullingMask = layerMask.value;
   c.clearFlags = clearFlags;
   c.clearColor = clearColor;
   if (replacementShader != null) {
     c.replacementShader = replacementShader;
     c.replacementTag = replacementTag;
   }
   tmp.SetActive(true);
   return c;
 }
예제 #17
0
    void InitRenderTexture(ref RenderTexture rt, int width, int height, int depth, RenderTextureFormat format, bool temp = true)
    {
        if (temp)
        {
            rt = RenderTexture.GetTemporary(width, height, depth, format);
        }
        else
        {
            if (rt != null)
            {
                if (rt.width == width && rt.height == height && rt.depth == depth && rt.format == format)
                    return;

                rt.Release();
                DestroyImmediate(rt);
            }

            rt = new RenderTexture(width, height, depth, format);
            rt.hideFlags = HideFlags.HideAndDontSave;
        }
    }
예제 #18
0
 public HDDynamicShadowAtlas(HDRenderPipelineRuntimeResources renderPipelineResources, RenderGraph renderGraph, bool useSharedTexture, int width, int height, int atlasShaderID, Material clearMaterial, int maxShadowRequests, HDShadowInitParameters initParams, BlurAlgorithm blurAlgorithm = BlurAlgorithm.None, FilterMode filterMode = FilterMode.Bilinear, DepthBits depthBufferBits = DepthBits.Depth16, RenderTextureFormat format = RenderTextureFormat.Shadowmap, string name = "")
     : base(renderPipelineResources, renderGraph, useSharedTexture, width, height, atlasShaderID, clearMaterial, maxShadowRequests, initParams, blurAlgorithm, filterMode, depthBufferBits, format, name)
 {
     m_SortedRequestsCache = new HDShadowResolutionRequest[Mathf.CeilToInt(maxShadowRequests)];
 }
예제 #19
0
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (bloom == null)
        {
            bloom           = new Material(bloomShader);
            bloom.hideFlags = HideFlags.HideAndDontSave;
        }
        float   knee = threshold * softThreshold;
        Vector4 filter;

        filter.x = threshold;
        filter.y = filter.x - knee;
        filter.z = 2f * knee;
        filter.w = 0.25f / (knee + 0.00001f);
        bloom.SetVector("_Filter", filter);
        bloom.SetFloat("_Intensity", Mathf.GammaToLinearSpace(intensity));
        int width  = source.width / 2;
        int height = source.height / 2;
        RenderTextureFormat format = source.format;

        RenderTexture[] textures           = new RenderTexture[16];
        RenderTexture   currentDestination = textures[0] = RenderTexture.GetTemporary(width, height, 0, format);

        //Graphics.Blit(source, destination);


        Graphics.Blit(source, currentDestination, bloom, BoxDownPrefilterPass);
        RenderTexture currentSource = currentDestination;


        int i = 1;

        for (; i < iterations; i++)
        {
            width  /= 2;
            height /= 2;
            if (height < 2)
            {
                break;
            }
            currentDestination = textures[i] =
                RenderTexture.GetTemporary(width, height, 0, format);
            Graphics.Blit(currentSource, currentDestination, bloom, BoxDownPass);
            //RenderTexture.ReleaseTemporary(currentSource);
            currentSource = currentDestination;
        }
        for (i -= 2; i >= 0; i--)
        {
            currentDestination = textures[i];
            textures[i]        = null;
            Graphics.Blit(currentSource, currentDestination, bloom, BoxUpPass);
            RenderTexture.ReleaseTemporary(currentSource);
            currentSource = currentDestination;
        }


        bloom.SetTexture("_SourceTex", source);
        if (ShowBloomOnly)
        {
            Graphics.Blit(currentSource, destination, bloom, ShowBloomOnlyPass);
        }
        else
        {
            Graphics.Blit(currentSource, destination, bloom, ApplyBloomPass);
            RenderTexture.ReleaseTemporary(currentSource);
        }
    }
예제 #20
0
        // This method wraps around regular RenderTexture creation.
        // There is no specific logic applied to RenderTextures created this way.
        public RTHandle Alloc(
            int width,
            int height,
            int slices = 1,
            DepthBits depthBufferBits          = DepthBits.None,
            GraphicsFormat colorFormat         = GraphicsFormat.R8G8B8A8_SRGB,
            FilterMode filterMode              = FilterMode.Point,
            TextureWrapMode wrapMode           = TextureWrapMode.Repeat,
            TextureDimension dimension         = TextureDimension.Tex2D,
            bool enableRandomWrite             = false,
            bool useMipMap                     = false,
            bool autoGenerateMips              = true,
            bool isShadowMap                   = false,
            int anisoLevel                     = 1,
            float mipMapBias                   = 0f,
            MSAASamples msaaSamples            = MSAASamples.None,
            bool bindTextureMS                 = false,
            bool useDynamicScale               = false,
            bool xrInstancing                  = false,
            RenderTextureMemoryless memoryless = RenderTextureMemoryless.None,
            string name = ""
            )
        {
            bool enableMSAA = msaaSamples != MSAASamples.None;

            if (!enableMSAA && bindTextureMS == true)
            {
                Debug.LogWarning("RTHandle allocated without MSAA but with bindMS set to true, forcing bindMS to false.");
                bindTextureMS = false;
            }

            // XR override for instancing support
            VRTextureUsage vrUsage = VRTextureUsage.None;

            // We need to handle this in an explicit way since GraphicsFormat does not expose depth formats. TODO: Get rid of this branch once GraphicsFormat'll expose depth related formats
            RenderTexture rt;

            if (isShadowMap || depthBufferBits != DepthBits.None)
            {
                RenderTextureFormat format = isShadowMap ? RenderTextureFormat.Shadowmap : RenderTextureFormat.Depth;
                rt = new RenderTexture(width, height, (int)depthBufferBits, format, RenderTextureReadWrite.Linear)
                {
                    hideFlags         = HideFlags.HideAndDontSave,
                    volumeDepth       = slices,
                    filterMode        = filterMode,
                    wrapMode          = wrapMode,
                    dimension         = dimension,
                    enableRandomWrite = enableRandomWrite,
                    useMipMap         = useMipMap,
                    autoGenerateMips  = autoGenerateMips,
                    anisoLevel        = anisoLevel,
                    mipMapBias        = mipMapBias,
                    antiAliasing      = (int)msaaSamples,
                    bindTextureMS     = bindTextureMS,
                    useDynamicScale   = m_HardwareDynamicResRequested && useDynamicScale,
                    vrUsage           = vrUsage,
                    memorylessMode    = memoryless,
                    name = CoreUtils.GetRenderTargetAutoName(width, height, slices, format, name, mips: useMipMap, enableMSAA: enableMSAA, msaaSamples: msaaSamples)
                };
            }
            else
            {
                rt = new RenderTexture(width, height, (int)depthBufferBits, colorFormat)
                {
                    hideFlags         = HideFlags.HideAndDontSave,
                    volumeDepth       = slices,
                    filterMode        = filterMode,
                    wrapMode          = wrapMode,
                    dimension         = dimension,
                    enableRandomWrite = enableRandomWrite,
                    useMipMap         = useMipMap,
                    autoGenerateMips  = autoGenerateMips,
                    anisoLevel        = anisoLevel,
                    mipMapBias        = mipMapBias,
                    antiAliasing      = (int)msaaSamples,
                    bindTextureMS     = bindTextureMS,
                    useDynamicScale   = m_HardwareDynamicResRequested && useDynamicScale,
                    vrUsage           = vrUsage,
                    memorylessMode    = memoryless,
                    name = CoreUtils.GetRenderTargetAutoName(width, height, slices, GraphicsFormatUtility.GetRenderTextureFormat(colorFormat), name, mips: useMipMap, enableMSAA: enableMSAA, msaaSamples: msaaSamples)
                };
            }

            rt.Create();

            RTCategory category = enableMSAA ? RTCategory.MSAA : RTCategory.Regular;
            var        newRT    = new RTHandle(this);

            newRT.SetRenderTexture(rt, category);
            newRT.useScaling             = false;
            newRT.m_EnableRandomWrite    = enableRandomWrite;
            newRT.m_EnableMSAA           = enableMSAA;
            newRT.m_EnableHWDynamicScale = useDynamicScale;
            newRT.m_Name = name;

            newRT.referenceSize = new Vector2Int(width, height);

            return(newRT);
        }
예제 #21
0
 public static RenderTexture GetScreenRenderTexture(int depth, bool writable = false, RenderTextureFormat format = RenderTextureFormat.ARGBFloat)
 {
     return(GetRenderTexture(Screen.width, Screen.height, depth, writable, format));
 }
예제 #22
0
파일: PostFXBase.cs 프로젝트: slb1988/agame
 public void DoPostProcess(RenderTexture source, RenderTexture destination)
 {
     if (!this.CheckResources())
     {
         Graphics.Blit(source, destination);
     }
     else
     {
         if ((this.converted2DLut == null) && this.UseColorGrading)
         {
             if (this.sourceLut3D == null)
             {
                 this.SetIdentityLut();
             }
             else
             {
                 this.Convert(this.sourceLut3D, string.Empty);
             }
         }
         if (this.FastMode)
         {
             if (this.SepiaColor.a != 0f)
             {
                 this.GlareCompositionEx.SetVector(HASH_SEPIA_COLOR, (Vector4)this.SepiaColor);
                 this.GlareCompositionEx.SetTexture(HASH_MAIN_TEX, source);
                 Graphics.Blit(null, destination, this.GlareCompositionEx, 5);
             }
             else
             {
                 Graphics.Blit(source, destination);
             }
         }
         else
         {
             this.aspectRatio  = source.width;
             this.aspectRatio /= (float)source.height;
             if (this.HDRBuffer)
             {
                 this.internalBufferFormat = RenderTextureFormat.ARGBHalf;
             }
             else
             {
                 this.internalBufferFormat = RenderTextureFormat.ARGB32;
             }
             this.CreateRenderTextures(source.width, source.height);
             if (this.WriteAlpha)
             {
                 this.PrepareAlpha();
             }
             if (this.UseDistortion)
             {
                 this.PrepareDistortion();
             }
             this.DownSample4X.SetVector(HASH_TEXEL_SIZE, new Vector2(1f / ((float)source.width), 1f / ((float)source.height)));
             Graphics.Blit(source, (RenderTexture)this.downsample4X_buffer, this.DownSample4X, 0);
             this.DownSample4X.SetVector(HASH_TEXEL_SIZE, new Vector2(0.5f / ((float)this.downsample4X_buffer.content.width), 0.5f / ((float)this.downsample4X_buffer.content.height)));
             Graphics.Blit((Texture)this.downsample4X_buffer, (RenderTexture)this.blur_bufferA[0], this.DownSample4X, 0);
             this.extractHL((RenderTexture)this.blur_bufferA[0], (RenderTexture)this.compose_buffer[0]);
             this.blur((RenderTexture)this.compose_buffer[0], (RenderTexture)this.blur_bufferA[0], (RenderTexture)this.blur_bufferB[0], 0);
             for (int i = 1; i < 4; i++)
             {
                 Graphics.Blit((Texture)this.compose_buffer[i - 1], (RenderTexture)this.compose_buffer[i], this.DownSample, 0);
                 this.blur((RenderTexture)this.compose_buffer[i], (RenderTexture)this.blur_bufferA[i], (RenderTexture)this.blur_bufferB[i], i);
             }
             this.ComposeBlur((RenderTexture)this.gauss_buffer);
             if (this.UseRadialBlur)
             {
                 this.ComposeEffect(source, (RenderTexture)this.radial_blur_buffer_temp, false);
                 this.RadialBlur((RenderTexture)this.radial_blur_buffer_temp, (RenderTexture)this.radial_blur_buffer);
             }
             this.ComposeEffect(source, destination, this.UseRadialBlur);
             this.ReleaseRenderTextures();
         }
     }
 }
예제 #23
0
	void Start()
	{
		// Disable if we don't support image effects
		if (!SystemInfo.supportsImageEffects)
		{
			Debug.LogWarning("Image Effects are not supported on this platform.");
			enabled = false;
			return;
		}

		// Disable if we don't support render textures
		if (SystemInfo.supportsRenderTextures)
		{
#if UNITY_4_X
			if (!SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RFloat))
			{
				if (!SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.Depth))
				{
					Debug.LogWarning("RFloat && Depth RenderTextures are not supported on this platform.");
					enabled = false;
					return;
				}

				m_RTFormat = RenderTextureFormat.Depth;
			}
#endif
		}
		else
		{
			Debug.LogWarning("RenderTextures are not supported on this platform.");
			enabled = false;
			return;
		}

		// Disable the image effect if the shaders can't run on the users graphics card
		if (ShaderSSAO != null && !ShaderSSAO.isSupported)
		{
			Debug.LogWarning("Unsupported shader (SSAO).");
			enabled = false;
			return;
		}

#if UNITY_4_X
		if (ShaderHighPrecisionDepth != null && !ShaderHighPrecisionDepth.isSupported)
		{
			Debug.LogWarning("Unsupported shader (High Precision Depth Map).");
			enabled = false;
			return;
		}
#endif
	}
예제 #24
0
        public override void InitAtlas(HDRenderPipelineRuntimeResources renderPipelineResources, RenderGraph renderGraph, bool useSharedTexture, int width, int height, int atlasShaderID, Material clearMaterial, int maxShadowRequests, HDShadowInitParameters initParams, BlurAlgorithm blurAlgorithm = BlurAlgorithm.None, FilterMode filterMode = FilterMode.Bilinear, DepthBits depthBufferBits = DepthBits.Depth16, RenderTextureFormat format = RenderTextureFormat.Shadowmap, string name = "")
        {
            base.InitAtlas(renderPipelineResources, renderGraph, useSharedTexture, width, height, atlasShaderID, clearMaterial, maxShadowRequests, initParams, blurAlgorithm, filterMode, depthBufferBits, format, name);
            m_IsACacheForShadows = true;

            m_AtlasResolutionInSlots = HDUtils.DivRoundUp(width, m_MinSlotSize);
            m_AtlasSlots             = new List <SlotValue>(m_AtlasResolutionInSlots * m_AtlasResolutionInSlots);
            for (int i = 0; i < m_AtlasResolutionInSlots * m_AtlasResolutionInSlots; ++i)
            {
                m_AtlasSlots.Add(SlotValue.Free);
            }

            // Note: If changing the characteristics of the atlas via HDRP asset, the lights OnEnable will not be called again so we are missing them, however we can explicitly
            // put them back up for placement. If this is the first Init of the atlas, the lines below do nothing.
            DefragmentAtlasAndReRender(initParams);
            m_CanTryPlacement    = true;
            m_NeedOptimalPacking = true;
        }
예제 #25
0
 public static bool CreateTexture(ref RenderTexture renderTexture, int width, int height, int depth, RenderTextureFormat format) => default;         // 0x000000018113D230-0x000000018113D3B0
예제 #26
0
        internal static PaintContext InitializePaintContext(Terrain terrain, int targetWidth, int targetHeight, RenderTextureFormat pcFormat, Rect boundsInTerrainSpace, int extraBorderPixels = 0, bool texelPadding = true)
        {
            PaintContext ctx = PaintContext.CreateFromBounds(terrain, boundsInTerrainSpace, targetWidth, targetHeight, extraBorderPixels, texelPadding);

            ctx.CreateRenderTargets(pcFormat);
            return(ctx);
        }
        private void Start()
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                Shader.SetGlobalTexture("_ObstacleTex", Texture2D.whiteTexture);
                return;
            }
#endif

            if (LightCamera == null)
            {
                Debug.LogError(
                    "Lighting Camera in LightingSystem is null. Please, select Lighting Camera camera for lighting to work.");
                enabled = false;
                return;
            }

            if (LightOverlayMaterial == null)
            {
                Debug.LogError(
                    "LightOverlayMaterial in LightingSystem is null. Please, select LightOverlayMaterial camera for lighting to work.");
                enabled = false;
                return;
            }

            if (AffectOnlyThisCamera && _camera.targetTexture != null)
            {
                Debug.LogError("\"Affect Only This Camera\" will not work if camera.targetTexture is set.");
                AffectOnlyThisCamera = false;
            }

            _camera = GetComponent <Camera>();

            if (EnableNormalMapping && !_camera.orthographic)
            {
                Debug.LogError("Normal mapping is not supported with perspective camera.");
                EnableNormalMapping = false;
            }

            if (!SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf))
            {
                HDR = false;
            }
            _texFormat = HDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;

            var lightPixelsPerUnityMeter = LightPixelsPerUnityMeter;

            _halfTexelOffest = SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 9");

            InitTK2D();

            if (_camera.orthographic)
            {
                var rawCamHeight = (_camera.orthographicSize + LightCameraSizeAdd) * 2f;
                var rawCamWidth  = (_camera.orthographicSize * _camera.aspect + LightCameraSizeAdd) * 2f;

                _extendedLightTextureSize = new Point2(
                    Mathf.RoundToInt(rawCamWidth * lightPixelsPerUnityMeter),
                    Mathf.RoundToInt(rawCamHeight * lightPixelsPerUnityMeter));

                var rawSmallCamHeight = _camera.orthographicSize * 2f * lightPixelsPerUnityMeter;
                _smallLightTextureSize = new Point2(
                    Mathf.RoundToInt(rawSmallCamHeight * _camera.aspect),
                    Mathf.RoundToInt(rawSmallCamHeight));
            }
            else
            {
                {
                    var lightCamHalfFov = (_camera.fieldOfView + LightCameraFovAdd) * Mathf.Deg2Rad / 2f;
                    var lightCamSize    = Mathf.Tan(lightCamHalfFov) * LightObstaclesDistance * 2;
                    //var gameCamHalfFov = _camera.fieldOfView*Mathf.Deg2Rad/2f;
                    var texHeight = Mathf.RoundToInt(lightCamSize / LightPixelSize);
                    var texWidth  = texHeight * _camera.aspect;
                    _extendedLightTextureSize = Point2.Round(new Vector2(texWidth, texHeight));
                }
                {
                    var lightCamHalfFov = _camera.fieldOfView * Mathf.Deg2Rad / 2f;
                    var lightCamSize    = Mathf.Tan(lightCamHalfFov) * LightObstaclesDistance * 2;
                    //LightCamera.orthographicSize = lightCamSize/2f;

                    var gameCamHalfFov = _camera.fieldOfView * Mathf.Deg2Rad / 2f;
                    var gameCamSize    = Mathf.Tan(gameCamHalfFov) * LightObstaclesDistance * 2;
                    _camera.orthographicSize = gameCamSize / 2f;

                    var texHeight = Mathf.RoundToInt(lightCamSize / LightPixelSize);
                    var texWidth  = texHeight * _camera.aspect;
                    _smallLightTextureSize = Point2.Round(new Vector2(texWidth, texHeight));
                }
            }

            if (_extendedLightTextureSize.x % 2 != 0)
            {
                _extendedLightTextureSize.x++;
            }
            if (_extendedLightTextureSize.y % 2 != 0)
            {
                _extendedLightTextureSize.y++;
            }

            if (_extendedLightTextureSize.x > 1024 || _extendedLightTextureSize.y > 1024 ||
                _smallLightTextureSize.x > 1024 || _smallLightTextureSize.y > 1024)
            {
                Debug.LogError("LightPixelSize is too small. Turning off lighting system.");
                enabled = false;
                return;
            }

            if (_extendedLightTextureSize.x < 4 || _extendedLightTextureSize.y < 4 ||
                _smallLightTextureSize.x < 4 || _smallLightTextureSize.y < 4)
            {
                Debug.LogError("LightPixelSize is too big. Turning off lighting system.");
                enabled = false;
                return;
            }

            _screenBlitTempTex            = new RenderTexture(_camera.pixelWidth, _camera.pixelHeight, 0, _texFormat);
            _screenBlitTempTex.filterMode = FilterMode.Point;

            LightCamera.orthographic = _camera.orthographic;

            if (EnableNormalMapping)
            {
                _lightSourcesTexture = new RenderTexture(_camera.pixelWidth, _camera.pixelHeight,
                                                         0, _texFormat);
                _lightSourcesTexture.filterMode = FilterMode.Point;
            }
            else
            {
                _lightSourcesTexture = new RenderTexture(_smallLightTextureSize.x, _smallLightTextureSize.y,
                                                         0, _texFormat);
                _lightSourcesTexture.filterMode = LightTexturesFilterMode;
            }

            _obstaclesTexture = new RenderTexture(_extendedLightTextureSize.x, _extendedLightTextureSize.y,
                                                  0, _texFormat);
            _ambientTexture = new RenderTexture(_extendedLightTextureSize.x, _extendedLightTextureSize.y,
                                                0, _texFormat);

            _ambientTexture.filterMode = LightTexturesFilterMode;

            var upsampledObstacleSize = _extendedLightTextureSize * (LightObstaclesAntialiasing ? 2 : 1);
            _obstaclesUpsampledTexture = new RenderTexture(
                upsampledObstacleSize.x, upsampledObstacleSize.y, 0, _texFormat);

            if (AffectOnlyThisCamera)
            {
                _renderTargetTexture =
                    new RenderTexture(_camera.pixelWidth, _camera.pixelHeight, 0, RenderTextureFormat.ARGB32);
                _renderTargetTexture.filterMode = FilterMode.Point;
            }

            _obstaclesPostProcessor = new ObstacleCameraPostPorcessor();

            LoopAmbientLight(100);
        }
예제 #28
0
    private byte[] Encode(
        Camera cam,
        int width,
        int height,
        bool supportsAntialiasing,
        bool needsRescale,
        bool jpg = false,
        RenderTextureFormat format             = RenderTextureFormat.Default,
        RenderTextureReadWrite textureReadMode = RenderTextureReadWrite.Default
        )
    {
        var mainCamera   = GetComponent <Camera>();
        var depth        = 24;
        var readWrite    = textureReadMode;
        var antiAliasing = (supportsAntialiasing) ? Mathf.Max(1, QualitySettings.antiAliasing) : 1;

        var finalRT =
            RenderTexture.GetTemporary(width, height, depth, format, readWrite, antiAliasing);
        var renderRT = (!needsRescale) ? finalRT :
                       RenderTexture.GetTemporary(mainCamera.pixelWidth, mainCamera.pixelHeight, depth, format, readWrite, antiAliasing);

        if (tex == null)
        {
            tex = new Texture2D(width, height, TextureFormat.RGB24, false);
        }

        var prevActiveRT = RenderTexture.active;
        var prevCameraRT = cam.targetTexture;

        // render to offscreen texture (readonly from CPU side)
        RenderTexture.active = renderRT;
        cam.targetTexture    = renderRT;

        cam.Render();

        if (needsRescale)
        {
            // blit to rescale (see issue with Motion Vectors in @KNOWN ISSUES)
            RenderTexture.active = finalRT;
            Graphics.Blit(renderRT, finalRT);
            RenderTexture.ReleaseTemporary(renderRT);
        }

        // read offsreen texture contents into the CPU readable texture
        float startTime = Time.realtimeSinceStartup;

        tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
        tex.Apply();
        Debug.Log("imageSynth encode time" + (Time.realtimeSinceStartup - startTime));

        startTime = Time.realtimeSinceStartup;

        // encode texture into PNG/JPG
        byte[] bytes;
        if (jpg)
        {
            bytes = tex.EncodeToJPG();
        }
        else
        {
            bytes = tex.GetRawTextureData();
        }

        Debug.Log("imageSynth format time" + (Time.realtimeSinceStartup - startTime));


        // restore state and cleanup
        cam.targetTexture    = prevCameraRT;
        RenderTexture.active = prevActiveRT;



        // UnityEngine.Object.Destroy(tex);
        RenderTexture.ReleaseTemporary(finalRT);
        return(bytes);
    }
예제 #29
0
		protected void CreateMap(ref RenderTexture map, RenderTextureFormat format, int ansio) {
			map = new RenderTexture(m_fourierGridSize, m_fourierGridSize, 0, format);
			map.filterMode = FilterMode.Trilinear;
			map.wrapMode = TextureWrapMode.Repeat;
			map.anisoLevel = ansio;
			map.useMipMap = true;
			map.Create();
		}
        public static void RenderPostProcess(CommandBuffer cmd, PostProcessRenderContext context, ref CameraData cameraData, RenderTextureFormat colorFormat, RenderTargetIdentifier source, RenderTargetIdentifier dest, bool opaqueOnly)
        {
            context.Reset();
            context.camera       = cameraData.camera;
            context.source       = source;
            context.sourceFormat = colorFormat;
            context.destination  = dest;
            context.command      = cmd;
            context.flip         = cameraData.camera.targetTexture == null;

            if (opaqueOnly)
            {
                cameraData.postProcessLayer.RenderOpaqueOnly(context);
            }
            else
            {
                cameraData.postProcessLayer.Render(context);
            }
        }
예제 #31
0
 public OffscreenProcessor()
 {
     _ProcessingMaterial = new Material(Shader.Find("Diffuse"));
     TargetFormat        = RenderTextureFormat.Default;
 }
예제 #32
0
    void Render(ScriptableRenderContext context, Camera camera)
    {
        ScriptableCullingParameters cullingParameters;

        if (!CullResults.GetCullingParameters(camera, out cullingParameters))
        {
            return;
        }
        cullingParameters.shadowDistance =
            Mathf.Min(shadowDistance, camera.farClipPlane);
#if UNITY_EDITOR
        if (camera.cameraType == CameraType.SceneView)
        {
            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
        }
#endif
        CullResults.Cull(ref cullingParameters, context, ref cull);
        if (cull.visibleLights.Count > 0)
        {
            ConfigureLights();
            if (mainLightExists)
            {
                RenderCascadedShadows(context);
            }
            else
            {
                cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword);
                cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword);
            }
            if (shadowTileCount > 0)
            {
                RenderShadows(context);
            }
            else
            {
                cameraBuffer.DisableShaderKeyword(shadowsHardKeyword);
                cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword);
            }
        }
        else
        {
            cameraBuffer.SetGlobalVector(
                lightIndecesOffsetAndCountId, Vector4.zero
                );
            cameraBuffer.DisableShaderKeyword(cascadedShadowsHardKeyword);
            cameraBuffer.DisableShaderKeyword(cascadedShadowsSoftKeyword);
            cameraBuffer.DisableShaderKeyword(shadowsHardKeyword);
            cameraBuffer.DisableShaderKeyword(shadowsSoftKeyword);
        }
        ConfigureLights();

        context.SetupCameraProperties(camera);

        var myPipelineCamera = camera.GetComponent <MyPipelineCamera>();
        MyPostProcessingStack activeStack = myPipelineCamera ?
                                            myPipelineCamera.PostProcessingStack : defaultStack;

        bool scaledRendering =
            (renderScale <1f || renderScale> 1f) && camera.cameraType == CameraType.Game;

        int renderWidth  = camera.pixelWidth;
        int renderHeight = camera.pixelHeight;
        if (scaledRendering)
        {
            renderWidth  = (int)(renderWidth * renderScale);
            renderHeight = (int)(renderHeight * renderScale);
        }
        int  renderSamples      = camera.allowMSAA ? msaaSamples : 1;
        bool renderToTexture    = scaledRendering || renderSamples > 1 || activeStack;
        bool needsDepth         = activeStack && activeStack.NeedsDepth;
        bool needsDirectDepth   = needsDepth && renderSamples == 1;
        bool needsDepthOnlyPass = needsDepth && renderSamples > 1;

        RenderTextureFormat format = allowHDR && camera.allowHDR ?
                                     RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;
        if (renderToTexture)
        {
            cameraBuffer.GetTemporaryRT(
                cameraColorTextureId, renderWidth, renderHeight,
                needsDirectDepth ? 0 : 24,
                FilterMode.Bilinear, format,
                RenderTextureReadWrite.Default, renderSamples
                );
            if (needsDepth)
            {
                cameraBuffer.GetTemporaryRT(
                    cameraDepthTextureId, renderWidth, renderHeight, 24,
                    FilterMode.Point, RenderTextureFormat.Depth,
                    RenderTextureReadWrite.Linear, 1
                    );
            }
            if (needsDirectDepth)
            {
                cameraBuffer.SetRenderTarget(
                    cameraColorTextureId,
                    RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store,
                    cameraDepthTextureId,
                    RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store
                    );
            }
            else
            {
                cameraBuffer.SetRenderTarget(
                    cameraColorTextureId,
                    RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store
                    );
            }
        }

        CameraClearFlags clearFlags = camera.clearFlags;
        cameraBuffer.ClearRenderTarget(
            (clearFlags & CameraClearFlags.Depth) != 0,
            (clearFlags & CameraClearFlags.Color) != 0,
            camera.backgroundColor
            );

        cameraBuffer.BeginSample("Render Camera");
        cameraBuffer.SetGlobalVectorArray(
            visibleLightColorsId, visibleLightColors
            );
        cameraBuffer.SetGlobalVectorArray(
            visibleLightDirectionsOrPositionsId, visibleLightDirectionsOrPositions
            );
        cameraBuffer.SetGlobalVectorArray(
            visibleLightAttenuationId, visibleLightAttenuations
            );
        cameraBuffer.SetGlobalVectorArray(
            visibleLightSpotDirectionsId, visibleLightSpotDirections
            );
        cameraBuffer.SetGlobalVectorArray(
            visibleLightOcclusionMasksId, visibleLightOcclusionMasks
            );
        globalShadowData.z = 1f - cullingParameters.shadowDistance * globalShadowData.y;
        cameraBuffer.SetGlobalVector(globalShadowDataId, globalShadowData);
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        var drawSettings = new DrawRendererSettings(
            camera, new ShaderPassName("SRPDefaultUnlit")
            )
        {
            flags = drawFlags
        };
        if (cull.visibleLights.Count > 0)
        {
            drawSettings.rendererConfiguration =
                RendererConfiguration.PerObjectLightIndices8;
        }
        drawSettings.rendererConfiguration |=
            RendererConfiguration.PerObjectReflectionProbes |
            RendererConfiguration.PerObjectLightmaps |
            RendererConfiguration.PerObjectLightProbe |
            RendererConfiguration.PerObjectLightProbeProxyVolume |
            RendererConfiguration.PerObjectShadowMask |
            RendererConfiguration.PerObjectOcclusionProbe |
            RendererConfiguration.PerObjectOcclusionProbeProxyVolume;

        drawSettings.sorting.flags = SortFlags.CommonOpaque;
        var filterSettings = new FilterRenderersSettings(true)
        {
            renderQueueRange = RenderQueueRange.opaque
        };
        context.DrawRenderers(
            cull.visibleRenderers, ref drawSettings, filterSettings
            );

        context.DrawSkybox(camera);

        if (activeStack)
        {
            if (needsDepthOnlyPass)
            {
                var depthOnlyDrawSettings = new DrawRendererSettings(
                    camera, new ShaderPassName("DepthOnly")
                    )
                {
                    flags = drawFlags
                };
                depthOnlyDrawSettings.sorting.flags = SortFlags.CommonOpaque;
                cameraBuffer.SetRenderTarget(
                    cameraDepthTextureId,
                    RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store
                    );
                cameraBuffer.ClearRenderTarget(true, false, Color.clear);
                context.ExecuteCommandBuffer(cameraBuffer);
                cameraBuffer.Clear();
                context.DrawRenderers(
                    cull.visibleRenderers, ref depthOnlyDrawSettings, filterSettings
                    );
            }
            activeStack.RenderAfterOpaque(
                postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId,
                renderWidth, renderHeight, msaaSamples, format
                );
            context.ExecuteCommandBuffer(postProcessingBuffer);
            postProcessingBuffer.Clear();

            if (needsDirectDepth)
            {
                cameraBuffer.SetRenderTarget(
                    cameraColorTextureId,
                    RenderBufferLoadAction.Load, RenderBufferStoreAction.Store,
                    cameraDepthTextureId,
                    RenderBufferLoadAction.Load, RenderBufferStoreAction.Store
                    );
            }
            else
            {
                cameraBuffer.SetRenderTarget(
                    cameraColorTextureId,
                    RenderBufferLoadAction.Load, RenderBufferStoreAction.Store
                    );
            }

            context.ExecuteCommandBuffer(cameraBuffer);
            cameraBuffer.Clear();
        }

        drawSettings.sorting.flags      = SortFlags.CommonTransparent;
        filterSettings.renderQueueRange = RenderQueueRange.transparent;
        context.DrawRenderers(
            cull.visibleRenderers, ref drawSettings, filterSettings
            );

        DrawDefaultPipeline(context, camera);

        if (renderToTexture)
        {
            if (activeStack)
            {
                activeStack.RenderAfterTransparent(
                    postProcessingBuffer, cameraColorTextureId, cameraDepthTextureId,
                    renderWidth, renderHeight, msaaSamples, format
                    );
                context.ExecuteCommandBuffer(postProcessingBuffer);
                postProcessingBuffer.Clear();
            }
            else
            {
                cameraBuffer.Blit(
                    cameraColorTextureId, BuiltinRenderTextureType.CameraTarget
                    );
            }

            cameraBuffer.ReleaseTemporaryRT(cameraColorTextureId);
            if (needsDepth)
            {
                cameraBuffer.ReleaseTemporaryRT(cameraDepthTextureId);
            }
        }

        cameraBuffer.EndSample("Render Camera");
        context.ExecuteCommandBuffer(cameraBuffer);
        cameraBuffer.Clear();

        context.Submit();
        if (shadowMap)
        {
            RenderTexture.ReleaseTemporary(shadowMap);
            shadowMap = null;
        }
        if (cascadedShadowMap)
        {
            RenderTexture.ReleaseTemporary(cascadedShadowMap);
            cascadedShadowMap = null;
        }
    }
예제 #33
0
		public static RenderTexture GetTemporary(int width, int height, int depthBuffer, RenderTextureFormat format)
		{
			int antiAliasing = 1;
			RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default;
			return RenderTexture.GetTemporary(width, height, depthBuffer, format, readWrite, antiAliasing);
		}
예제 #34
0
 public RenderTexture(int width, int height, int depth, RenderTextureFormat format)
     : this(width, height, depth, format, RenderTextureReadWrite.Default)
 {
 }
예제 #35
0
        private bool CheckSmallAdaptiveRt()
        {
            if (m_SmallAdaptiveRt != null)
                return false;

            m_AdaptiveRtFormat = RenderTextureFormat.ARGBHalf;

            if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RGHalf))
                m_AdaptiveRtFormat = RenderTextureFormat.RGHalf;

            m_SmallAdaptiveRt = new RenderTexture(1, 1, 0, m_AdaptiveRtFormat);
            m_SmallAdaptiveRt.hideFlags = HideFlags.DontSave;

            return true;
        }
예제 #36
0
 public RenderTextureDescriptor(int width, int height, RenderTextureFormat colorFormat) : this(width, height, colorFormat, 0)
 {
 }
예제 #37
0
                public void MakeRecordRaw(CommandBuffer cb, RenderTargetIdentifier source, int width, int height, RenderTextureFormat format)
                {
                    Release();

                    lumaTexture            = RenderTexture.GetTemporary(width, height, 0, format);
                    lumaTexture.filterMode = FilterMode.Point;

                    cb.SetGlobalTexture(Uniforms._MainTex, source);
                    cb.Blit(source, lumaTexture);

                    m_Time = Time.time;
                }
예제 #38
0
 // Helpers
 private RenderTexture CreateTempBuffer(int width, int height, int depth, RenderTextureFormat format)
 {
     return(RenderTexture.GetTemporary(width, height, depth, format));
 }
예제 #39
0
    private bool PopulateLayer(int mipLevels, bool isHdr, OVRPlugin.Sizei size, int sampleCount, int stage)
    {
        if (isExternalSurface)
        {
            return(true);
        }

        bool ret = false;

        RenderTextureFormat rtFormat = (isHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;

        for (int eyeId = 0; eyeId < texturesPerStage; ++eyeId)
        {
            Texture et = layerTextures[eyeId].swapChain[stage];
            if (et == null)
            {
                continue;
            }

            for (int mip = 0; mip < mipLevels; ++mip)
            {
                bool dataIsLinear = isHdr || (QualitySettings.activeColorSpace == ColorSpace.Linear);

                var rt = textures[eyeId] as RenderTexture;
#if UNITY_ANDROID && !UNITY_EDITOR
                dataIsLinear = true;                 //HACK: Graphics.CopyTexture causes linear->srgb conversion on target write with D3D but not GLES.
#endif
                // PC requries premultiplied Alpha
                bool requiresPremultipliedAlpha = !Application.isMobilePlatform;

                bool linearToSRGB = !isHdr && dataIsLinear;
                // if the texture needs to be premultiplied, premultiply it unless its already premultiplied
                bool premultiplyAlpha = requiresPremultipliedAlpha && !isAlphaPremultiplied;

                bool bypassBlit = !linearToSRGB && !premultiplyAlpha && rt != null && rt.format == rtFormat;

                RenderTexture tempRTDst = null;

                if (!bypassBlit)
                {
                    int width = size.w >> mip;
                    if (width < 1)
                    {
                        width = 1;
                    }
                    int height = size.h >> mip;
                    if (height < 1)
                    {
                        height = 1;
                    }
                    RenderTextureDescriptor descriptor = new RenderTextureDescriptor(width, height, rtFormat, 0);
                    descriptor.msaaSamples      = sampleCount;
                    descriptor.useMipMap        = true;
                    descriptor.autoGenerateMips = false;
                    descriptor.sRGB             = false;

                    tempRTDst = RenderTexture.GetTemporary(descriptor);

                    if (!tempRTDst.IsCreated())
                    {
                        tempRTDst.Create();
                    }

                    tempRTDst.DiscardContents();

                    Material blitMat = null;
                    if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
                    {
                        blitMat = tex2DMaterial;
                    }
                    else
                    {
                        blitMat = cubeMaterial;
                    }

                    blitMat.SetInt("_linearToSrgb", linearToSRGB ? 1 : 0);
                    blitMat.SetInt("_premultiply", premultiplyAlpha ? 1 : 0);
                    blitMat.SetInt("_flip", OVRPlugin.nativeXrApi == OVRPlugin.XrApi.OpenXR ? 1 : 0);
                }

                if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
                {
                    if (bypassBlit)
                    {
                        Graphics.CopyTexture(textures[eyeId], 0, mip, et, 0, mip);
                    }
                    else
                    {
                        if (overrideTextureRectMatrix)
                        {
                            BlitSubImage(textures[eyeId], tempRTDst, tex2DMaterial, GetBlitRect(eyeId));
                        }
                        else
                        {
                            Graphics.Blit(textures[eyeId], tempRTDst, tex2DMaterial);
                        }
                        //Resolve, decompress, swizzle, etc not handled by simple CopyTexture.
                        Graphics.CopyTexture(tempRTDst, 0, 0, et, 0, mip);
                    }
                }
                else                 // Cubemap
                {
                    for (int face = 0; face < 6; ++face)
                    {
                        cubeMaterial.SetInt("_face", face);
                        if (bypassBlit)
                        {
                            Graphics.CopyTexture(textures[eyeId], face, mip, et, face, mip);
                        }
                        else
                        {
                            //Resolve, decompress, swizzle, etc not handled by simple CopyTexture.
                            Graphics.Blit(textures[eyeId], tempRTDst, cubeMaterial);
                            Graphics.CopyTexture(tempRTDst, 0, 0, et, face, mip);
                        }
                    }
                }
                if (tempRTDst != null)
                {
                    RenderTexture.ReleaseTemporary(tempRTDst);
                }

                ret = true;
            }
        }

        return(ret);
    }
예제 #40
0
        // Token: 0x06001E48 RID: 7752 RVA: 0x0017A3D4 File Offset: 0x001785D4
        public override void PopulateCommandBuffer(CommandBuffer cb)
        {
            AmbientOcclusionModel.Settings settings = base.model.settings;
            Material mat      = this.context.materialFactory.Get("Hidden/Post FX/Blit");
            Material material = this.context.materialFactory.Get("Hidden/Post FX/Ambient Occlusion");

            material.shaderKeywords = null;
            material.SetFloat(AmbientOcclusionComponent.Uniforms._Intensity, settings.intensity);
            material.SetFloat(AmbientOcclusionComponent.Uniforms._Radius, settings.radius);
            material.SetFloat(AmbientOcclusionComponent.Uniforms._Downsample, settings.downsampling ? 0.5f : 1f);
            material.SetInt(AmbientOcclusionComponent.Uniforms._SampleCount, (int)settings.sampleCount);
            if (!this.context.isGBufferAvailable && RenderSettings.fog)
            {
                material.SetVector(AmbientOcclusionComponent.Uniforms._FogParams, new Vector3(RenderSettings.fogDensity, RenderSettings.fogStartDistance, RenderSettings.fogEndDistance));
                switch (RenderSettings.fogMode)
                {
                case FogMode.Linear:
                    material.EnableKeyword("FOG_LINEAR");
                    break;

                case FogMode.Exponential:
                    material.EnableKeyword("FOG_EXP");
                    break;

                case FogMode.ExponentialSquared:
                    material.EnableKeyword("FOG_EXP2");
                    break;
                }
            }
            else
            {
                material.EnableKeyword("FOG_OFF");
            }
            int width  = this.context.width;
            int height = this.context.height;
            int num    = settings.downsampling ? 2 : 1;
            int nameID = AmbientOcclusionComponent.Uniforms._OcclusionTexture1;

            cb.GetTemporaryRT(nameID, width / num, height / num, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
            cb.Blit(null, nameID, material, (int)this.occlusionSource);
            int occlusionTexture = AmbientOcclusionComponent.Uniforms._OcclusionTexture2;

            cb.GetTemporaryRT(occlusionTexture, width, height, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
            cb.SetGlobalTexture(AmbientOcclusionComponent.Uniforms._MainTex, nameID);
            cb.Blit(nameID, occlusionTexture, material, (this.occlusionSource == AmbientOcclusionComponent.OcclusionSource.GBuffer) ? 4 : 3);
            cb.ReleaseTemporaryRT(nameID);
            nameID = AmbientOcclusionComponent.Uniforms._OcclusionTexture;
            cb.GetTemporaryRT(nameID, width, height, 0, FilterMode.Bilinear, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear);
            cb.SetGlobalTexture(AmbientOcclusionComponent.Uniforms._MainTex, occlusionTexture);
            cb.Blit(occlusionTexture, nameID, material, 5);
            cb.ReleaseTemporaryRT(occlusionTexture);
            if (this.context.profile.debugViews.IsModeActive(BuiltinDebugViewsModel.Mode.AmbientOcclusion))
            {
                cb.SetGlobalTexture(AmbientOcclusionComponent.Uniforms._MainTex, nameID);
                cb.Blit(nameID, BuiltinRenderTextureType.CameraTarget, material, 8);
                this.context.Interrupt();
            }
            else if (this.ambientOnlySupported)
            {
                cb.SetRenderTarget(this.m_MRT, BuiltinRenderTextureType.CameraTarget);
                cb.DrawMesh(GraphicsUtils.quad, Matrix4x4.identity, material, 0, 7);
            }
            else
            {
                RenderTextureFormat format = this.context.isHdr ? RenderTextureFormat.DefaultHDR : RenderTextureFormat.Default;
                int tempRT = AmbientOcclusionComponent.Uniforms._TempRT;
                cb.GetTemporaryRT(tempRT, this.context.width, this.context.height, 0, FilterMode.Bilinear, format);
                cb.Blit(BuiltinRenderTextureType.CameraTarget, tempRT, mat, 0);
                cb.SetGlobalTexture(AmbientOcclusionComponent.Uniforms._MainTex, tempRT);
                cb.Blit(tempRT, BuiltinRenderTextureType.CameraTarget, material, 6);
                cb.ReleaseTemporaryRT(tempRT);
            }
            cb.ReleaseTemporaryRT(nameID);
        }
 private static void ChangeSet(RenderTexture targetRT, int width, int height, int depth, RenderTextureFormat format)
 {
     targetRT.Release();
     targetRT.width  = width;
     targetRT.height = height;
     targetRT.depth  = depth;
     targetRT.format = format;
     targetRT.Create();
 }
예제 #42
0
        // Internal function
        RTHandle AllocAutoSizedRenderTexture(
            int width,
            int height,
            int slices,
            DepthBits depthBufferBits,
            GraphicsFormat colorFormat,
            FilterMode filterMode,
            TextureWrapMode wrapMode,
            TextureDimension dimension,
            bool enableRandomWrite,
            bool useMipMap,
            bool autoGenerateMips,
            bool isShadowMap,
            int anisoLevel,
            float mipMapBias,
            bool enableMSAA,
            bool bindTextureMS,
            bool useDynamicScale,
            bool xrInstancing,
            RenderTextureMemoryless memoryless,
            string name
            )
        {
            // Here user made a mistake in setting up msaa/bindMS, hence the warning
            if (!enableMSAA && bindTextureMS == true)
            {
                Debug.LogWarning("RTHandle allocated without MSAA but with bindMS set to true, forcing bindMS to false.");
                bindTextureMS = false;
            }

            bool allocForMSAA = m_ScaledRTSupportsMSAA ? enableMSAA : false;

            // Here we purposefully disable MSAA so we just force the bindMS param to false.
            if (!allocForMSAA)
            {
                bindTextureMS = false;
            }

            // MSAA Does not support random read/write.
            bool UAV = enableRandomWrite;

            if (allocForMSAA && (UAV == true))
            {
                Debug.LogWarning("RTHandle that is MSAA-enabled cannot allocate MSAA RT with 'enableRandomWrite = true'.");
                UAV = false;
            }

            int        msaaSamples = allocForMSAA ? (int)m_ScaledRTCurrentMSAASamples : 1;
            RTCategory category    = allocForMSAA ? RTCategory.MSAA : RTCategory.Regular;

            // XR override for instancing support
            VRTextureUsage vrUsage = VRTextureUsage.None;//TextureXR.OverrideRenderTexture(xrInstancing, ref dimension, ref slices);

            // We need to handle this in an explicit way since GraphicsFormat does not expose depth formats. TODO: Get rid of this branch once GraphicsFormat'll expose depth related formats
            RenderTexture rt;

            if (isShadowMap || depthBufferBits != DepthBits.None)
            {
                RenderTextureFormat format = isShadowMap ? RenderTextureFormat.Shadowmap : RenderTextureFormat.Depth;
                rt = new RenderTexture(width, height, (int)depthBufferBits, format, RenderTextureReadWrite.Linear)
                {
                    hideFlags         = HideFlags.HideAndDontSave,
                    volumeDepth       = slices,
                    filterMode        = filterMode,
                    wrapMode          = wrapMode,
                    dimension         = dimension,
                    enableRandomWrite = UAV,
                    useMipMap         = useMipMap,
                    autoGenerateMips  = autoGenerateMips,
                    anisoLevel        = anisoLevel,
                    mipMapBias        = mipMapBias,
                    antiAliasing      = msaaSamples,
                    bindTextureMS     = bindTextureMS,
                    useDynamicScale   = m_HardwareDynamicResRequested && useDynamicScale,
                    vrUsage           = vrUsage,
                    memorylessMode    = memoryless,
                    name = CoreUtils.GetRenderTargetAutoName(width, height, slices, GraphicsFormatUtility.GetRenderTextureFormat(colorFormat), name, mips: useMipMap, enableMSAA: allocForMSAA, msaaSamples: m_ScaledRTCurrentMSAASamples)
                };
            }
            else
            {
                rt = new RenderTexture(width, height, (int)depthBufferBits, colorFormat)
                {
                    hideFlags         = HideFlags.HideAndDontSave,
                    volumeDepth       = slices,
                    filterMode        = filterMode,
                    wrapMode          = wrapMode,
                    dimension         = dimension,
                    enableRandomWrite = UAV,
                    useMipMap         = useMipMap,
                    autoGenerateMips  = autoGenerateMips,
                    anisoLevel        = anisoLevel,
                    mipMapBias        = mipMapBias,
                    antiAliasing      = msaaSamples,
                    bindTextureMS     = bindTextureMS,
                    useDynamicScale   = m_HardwareDynamicResRequested && useDynamicScale,
                    vrUsage           = vrUsage,
                    memorylessMode    = memoryless,
                    name = CoreUtils.GetRenderTargetAutoName(width, height, slices, GraphicsFormatUtility.GetRenderTextureFormat(colorFormat), name, mips: useMipMap, enableMSAA: allocForMSAA, msaaSamples: m_ScaledRTCurrentMSAASamples)
                };
            }

            rt.Create();

            var rth = new RTHandle(this);

            rth.SetRenderTexture(rt, category);
            rth.m_EnableMSAA           = enableMSAA;
            rth.m_EnableRandomWrite    = enableRandomWrite;
            rth.useScaling             = true;
            rth.m_EnableHWDynamicScale = useDynamicScale;
            rth.m_Name = name;
            m_AutoSizedRTs.Add(rth);
            return(rth);
        }
예제 #43
0
 RenderTexture PushRenderTexture(int width, int height, int depth = 0, RenderTextureFormat format = RenderTextureFormat.Default)
 {
     var tex = RenderTexture.GetTemporary (width, height, depth, format);
     tex.filterMode = FilterMode.Point;
     tex.wrapMode = TextureWrapMode.Clamp;
     _tempRenderTextures.Add (tex);
     return tex;
 }
예제 #44
0
	private void Update()
	{
		if (!isVRPresent)
			return;

		if (!usingPositionTrackingCached || usingPositionTracking != usePositionTracking)
		{
			tracker.isEnabled = usePositionTracking;
			usingPositionTracking = usePositionTracking;
			usingPositionTrackingCached = true;
		}

		// Dispatch any events.
		if (HMDLost != null && wasHmdPresent && !display.isPresent)
			HMDLost();

		if (HMDAcquired != null && !wasHmdPresent && display.isPresent)
			HMDAcquired();

		wasHmdPresent = display.isPresent;

		if (Created != null && wasRecreated)
			Created();

		wasRecreated = false;

		if (TrackingLost != null && wasPositionTracked && !tracker.isPositionTracked)
			TrackingLost();

		if (TrackingAcquired != null && !wasPositionTracked && tracker.isPositionTracked)
			TrackingAcquired();

		wasPositionTracked = tracker.isPositionTracked;

#if (!UNITY_ANDROID || UNITY_EDITOR)
		OVRPlugin.nativeTextureScale = nativeTextureScale;
		OVRPlugin.virtualTextureScale = virtualTextureScale;
#endif

		if (NativeTextureScaleModified != null && nativeTextureScale != prevNativeTextureScale)
			NativeTextureScaleModified(prevNativeTextureScale, nativeTextureScale);

		prevNativeTextureScale = nativeTextureScale;

		if (VirtualTextureScaleModified != null && virtualTextureScale != prevVirtualTextureScale)
			VirtualTextureScaleModified(prevVirtualTextureScale, virtualTextureScale);

		prevVirtualTextureScale = virtualTextureScale;

		if (EyeTextureAntiAliasingModified != null && eyeTextureAntiAliasing != prevEyeTextureAntiAliasing)
			EyeTextureAntiAliasingModified(prevEyeTextureAntiAliasing, eyeTextureAntiAliasing);

		prevEyeTextureAntiAliasing = eyeTextureAntiAliasing;

		if (EyeTextureDepthModified != null && eyeTextureDepth != prevEyeTextureDepth)
			EyeTextureDepthModified(prevEyeTextureDepth, eyeTextureDepth);

		prevEyeTextureDepth = eyeTextureDepth;

		if (EyeTextureFormatModified != null && eyeTextureFormat != prevEyeTextureFormat)
			EyeTextureFormatModified(prevEyeTextureFormat, eyeTextureFormat);

		prevEyeTextureFormat = eyeTextureFormat;

		if (MonoscopicModified != null && monoscopic != prevMonoscopic)
			MonoscopicModified(prevMonoscopic, monoscopic);

		prevMonoscopic = monoscopic;

		if (HdrModified != null && hdr != prevHdr)
			HdrModified(prevHdr, hdr);

		prevHdr = hdr;

		if (isHSWDisplayed && Input.anyKeyDown)
		{
			DismissHSWDisplay();
			
			if (HSWDismissed != null)
				HSWDismissed();
		}

		display.timeWarp = timeWarp;

		display.Update();
		input.Update();

#if UNITY_ANDROID && !UNITY_EDITOR
		if (volumeController != null)
		{
			if (volumeControllerTransform == null)
			{
				if (gameObject.GetComponent<OVRCameraRig>() != null)
				{
					volumeControllerTransform = gameObject.GetComponent<OVRCameraRig>().centerEyeAnchor;
				}
			}
			volumeController.UpdatePosition(volumeControllerTransform);
		}

		// Service VrApi events
		// If this code is not called, internal VrApi events will never be pushed to the internal event queue.
		VrApiEventStatus pendingResult = (VrApiEventStatus)OVR_GetNextPendingEvent( EventData, (uint)MaxDataSize );
		while (pendingResult == VrApiEventStatus.PENDING)
		{
			if (OnVrApiEvent != null)
			{
				OnVrApiEvent(EventData.ToString());
			}
			else
			{
				Debug.Log("No OnVrApiEvent delegate set!");
			}

			EventData.Length = 0;
			pendingResult = (VrApiEventStatus)OVR_GetNextPendingEvent(EventData, (uint)MaxDataSize);
		}
#endif
	}
예제 #45
0
		protected void CreateBuffer(ref RenderTexture[] tex, RenderTextureFormat format) {
			tex = new RenderTexture[2];
			
			for (int i = 0; i < 2; i++) {
				tex[i] = new RenderTexture(m_fourierGridSize, m_fourierGridSize, 0, format);
				tex[i].filterMode = FilterMode.Point;
				tex[i].wrapMode = TextureWrapMode.Clamp;
				tex[i].Create();
			}
		}
예제 #46
0
 RenderTexture GetTemporaryRT(Texture source, int divider, RenderTextureFormat format)
 {
     var w = source.width / divider;
     var h = source.height / divider;
     var rt = RenderTexture.GetTemporary(w, h, 0, format);
     rt.filterMode = FilterMode.Point;
     return rt;
 }
예제 #47
0
	private void Awake()
	{
		// Only allow one instance at runtime.
		if (instance != null)
		{
			enabled = false;
			DestroyImmediate(this);
			return;
		}

		instance = this;

		System.Version netVersion = OVRPlugin.wrapperVersion;
		System.Version ovrVersion = OVRPlugin.version;
		
		Debug.Log("Unity v" + Application.unityVersion + ", " +
		          "Oculus Integration v" + netVersion + ", " +
		          "OVRPlugin v" + ovrVersion + ".");

        // Detect whether this platform is a supported platform
        RuntimePlatform currPlatform = Application.platform;
        isSupportedPlatform |= currPlatform == RuntimePlatform.Android;
        isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer;
        isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor;
        isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer;
        isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor;
        isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer;
        if (!isSupportedPlatform)
        {
            Debug.LogWarning("This platform is unsupported");
            return;
        }

#if !UNITY_ANDROID || UNITY_EDITOR
        if (OVRUnityVersionChecker.hasBuiltInVR)
        {
            Debug.LogWarning("The Oculus Unity Legacy Integration is only supported in Unity 4.x releases. For Unity 5.x, please migrate to the Oculus Utilities for Unity package and use Unity's built-in VR support (available in Unity 5.1 and later).");
            isVRPresent = false;
        }
		else if (!ovrIsInitialized)
		{
			//HACK: For some reason, Unity doesn't call UnitySetGraphicsDevice until we make the first P/Invoke call.
			OVRPluginEvent.eventBase = OVRPluginEvent.eventBase;

#if !UNITY_ANDROID || UNITY_EDITOR
			//Handle all log messages
			OVR_FlushLog(OnLogMessage);
#endif

			// If unable to load the Oculus Runtime.
			if (!OVRPlugin.initialized)
			{
				bool isBadWinRenderer =
					((Application.platform == RuntimePlatform.WindowsEditor ||
					  Application.platform == RuntimePlatform.WindowsPlayer) &&
					 !SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11"));

				if (isBadWinRenderer)
					Debug.LogWarning("Only D3D11 is supported on Windows.");
				else
					Debug.LogWarning("Runtime is not present or no Rift attached. Running without VR.");

				// Runtime is not installed if ovr_Initialize() fails.
				isVRPresent = false;
				// Go monoscopic in response.
				monoscopic = true;
			}
			else
			{
				OVRPluginEvent.Issue(RenderEventType.InitRenderThread);

				isVRPresent = true;

#if UNITY_EDITOR
				if (!OVRUnityVersionChecker.hasEditorVRSupport)
				{
					// Only allow VR in standalones.
					isVRPresent = false;
					Debug.LogWarning("VR rendering is not supported in the editor. Please update to 4.6.7p4 or build a stand-alone player.");
				}
#endif
				if (netVersion.Major > ovrVersion.Major || netVersion.Major == ovrVersion.Major && netVersion.Minor > ovrVersion.Minor)
				{
					isVRPresent = false;
					Debug.LogWarning("Version check failed. Please make sure you are using OVRPlugin " +
					                 Ovr.Hmd.OVR_VERSION_STRING + " or newer.");
				}

				OVRPlugin.queueAheadFraction = 0f;

				ovrIsInitialized = true;
			}
		}

		SetEditorPlay(Application.isEditor);

#else // UNITY_ANDROID && !UNITY_EDITOR: Start of Android init.

		// Android integration does not dynamically load its runtime.
		isVRPresent = true;

		// log the unity version
		Debug.Log( "Unity Version: " + Application.unityVersion );

		// don't allow the application to run if orientation is not landscape left.
		if (Screen.orientation != ScreenOrientation.LandscapeLeft)
		{
			Debug.LogError("********************************************************************************\n");
			Debug.LogError("***** Default screen orientation must be set to landscape left for VR.\n" +
			               "***** Stopping application.\n");
			Debug.LogError("********************************************************************************\n");

			Debug.Break();
			Application.Quit();
		}

		// don't enable gyro, it is not used and triggers expensive display calls
		if (Input.gyro.enabled)
		{
			Debug.LogError("*** Auto-disabling Gyroscope ***");
			Input.gyro.enabled = false;
		}
		
		// NOTE: On Adreno Lollipop, it is an error to have antiAliasing set on the
		// main window surface with front buffer rendering enabled. The view will
		// render black.
		// On Adreno KitKat, some tiling control modes will cause the view to render
		// black.
		if (QualitySettings.antiAliasing > 1)
		{
			Debug.LogError("*** Antialiasing must be disabled for Gear VR ***");
		}

		// we sync in the TimeWarp, so we don't want unity
		// syncing elsewhere
		QualitySettings.vSyncCount = 0;

		// try to render at 60fps
		Application.targetFrameRate = 60;
		// don't allow the app to run in the background
		Application.runInBackground = false;
		// Disable screen dimming
		Screen.sleepTimeout = SleepTimeout.NeverSleep;

		if (!androidJavaInit)
		{
			AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
			activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
			// Prepare for the RenderThreadInit()
			SetInitVariables(activity.GetRawObject(), System.IntPtr.Zero);

#if USE_ENTITLEMENT_CHECK
			AndroidJavaObject entitlementChecker = new AndroidJavaObject("com.oculus.svclib.OVREntitlementChecker");
			entitlementChecker.CallStatic("doAutomatedCheck", activity);
#else
			Debug.Log( "Inhibiting Entitlement Check!" );
#endif

			androidJavaInit = true;
		}

		// We want to set up our touchpad messaging system
		OVRTouchpad.Create();

		InitVolumeController();

		// set an event delegate like this if you wish to handle events like "reorient".
		//SetVrApiEventDelegate( VrApiEventDefaultDelegate );
#endif // End of android init.

		prevEyeTextureAntiAliasing = OVRManager.instance.eyeTextureAntiAliasing;
		prevEyeTextureDepth = OVRManager.instance.eyeTextureDepth;
		prevEyeTextureFormat = OVRManager.instance.eyeTextureFormat;
        prevNativeTextureScale = OVRManager.instance.nativeTextureScale;
        prevVirtualTextureScale = OVRManager.instance.virtualTextureScale;
        prevMonoscopic = OVRManager.instance.monoscopic;
        prevHdr = OVRManager.instance.hdr;

		if (tracker == null)
			tracker = new OVRTracker();

		if (display == null)
			display = new OVRDisplay();
		else
			wasRecreated = true;

		if (input == null)
			input = new OVRInput();

		if (resetTrackerOnLoad)
			display.RecenterPose();

#if !UNITY_ANDROID || UNITY_EDITOR
		// Except for D3D9, SDK rendering forces vsync unless you pass ovrHmdCap_NoVSync to Hmd.SetEnabledCaps().
		if (timeWarp)
		{
			bool useUnityVSync = SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9");
			QualitySettings.vSyncCount = useUnityVSync ? 1 : 0;
			QualitySettings.maxQueuedFrames = 0;
		}
#endif

#if UNITY_STANDALONE_WIN
		if (!OVRUnityVersionChecker.hasD3D9ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9"))
		{
			MessageBox(0, "Direct3D 9 extended mode is not supported in this configuration. "
				+ "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version."
				, "VR Configuration Warning", 0);
		}

		if (!OVRUnityVersionChecker.hasD3D11ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11"))
		{
			MessageBox(0, "Direct3D 11 extended mode is not supported in this configuration. "
				+ "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version."
				, "VR Configuration Warning", 0);
		}
#endif
	}
예제 #48
0
    public static RenderTexture GetRenderTexture(int width, int height, int depth, bool writable = false, RenderTextureFormat format = RenderTextureFormat.ARGBFloat)
    {
        var rt = new RenderTexture(width, height, depth, format);

        rt.enableRandomWrite = writable;
        rt.Create();
        return(rt);
    }
예제 #49
0
            bool CheckTextureFormatSupport()
            {
                // RGHalf is not supported = Can't use motion vectors.
                if (!SystemInfo.SupportsRenderTextureFormat(_vectorRTFormat))
                    return false;

                // If 2:10:10:10 isn't supported, use ARGB32 instead.
                if (!SystemInfo.SupportsRenderTextureFormat(_packedRTFormat))
                    _packedRTFormat = RenderTextureFormat.ARGB32;

                return true;
            }
예제 #50
0
    private bool PopulateLayer(int mipLevels, bool isHdr, OVRPlugin.Sizei size, int sampleCount)
    {
        bool ret = false;

        RenderTextureFormat rtFormat = (isHdr) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;

        for (int eyeId = 0; eyeId < texturesPerStage; ++eyeId)
        {
            int dstElement = (layout == OVRPlugin.LayerLayout.Array) ? eyeId : 0;

            int     stage = frameIndex % stageCount;
            Texture et    = layerTextures[eyeId].swapChain[stage];
            if (et == null)
            {
                continue;
            }

            for (int mip = 0; mip < mipLevels; ++mip)
            {
#if UNITY_2017_1_1 || UNITY_2017_2_OR_NEWER
                int width = size.w >> mip;
                if (width < 1)
                {
                    width = 1;
                }
                int height = size.h >> mip;
                if (height < 1)
                {
                    height = 1;
                }

                RenderTextureDescriptor descriptor = new RenderTextureDescriptor(width, height, rtFormat, 0);
                descriptor.msaaSamples      = sampleCount;
                descriptor.useMipMap        = true;
                descriptor.autoGenerateMips = false;

                var tempRTDst = RenderTexture.GetTemporary(descriptor);
#else
                var tempRTDst = RenderTexture.GetTemporary(size.w >> mip, size.h >> mip, 0, rtFormat, RenderTextureReadWrite.Default, sampleCount);
#endif

                if (!tempRTDst.IsCreated())
                {
                    tempRTDst.Create();
                }

                tempRTDst.DiscardContents();

                if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
                {
#if UNITY_ANDROID && !UNITY_EDITOR
                    if (((textures[eyeId] as Cubemap) != null) &&
                        ((et as Cubemap) != null) &&
                        ((textures[eyeId] as Cubemap).format == (et as Cubemap).format))
                    {
                        Graphics.CopyTexture(textures[eyeId], 0, mip, et, 0, mip);
                    }
                    else
                    {
                        Graphics.Blit(textures[eyeId], tempRTDst);                         //Resolve, decompress, swizzle, etc not handled by simple CopyTexture.
                        Graphics.CopyTexture(tempRTDst, 0, 0, et, dstElement, mip);
                    }
#else
                    // The PC compositor uses premultiplied alpha, so multiply it here.
                    Graphics.Blit(textures[eyeId], tempRTDst, premultiplyMaterial);
                    Graphics.CopyTexture(tempRTDst, 0, 0, et, dstElement, mip);
#endif
                }
#if UNITY_2017_1_OR_NEWER
                else                 // Cubemap
                {
                    var tempRTSrc = RenderTexture.GetTemporary(size.w >> mip, size.h >> mip, 0, rtFormat, RenderTextureReadWrite.Default, sampleCount);

                    if (!tempRTSrc.IsCreated())
                    {
                        tempRTSrc.Create();
                    }

                    tempRTSrc.DiscardContents();

                    for (int face = 0; face < 6; ++face)
                    {
#if UNITY_ANDROID && !UNITY_EDITOR
                        if ((textures[eyeId] as Cubemap).format == (et as Cubemap).format)
                        {
                            Graphics.CopyTexture(textures[eyeId], face, mip, et, 0, mip);
                        }
                        else
                        {
                            //HACK: It would be much more efficient to blit directly from textures[eyeId] to et, but Unity's API doesn't support that.
                            //Suggest using a native plugin to render directly to a cubemap layer for 360 video, etc.
                            Graphics.CopyTexture(textures[eyeId], face, mip, tempRTSrc, 0, 0);
                            Graphics.Blit(tempRTSrc, tempRTDst);
                            Graphics.CopyTexture(tempRTDst, 0, 0, et, face, mip);
                        }
#else
                        //HACK: It would be much more efficient to blit directly from textures[eyeId] to et, but Unity's API doesn't support that.
                        //Suggest using a native plugin to render directly to a cubemap layer for 360 video, etc.
                        Graphics.CopyTexture(textures[eyeId], face, mip, tempRTSrc, 0, 0);
                        // The PC compositor uses premultiplied alpha, so multiply it here.
                        Graphics.Blit(tempRTSrc, tempRTDst, premultiplyMaterial);
                        Graphics.CopyTexture(tempRTDst, 0, 0, et, face, mip);
#endif
                    }
                    RenderTexture.ReleaseTemporary(tempRTSrc);
                }
#endif
                RenderTexture.ReleaseTemporary(tempRTDst);

                ret = true;
            }
        }

        return(ret);
    }
예제 #51
0
        public void CreateRenderTexture()
        {
            if (m_textureWidth <= 0 || m_textureHeight <= 0 || m_projector == null)
            {
                return;
            }
            // choose a texture format
            RenderTextureFormat textureFormat = RenderTextureFormat.ARGB32;

            if (m_preferredTextureFormats != null && 0 < m_preferredTextureFormats.Length)
            {
                foreach (RenderTextureFormat format in m_preferredTextureFormats)
                {
                    if (SystemInfo.SupportsRenderTextureFormat(textureFormat))
                    {
                        textureFormat = format;
                    }
                }
            }
            // create texture
            if (m_shadowTexture != null)
            {
                if (m_camera != null)
                {
                    m_camera.targetTexture = null;
                }
                DestroyImmediate(m_shadowTexture);
            }
            m_shadowTexture = new RenderTexture(m_textureWidth, m_textureHeight, 0, textureFormat, RenderTextureReadWrite.Linear);
            if (useIntermediateTexture)
            {
                m_shadowTexture.antiAliasing = 1;
            }
            else
            {
                m_shadowTexture.antiAliasing = (int)m_multiSampling;
            }
            if (0 < m_mipLevel)
            {
                m_shadowTexture.useMipMap        = true;
                m_shadowTexture.autoGenerateMips = false;
                m_shadowTexture.mipMapBias       = 0.0f;
                m_shadowTexture.filterMode       = FilterMode.Trilinear;
            }
            else
            {
                m_shadowTexture.useMipMap  = false;
                m_shadowTexture.filterMode = FilterMode.Bilinear;
            }
            m_shadowTexture.wrapMode = TextureWrapMode.Clamp;
            m_shadowTexture.Create();
            m_shadowTextureValid = false;
            if (m_projector.material != null)
            {
                m_projector.material.SetTexture("_ShadowTex", m_shadowTexture);
                m_projector.material.SetFloat("_DSPMipLevel", m_mipLevel);
            }
            if (m_camera != null)
            {
                m_camera.targetTexture = m_shadowTexture;
            }
            m_isTexturePropertyChanged = false;
        }
예제 #52
0
    private void Awake()
    {
        // Only allow one instance at runtime.
        if (instance != null)
        {
            enabled = false;
            DestroyImmediate(this);
            return;
        }

        instance = this;

        // Detect whether this platform is a supported platform
        RuntimePlatform currPlatform = Application.platform;

        isSupportedPlatform |= currPlatform == RuntimePlatform.Android;
        isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer;
        isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor;
        isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer;
        isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor;
        isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer;
        if (!isSupportedPlatform)
        {
            Debug.LogWarning("This platform is unsupported");
            return;
        }

#if !UNITY_ANDROID || UNITY_EDITOR
        if (!ovrIsInitialized)
        {
            // If unable to load the Oculus Runtime,
            if (!OVR_Initialize())
            {
                Debug.LogWarning("Unable initialize VR. Please make sure the runtime is installed and running and a VR display is attached.");

                // Runtime is not installed if ovr_Initialize() fails.
                isVRPresent = false;
                // Go monoscopic in response.
                monoscopic = true;
            }
            else
            {
                OVRPluginEvent.Issue(RenderEventType.Initialize);

                isVRPresent = true;

#if UNITY_EDITOR
                // Only allow VR in the editor in extended mode.
                uint caps = capiHmd.GetDesc().HmdCaps;
                uint mask = caps & (uint)HmdCaps.ExtendDesktop;

                isVRPresent = (mask != 0);

                if (!isVRPresent)
                {
                    Debug.LogWarning("VR direct mode rendering is not supported in the editor. Please use extended mode or build a stand-alone player.");
                }
#endif

                ovrIsInitialized = true;
            }
        }

        if (isVRPresent)
        {
            var            netVersion    = new System.Version(Ovr.Hmd.OVR_VERSION_STRING);
            System.Version ovrVersion    = new System.Version("0.0.0");
            var            versionString = Ovr.Hmd.GetVersionString();
            var            success       = false;
            try {
                ovrVersion = new System.Version(versionString);
                success    = true;
            } catch (Exception e) {
                Debug.Log("Failed to parse Oculus version string \"" + versionString + "\" with message \"" + e.Message + "\".");
            }
            if (!success || netVersion > ovrVersion)
            {
                Debug.LogWarning("Version check failed. Please make sure you are using Oculus runtime " +
                                 Ovr.Hmd.OVR_VERSION_STRING + " or newer.");
            }
        }

        SetEditorPlay(Application.isEditor);
#else // UNITY_ANDROID && !UNITY_EDITOR: Start of Android init.
        // Android integration does not dynamically load its runtime.
        isVRPresent = true;

        // log the unity version
        Debug.Log("Unity Version: " + Application.unityVersion);

        // don't allow the application to run if orientation is not landscape left.
        if (Screen.orientation != ScreenOrientation.LandscapeLeft)
        {
            Debug.LogError("********************************************************************************\n");
            Debug.LogError("***** Default screen orientation must be set to landscape left for VR.\n" +
                           "***** Stopping application.\n");
            Debug.LogError("********************************************************************************\n");

            Debug.Break();
            Application.Quit();
        }

        // don't enable gyro, it is not used and triggers expensive display calls
        if (Input.gyro.enabled)
        {
            Debug.LogError("*** Auto-disabling Gyroscope ***");
            Input.gyro.enabled = false;
        }

        // NOTE: On Adreno Lollipop, it is an error to have antiAliasing set on the
        // main window surface with front buffer rendering enabled. The view will
        // render black.
        // On Adreno KitKat, some tiling control modes will cause the view to render
        // black.
        if (QualitySettings.antiAliasing > 1)
        {
            Debug.LogError("*** Antialiasing must be disabled for Gear VR ***");
        }

        // we sync in the TimeWarp, so we don't want unity
        // syncing elsewhere
        QualitySettings.vSyncCount = 0;

        // try to render at 60fps
        Application.targetFrameRate = 60;
        // don't allow the app to run in the background
        Application.runInBackground = false;
        // Disable screen dimming
        Screen.sleepTimeout = SleepTimeout.NeverSleep;

        if (!androidJavaInit)
        {
            AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            activity = unityPlayer.GetStatic <AndroidJavaObject>("currentActivity");
            // Prepare for the RenderThreadInit()
            SetInitVariables(activity.GetRawObject(), System.IntPtr.Zero);

#if USE_ENTITLEMENT_CHECK
            AndroidJavaObject entitlementChecker = new AndroidJavaObject("com.oculus.svclib.OVREntitlementChecker");
            entitlementChecker.CallStatic("doAutomatedCheck", activity);
#else
            Debug.Log("Inhibiting Entitlement Check!");
#endif

            androidJavaInit = true;
        }

        // We want to set up our touchpad messaging system
        OVRTouchpad.Create();

        InitVolumeController();

        // set an event delegate like this if you wish to handle events like "reorient".
        //SetVrApiEventDelegate( VrApiEventDefaultDelegate );
#endif // End of android init.

        prevEyeTextureAntiAliasing = OVRManager.instance.eyeTextureAntiAliasing;
        prevEyeTextureDepth        = OVRManager.instance.eyeTextureDepth;
        prevEyeTextureFormat       = OVRManager.instance.eyeTextureFormat;
        prevNativeTextureScale     = OVRManager.instance.nativeTextureScale;
        prevVirtualTextureScale    = OVRManager.instance.virtualTextureScale;
        prevMonoscopic             = OVRManager.instance.monoscopic;
        prevHdr = OVRManager.instance.hdr;

        if (tracker == null)
        {
            tracker = new OVRTracker();
        }
        if (display == null)
        {
            display = new OVRDisplay();
        }
        else
        {
            wasRecreated = true;
        }

        if (resetTrackerOnLoad)
        {
            display.RecenterPose();
        }

#if !UNITY_ANDROID || UNITY_EDITOR
        // Except for D3D9, SDK rendering forces vsync unless you pass ovrHmdCap_NoVSync to Hmd.SetEnabledCaps().
        if (timeWarp)
        {
            bool useUnityVSync = SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9");
            QualitySettings.vSyncCount = useUnityVSync ? 1 : 0;
        }
#endif

#if UNITY_STANDALONE_WIN
        if (!OVRUnityVersionChecker.hasD3D9ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9"))
        {
            MessageBox(0, "Direct3D 9 extended mode is not supported in this configuration. "
                       + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version."
                       , "VR Configuration Warning", 0);
        }

        if (!OVRUnityVersionChecker.hasD3D11ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11"))
        {
            MessageBox(0, "Direct3D 11 extended mode is not supported in this configuration. "
                       + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version."
                       , "VR Configuration Warning", 0);
        }
#endif
    }
예제 #53
0
		public void GetTemporaryRT(int nameID, int width, int height, int depthBuffer, FilterMode filter, RenderTextureFormat format)
		{
			int antiAliasing = 1;
			RenderTextureReadWrite readWrite = RenderTextureReadWrite.Default;
			this.GetTemporaryRT(nameID, width, height, depthBuffer, filter, format, readWrite, antiAliasing);
		}
예제 #54
0
    private void Update()
    {
        if (!isVRPresent)
        {
            return;
        }

        if (!usingPositionTrackingCached || usingPositionTracking != usePositionTracking)
        {
            tracker.isEnabled           = usePositionTracking;
            usingPositionTracking       = usePositionTracking;
            usingPositionTrackingCached = true;
        }

        // Dispatch any events.
        if (HMDLost != null && wasHmdPresent && !display.isPresent)
        {
            HMDLost();
        }

        if (HMDAcquired != null && !wasHmdPresent && display.isPresent)
        {
            HMDAcquired();
        }

        wasHmdPresent = display.isPresent;

        if (Created != null && wasRecreated)
        {
            Created();
        }

        wasRecreated = false;

        if (TrackingLost != null && wasPositionTracked && !tracker.isPositionTracked)
        {
            TrackingLost();
        }

        if (TrackingAcquired != null && !wasPositionTracked && tracker.isPositionTracked)
        {
            TrackingAcquired();
        }

        wasPositionTracked = tracker.isPositionTracked;

        if (NativeTextureScaleModified != null && nativeTextureScale != prevNativeTextureScale)
        {
            NativeTextureScaleModified(prevNativeTextureScale, nativeTextureScale);
        }

        prevNativeTextureScale = nativeTextureScale;

        if (VirtualTextureScaleModified != null && virtualTextureScale != prevVirtualTextureScale)
        {
            VirtualTextureScaleModified(prevVirtualTextureScale, virtualTextureScale);
        }

        prevVirtualTextureScale = virtualTextureScale;

        if (EyeTextureAntiAliasingModified != null && eyeTextureAntiAliasing != prevEyeTextureAntiAliasing)
        {
            EyeTextureAntiAliasingModified(prevEyeTextureAntiAliasing, eyeTextureAntiAliasing);
        }

        prevEyeTextureAntiAliasing = eyeTextureAntiAliasing;

        if (EyeTextureDepthModified != null && eyeTextureDepth != prevEyeTextureDepth)
        {
            EyeTextureDepthModified(prevEyeTextureDepth, eyeTextureDepth);
        }

        prevEyeTextureDepth = eyeTextureDepth;

        if (EyeTextureFormatModified != null && eyeTextureFormat != prevEyeTextureFormat)
        {
            EyeTextureFormatModified(prevEyeTextureFormat, eyeTextureFormat);
        }

        prevEyeTextureFormat = eyeTextureFormat;

        if (MonoscopicModified != null && monoscopic != prevMonoscopic)
        {
            MonoscopicModified(prevMonoscopic, monoscopic);
        }

        prevMonoscopic = monoscopic;

        if (HdrModified != null && hdr != prevHdr)
        {
            HdrModified(prevHdr, hdr);
        }

        prevHdr = hdr;

        if (isHSWDisplayed)
        {
            DismissHSWDisplay();

            if (HSWDismissed != null)
            {
                HSWDismissed();
            }
        }

        display.timeWarp = timeWarp;

        display.Update();

#if UNITY_ANDROID && !UNITY_EDITOR
        if (volumeController != null)
        {
            if (volumeControllerTransform == null)
            {
                if (gameObject.GetComponent <OVRCameraRig>() != null)
                {
                    volumeControllerTransform = gameObject.GetComponent <OVRCameraRig>().centerEyeAnchor;
                }
            }
            volumeController.UpdatePosition(volumeControllerTransform);
        }

        // Service VrApi events
        // If this code is not called, internal VrApi events will never be pushed to the internal event queue.
        VrApiEventStatus pendingResult = (VrApiEventStatus)OVR_GetNextPendingEvent(EventData, (uint)MaxDataSize);
        while (pendingResult == VrApiEventStatus.PENDING)
        {
            if (OnVrApiEvent != null)
            {
                OnVrApiEvent(EventData.ToString());
            }
            else
            {
                Debug.Log("No OnVrApiEvent delegate set!");
            }

            EventData.Length = 0;
            pendingResult    = (VrApiEventStatus)OVR_GetNextPendingEvent(EventData, (uint)MaxDataSize);
        }
#endif
    }
예제 #55
0
 private void OnEnable()
 {
     SSSSS.Instance = this;
     this.InitialFOV = Camera.main.fieldOfView;
     if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf))
     {
         this.RTT_Format = RenderTextureFormat.ARGBHalf;
     }
     else if (SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBFloat))
     {
         this.RTT_Format = RenderTextureFormat.ARGBFloat;
     }
     else
     {
         this.RTT_Format = RenderTextureFormat.ARGB32;
     }
     Camera.main.depthTextureMode |= DepthTextureMode.DepthNormals;
     this.Shader_SSSSS_Camera = Shader.Find("Hidden/SSSSS_Camera");
     if (this.Shader_SSSSS_Camera == null)
     {
         Debug.Log("#ERROR# Hidden/SSSSS_Camera Shader not found");
     }
     this.Material_SSSSS_Camera = new Material(this.Shader_SSSSS_Camera);
     this.Shader_SSSSS_Skin = Shader.Find("Hidden/Skin Composite");
     if (this.Shader_SSSSS_Skin == null)
     {
         Debug.Log("#ERROR# The Forest/SSSSS_Skin Shader not found");
     }
 }
예제 #56
0
 private void OnRenderImage(RenderTexture source, RenderTexture destination)
 {
     if (!this.CheckResources())
     {
         Graphics.Blit(source, destination);
     }
     else
     {
         if (this.useDepthTexture)
         {
             Camera component = base.GetComponent <Camera>();
             component.depthTextureMode |= DepthTextureMode.Depth;
         }
         int num = 4;
         if (this.resolution == SunShaftsResolution.Normal)
         {
             num = 2;
         }
         else if (this.resolution == SunShaftsResolution.High)
         {
             num = 1;
         }
         Vector3 vector = Vector3.one * 0.5f;
         if (this.sunTransform)
         {
             vector = base.GetComponent <Camera>().WorldToViewportPoint(this.sunTransform.position);
         }
         else
         {
             vector = new Vector3(0.5f, 0.5f, 0f);
         }
         int           width  = source.width / num;
         int           height = source.height / num;
         RenderTexture dest   = RenderTexture.GetTemporary(width, height, 0);
         this.sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(1f, 1f, 0f, 0f) * this.sunShaftBlurRadius);
         this.sunShaftsMaterial.SetVector("_SunPosition", new Vector4(vector.x, vector.y, vector.z, this.maxRadius));
         this.sunShaftsMaterial.SetVector("_SunThreshold", (Vector4)this.sunThreshold);
         if (this.useDepthTexture)
         {
             Graphics.Blit(source, dest, this.sunShaftsMaterial, 2);
         }
         else
         {
             RenderTextureFormat format   = !base.GetComponent <Camera>().hdr ? RenderTextureFormat.Default : RenderTextureFormat.DefaultHDR;
             RenderTexture       texture3 = RenderTexture.GetTemporary(source.width, source.height, 0, format);
             RenderTexture.active = texture3;
             GL.ClearWithSkybox(false, base.GetComponent <Camera>());
             this.sunShaftsMaterial.SetTexture("_Skybox", texture3);
             Graphics.Blit(source, dest, this.sunShaftsMaterial, 3);
             RenderTexture.ReleaseTemporary(texture3);
         }
         base.DrawBorder(dest, this.simpleClearMaterial);
         this.radialBlurIterations = Mathf.Clamp(this.radialBlurIterations, 1, 4);
         float x = this.sunShaftBlurRadius * 0.001302083f;
         this.sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(x, x, 0f, 0f));
         this.sunShaftsMaterial.SetVector("_SunPosition", new Vector4(vector.x, vector.y, vector.z, this.maxRadius));
         for (int i = 0; i < this.radialBlurIterations; i++)
         {
             RenderTexture texture = RenderTexture.GetTemporary(width, height, 0);
             Graphics.Blit(dest, texture, this.sunShaftsMaterial, 1);
             RenderTexture.ReleaseTemporary(dest);
             x = (this.sunShaftBlurRadius * (((i * 2f) + 1f) * 6f)) / 768f;
             this.sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(x, x, 0f, 0f));
             dest = RenderTexture.GetTemporary(width, height, 0);
             Graphics.Blit(texture, dest, this.sunShaftsMaterial, 1);
             RenderTexture.ReleaseTemporary(texture);
             x = (this.sunShaftBlurRadius * (((i * 2f) + 2f) * 6f)) / 768f;
             this.sunShaftsMaterial.SetVector("_BlurRadius4", new Vector4(x, x, 0f, 0f));
         }
         if (vector.z >= 0f)
         {
             this.sunShaftsMaterial.SetVector("_SunColor", new Vector4(this.sunColor.r, this.sunColor.g, this.sunColor.b, this.sunColor.a) * this.sunShaftIntensity);
         }
         else
         {
             this.sunShaftsMaterial.SetVector("_SunColor", Vector4.zero);
         }
         this.sunShaftsMaterial.SetTexture("_ColorBuffer", dest);
         Graphics.Blit(source, destination, this.sunShaftsMaterial, (this.screenBlendMode != ShaftsScreenBlendMode.Screen) ? 4 : 0);
         RenderTexture.ReleaseTemporary(dest);
     }
 }
예제 #57
0
 private bool CreateInternalRenderTexture()
 {
     if (rt) {
         return false;
     }
     rtFormat = SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.RGHalf) ? RenderTextureFormat.RGHalf : RenderTextureFormat.ARGBHalf;
     rt = new RenderTexture(1, 1, 0, rtFormat);
     rt.hideFlags = HideFlags.DontSave;
     return true;
 }
예제 #58
0
        private void Start()
        {
            if (GameData.Instance.testServer || GameData.IsHeadlessServer)
            {
                Debug.Log("Turn off lightsystem as this is a server");
                enabled = false;
            }
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                Shader.SetGlobalTexture("_ObstacleTex", Texture2D.whiteTexture);
                return;
            }
#endif

            if (LightCamera == null)
            {
                Debug.LogError(
                    "Lighting Camera in LightingSystem is null. Please, select Lighting Camera camera for lighting to work.");
                enabled = false;
                return;
            }
            if (LightOverlayMaterial == null)
            {
                Debug.LogError(
                    "LightOverlayMaterial in LightingSystem is null. Please, select LightOverlayMaterial camera for lighting to work.");
                enabled = false;
                return;
            }
            if (AffectOnlyThisCamera && _camera.targetTexture != null)
            {
                Debug.LogError("\"Affect Only This Camera\" will not work if camera.targetTexture is set.");
                AffectOnlyThisCamera = false;
            }

            _camera = GetComponent <Camera>();

            if (EnableNormalMapping && !_camera.orthographic)
            {
                Debug.LogError("Normal mapping is not supported with perspective camera.");
                EnableNormalMapping = false;
            }

            // if both FlareLayer component and AffectOnlyThisCamera setting is enabled
            // Unity will print an error "Flare renderer to update not found"
            FlareLayer flare = GetComponent <FlareLayer>();
            if (flare != null && flare.enabled)
            {
                Debug.Log("Disabling FlareLayer since AffectOnlyThisCamera setting is checked.");
                flare.enabled = false;
            }

            if (!SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBHalf))
            {
                HDR = false;
            }
            _texFormat = HDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;

            float lightPixelsPerUnityMeter = LightPixelsPerUnityMeter;

            _halfTexelOffest = SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 9");

            InitTK2D();

            if (_camera.orthographic)
            {
                float rawCamHeight = (_camera.orthographicSize + LightCameraSizeAdd) * 2f;
                float rawCamWidth  = (_camera.orthographicSize * _camera.aspect + LightCameraSizeAdd) * 2f;

                _extendedLightTextureSize = new Point2(
                    Mathf.RoundToInt(rawCamWidth * lightPixelsPerUnityMeter),
                    Mathf.RoundToInt(rawCamHeight * lightPixelsPerUnityMeter));

                float rawSmallCamHeight = _camera.orthographicSize * 2f * lightPixelsPerUnityMeter;
                _smallLightTextureSize = new Point2(
                    Mathf.RoundToInt(rawSmallCamHeight * _camera.aspect),
                    Mathf.RoundToInt(rawSmallCamHeight));
            }
            else
            {
                {
                    float lightCamHalfFov = (_camera.fieldOfView + LightCameraFovAdd) * Mathf.Deg2Rad / 2f;
                    float lightCamSize    = Mathf.Tan(lightCamHalfFov) * LightObstaclesDistance * 2;
                    //var gameCamHalfFov = _camera.fieldOfView*Mathf.Deg2Rad/2f;
                    int   texHeight = Mathf.RoundToInt(lightCamSize / LightPixelSize);
                    float texWidth  = texHeight * _camera.aspect;
                    _extendedLightTextureSize = Point2.Round(new Vector2(texWidth, texHeight));
                }
                {
                    float lightCamHalfFov = _camera.fieldOfView * Mathf.Deg2Rad / 2f;
                    float lightCamSize    = Mathf.Tan(lightCamHalfFov) * LightObstaclesDistance * 2;
                    //LightCamera.orthographicSize = lightCamSize/2f;

                    float gameCamHalfFov = _camera.fieldOfView * Mathf.Deg2Rad / 2f;
                    float gameCamSize    = Mathf.Tan(gameCamHalfFov) * LightObstaclesDistance * 2;
                    _camera.orthographicSize = gameCamSize / 2f;

                    int   texHeight = Mathf.RoundToInt(lightCamSize / LightPixelSize);
                    float texWidth  = texHeight * _camera.aspect;
                    _smallLightTextureSize = Point2.Round(new Vector2(texWidth, texHeight));
                }
            }

            if (_extendedLightTextureSize.x % 2 != 0)
            {
                _extendedLightTextureSize.x++;
            }
            if (_extendedLightTextureSize.y % 2 != 0)
            {
                _extendedLightTextureSize.y++;
            }

            if (_extendedLightTextureSize.x > 1024 || _extendedLightTextureSize.y > 1024 ||
                _smallLightTextureSize.x > 1024 || _smallLightTextureSize.y > 1024)
            {
                Debug.LogError("LightPixelSize is too small. That might have a performance impact.");
                return;
            }

            if (_extendedLightTextureSize.x < 4 || _extendedLightTextureSize.y < 4 ||
                _smallLightTextureSize.x < 4 || _smallLightTextureSize.y < 4)
            {
                Debug.LogError("LightPixelSize is too big. Lighting may not work correctly.");
                return;
            }

            _screenBlitTempTex            = new RenderTexture(_camera.pixelWidth, _camera.pixelHeight, 0, _texFormat);
            _screenBlitTempTex.filterMode = FilterMode.Point;

            LightCamera.orthographic = _camera.orthographic;

            if (EnableNormalMapping)
            {
                _lightSourcesTexture = new RenderTexture(_camera.pixelWidth, _camera.pixelHeight,
                                                         0, _texFormat);
                _lightSourcesTexture.filterMode = FilterMode.Point;
            }
            else
            {
                _lightSourcesTexture = new RenderTexture(_smallLightTextureSize.x, _smallLightTextureSize.y,
                                                         0, _texFormat);
                _lightSourcesTexture.filterMode = LightTexturesFilterMode;
            }

            _obstaclesTexture = new RenderTexture(_extendedLightTextureSize.x, _extendedLightTextureSize.y,
                                                  0, _texFormat);
            _ambientTexture = new RenderTexture(_extendedLightTextureSize.x, _extendedLightTextureSize.y,
                                                0, _texFormat);

            _ambientTexture.filterMode = LightTexturesFilterMode;

            Point2 upsampledObstacleSize = _extendedLightTextureSize * (LightObstaclesAntialiasing ? 2 : 1);
            _obstaclesUpsampledTexture = new RenderTexture(
                upsampledObstacleSize.x, upsampledObstacleSize.y, 0, _texFormat);

            if (AffectOnlyThisCamera)
            {
                _renderTargetTexture = new RenderTexture(_camera.pixelWidth, _camera.pixelHeight, -2,
                                                         RenderTextureFormat.ARGB32);
                _renderTargetTexture.filterMode = FilterMode.Point;
                _camera.targetTexture           = _renderTargetTexture;
                _camera.clearFlags      = CameraClearFlags.SolidColor;
                _camera.backgroundColor = Color.clear;
            }

            _alphaBlendedMaterial = new Material(Shader.Find("Light2D/Internal/Alpha Blended"));

            if (XZPlane)
            {
                Shader.EnableKeyword("LIGHT2D_XZ_PLANE");
            }
            else
            {
                Shader.DisableKeyword("LIGHT2D_XZ_PLANE");
            }

            _obstaclesPostProcessor = new ObstacleCameraPostPorcessor();

            LoopAmbientLight(100);
        }
예제 #59
0
        public HDShadowAtlas(RenderPipelineResources renderPipelineResources, int width, int height, int atlasShaderID, int atlasSizeShaderID, Material clearMaterial, BlurAlgorithm blurAlgorithm = BlurAlgorithm.None, FilterMode filterMode = FilterMode.Bilinear, DepthBits depthBufferBits = DepthBits.Depth16, RenderTextureFormat format = RenderTextureFormat.Shadowmap, string name = "", int momentAtlasShaderID = 0)
        {
            this.width                = width;
            this.height               = height;
            m_FilterMode              = filterMode;
            m_DepthBufferBits         = depthBufferBits;
            m_Format                  = format;
            m_Name                    = name;
            m_AtlasShaderID           = atlasShaderID;
            m_MomentAtlasShaderID     = momentAtlasShaderID;
            m_AtlasSizeShaderID       = atlasSizeShaderID;
            m_ClearMaterial           = clearMaterial;
            m_BlurAlgorithm           = blurAlgorithm;
            m_RenderPipelineResources = renderPipelineResources;

            AllocateRenderTexture();
        }
        public override void OnPreviewSettings()
        {
            if (IsCubemap())
            {
                //TODO perhaps support custom cubemap settings. Not currently!
                defaultEditor.OnPreviewSettings();
                return;
            }

            RenderTexture rT = target as RenderTexture;

            if (rT != null && IsVolume(rT))
            {
                editor3D.PreviewSettings();
                return;
            }

            // TextureInspector code is reused for RenderTexture and Cubemap inspectors.
            // Make sure we can handle the situation where target is just a Texture and
            // not a Texture2D. It's also used for large popups for mini texture fields,
            // and while it's being shown the actual texture object might disappear --
            // make sure to handle null targets.
            Texture tex = target as Texture;

            if (tex == null)
            {
                return;
            }

            bool showMode  = true;
            bool alphaOnly = false;
            bool hasAlpha  = true;
            int  mipCount  = 1;

            if (target is Texture2D)
            {
                alphaOnly = true;
                hasAlpha  = false;
            }

            bool hasR = false, hasG = false, hasB = false;

            // ReSharper disable once PossibleInvalidCastExceptionInForeachLoop
            foreach (Texture t in targets)
            {
                if (t == null)                 // texture might have disappeared while we're showing this in a preview popup
                {
                    continue;
                }

                TextureFormat format      = 0;
                bool          checkFormat = false;
                if (t is Texture2D texture2D)
                {
                    format      = texture2D.format;
                    checkFormat = true;
                }

                if (checkFormat)
                {
                    if (!IsAlphaOnlyTextureFormat(format))
                    {
                        alphaOnly = false;
                    }
                    if (HasAlphaTextureFormat(format))
                    {
                        TextureUsageMode mode = GetUsageMode(t);
                        if (mode == TextureUsageMode.Default)                         // all other texture usage modes don't displayable alpha
                        {
                            hasAlpha = true;
                        }
                    }

                    CheckRGBFormats(format, out bool _hasR, out bool _hasG, out bool _hasB);
                    hasR = hasR || _hasR;
                    hasG = hasG || _hasG;
                    hasB = hasB || _hasB;
                }

                mipCount = Mathf.Max(mipCount, GetMipmapCount(t));

                if (!checkFormat)
                {
                    if (rT != null)
                    {
                        RenderTextureFormat renderTextureFormat = rT.format;
                        CheckRGBFormats(renderTextureFormat, out bool _hasR, out bool _hasG, out bool _hasB);
                        hasR = hasR || _hasR;
                        hasG = hasG || _hasG;
                        hasB = hasB || _hasB;
                    }
                    else
                    {
                        //If we cannot validate whether the texture has RGB, lets assume it does by default.
                        hasR = true;
                        hasG = true;
                        hasB = true;
                    }
                }
            }

//			if (GUILayout.Button("PreviewColor2D.shader"))
//			{
//
//				Shader previewShader = (Shader)EditorGUIUtility.LoadRequired("Previews/PreviewColor2D.shader");
//				Selection.activeObject = previewShader;
//			}

            if (rT != null)
            {
                continuousRepaintOverride = GUILayout.Toggle(continuousRepaintOverride, s_Styles.playIcon, s_Styles.previewButtonScale);
            }

            if (GUILayout.Button(s_Styles.scaleIcon, s_Styles.previewButtonScale))
            {
                //Switch between the default % zoom, and 100% zoom
                float p100 = 1 / zoomLevel;
                if (Math.Abs(zoomMultiplier - p100) > 0.001f)
                {
                    int     texWidth      = Mathf.Max(tex.width, 1);
                    int     texHeight     = Mathf.Max(tex.height, 1);
                    Vector2 posNormalized = new Vector2(m_Pos.x / (texWidth * zoomLevel * zoomMultiplier), m_Pos.y / (texHeight * zoomLevel * zoomMultiplier));
                    //Zooms to 100
                    zoomMultiplier = p100;

                    //Focuses Center
                    Vector2 newPos = new Vector2(posNormalized.x * (texWidth * zoomLevel * zoomMultiplier), posNormalized.y * (texHeight * zoomLevel * zoomMultiplier));
                    m_Pos = newPos;
                }
                else
                {
                    //Zooms to default
                    zoomMultiplier = 1;
                    m_Pos          = Vector2.zero;
                }

                Repaint();
            }

            if (!alphaOnly)
            {
                DrawRGBToggles(hasR, hasG, hasB);
            }

            if (alphaOnly)
            {
                m_ShowAlpha = true;
                showMode    = false;
            }
            else if (!hasAlpha)
            {
                m_ShowAlpha = false;
                showMode    = false;
            }

            if (showMode && !IsNormalMap(tex))
            {
                m_ShowAlpha = GUILayout.Toggle(m_ShowAlpha, m_ShowAlpha ? s_Styles.alphaIcon : s_Styles.RGBIcon, s_Styles.previewButton);
            }

            if (mipCount > 1)
            {
                GUILayout.Box(s_Styles.smallZoom, s_Styles.previewLabel);
                GUI.changed = false;
                using (EditorGUI.ChangeCheckScope changeCheckScope = new EditorGUI.ChangeCheckScope())
                {
                    m_MipLevel = Mathf.Round(GUILayout.HorizontalSlider(m_MipLevel, mipCount - 1, 0, s_Styles.previewSlider, s_Styles.previewSliderThumb, GUILayout.MaxWidth(64)));
                    if (changeCheckScope.changed)
                    {
                        rGBAMaterial.SetFloat(Mip, m_MipLevel);
                        rGBATransparentMaterial.SetFloat(Mip, m_MipLevel);
                        Repaint();
                    }
                }

                GUILayout.Box(s_Styles.largeZoom, s_Styles.previewLabel);
            }
        }