public static extern bool ReformatCubemap(Cubemap cubemap, int width, int height, TextureFormat textureFormat, bool useMipmap, bool linear);
 public static extern Texture2D GetSourceTexture(Cubemap cubemapRef, CubemapFace face);
 public static extern void CopyTextureIntoCubemapFace(Texture2D textureRef, Cubemap cubemapRef, CubemapFace face);
        public override void OnInspectorGUI()
        {
            base.serializedObject.Update();
            if (base.targets.Length == 1)
            {
                this.DoToolbar();
            }
            this.m_ShowProbeModeRealtimeOptions.target = (this.reflectionProbeMode == ReflectionProbeMode.Realtime);
            this.m_ShowProbeModeCustomOptions.target   = (this.reflectionProbeMode == ReflectionProbeMode.Custom);
            EditorGUILayout.IntPopup(this.m_Mode, ReflectionProbeEditor.Styles.reflectionProbeMode, ReflectionProbeEditor.Styles.reflectionProbeModeValues, ReflectionProbeEditor.Styles.typeText, new GUILayoutOption[0]);
            if (!this.m_Mode.hasMultipleDifferentValues)
            {
                EditorGUI.indentLevel++;
                if (EditorGUILayout.BeginFadeGroup(this.m_ShowProbeModeCustomOptions.faded))
                {
                    EditorGUILayout.PropertyField(this.m_RenderDynamicObjects, ReflectionProbeEditor.Styles.renderDynamicObjects, new GUILayoutOption[0]);
                    EditorGUI.BeginChangeCheck();
                    EditorGUI.showMixedValue = this.m_CustomBakedTexture.hasMultipleDifferentValues;
                    UnityEngine.Object objectReferenceValue = EditorGUILayout.ObjectField(ReflectionProbeEditor.Styles.customCubemapText, this.m_CustomBakedTexture.objectReferenceValue, typeof(Cubemap), false, new GUILayoutOption[0]);
                    EditorGUI.showMixedValue = false;
                    if (EditorGUI.EndChangeCheck())
                    {
                        this.m_CustomBakedTexture.objectReferenceValue = objectReferenceValue;
                    }
                }
                EditorGUILayout.EndFadeGroup();
                if (EditorGUILayout.BeginFadeGroup(this.m_ShowProbeModeRealtimeOptions.faded))
                {
                    EditorGUILayout.PropertyField(this.m_RefreshMode, ReflectionProbeEditor.Styles.refreshMode, new GUILayoutOption[0]);
                    EditorGUILayout.PropertyField(this.m_TimeSlicingMode, ReflectionProbeEditor.Styles.timeSlicing, new GUILayoutOption[0]);
                    EditorGUILayout.Space();
                }
                EditorGUILayout.EndFadeGroup();
                EditorGUI.indentLevel--;
            }
            EditorGUILayout.Space();
            GUILayout.Label(ReflectionProbeEditor.Styles.runtimeSettingsHeader, new GUILayoutOption[0]);
            EditorGUI.indentLevel++;
            EditorGUILayout.PropertyField(this.m_Importance, ReflectionProbeEditor.Styles.importanceText, new GUILayoutOption[0]);
            EditorGUILayout.PropertyField(this.m_IntensityMultiplier, ReflectionProbeEditor.Styles.intensityText, new GUILayoutOption[0]);
            if (!EditorGraphicsSettings.GetCurrentTierSettings().reflectionProbeBoxProjection)
            {
                using (new EditorGUI.DisabledScope(true))
                {
                    EditorGUILayout.Toggle(ReflectionProbeEditor.Styles.boxProjectionText, false, new GUILayoutOption[0]);
                }
            }
            else
            {
                EditorGUILayout.PropertyField(this.m_BoxProjection, ReflectionProbeEditor.Styles.boxProjectionText, new GUILayoutOption[0]);
            }
            bool flag  = SceneView.IsUsingDeferredRenderingPath();
            bool flag2 = flag && GraphicsSettings.GetShaderMode(BuiltinShaderType.DeferredReflections) != BuiltinShaderMode.Disabled;

            using (new EditorGUI.DisabledScope(!flag2))
            {
                EditorGUILayout.PropertyField(this.m_BlendDistance, ReflectionProbeEditor.Styles.blendDistanceText, new GUILayoutOption[0]);
            }
            if (EditorGUILayout.BeginFadeGroup(this.m_ShowBoxOptions.faded))
            {
                EditorGUI.BeginChangeCheck();
                EditorGUILayout.PropertyField(this.m_BoxSize, ReflectionProbeEditor.Styles.sizeText, new GUILayoutOption[0]);
                EditorGUILayout.PropertyField(this.m_BoxOffset, ReflectionProbeEditor.Styles.centerText, new GUILayoutOption[0]);
                if (EditorGUI.EndChangeCheck())
                {
                    Vector3 vector3Value  = this.m_BoxOffset.vector3Value;
                    Vector3 vector3Value2 = this.m_BoxSize.vector3Value;
                    if (this.ValidateAABB(ref vector3Value, ref vector3Value2))
                    {
                        this.m_BoxOffset.vector3Value = vector3Value;
                        this.m_BoxSize.vector3Value   = vector3Value2;
                    }
                }
            }
            EditorGUILayout.EndFadeGroup();
            EditorGUI.indentLevel--;
            EditorGUILayout.Space();
            GUILayout.Label(ReflectionProbeEditor.Styles.captureCubemapHeaderText, new GUILayoutOption[0]);
            EditorGUI.indentLevel++;
            EditorGUILayout.IntPopup(this.m_Resolution, ReflectionProbeEditor.Styles.renderTextureSizes.ToArray(), ReflectionProbeEditor.Styles.renderTextureSizesValues.ToArray(), ReflectionProbeEditor.Styles.resolutionText, new GUILayoutOption[]
            {
                GUILayout.MinWidth(40f)
            });
            EditorGUILayout.PropertyField(this.m_HDR, new GUILayoutOption[0]);
            EditorGUILayout.PropertyField(this.m_ShadowDistance, new GUILayoutOption[0]);
            EditorGUILayout.IntPopup(this.m_ClearFlags, ReflectionProbeEditor.Styles.clearFlags, ReflectionProbeEditor.Styles.clearFlagsValues, ReflectionProbeEditor.Styles.clearFlagsText, new GUILayoutOption[0]);
            EditorGUILayout.PropertyField(this.m_BackgroundColor, ReflectionProbeEditor.Styles.backgroundColorText, new GUILayoutOption[0]);
            EditorGUILayout.PropertyField(this.m_CullingMask, new GUILayoutOption[0]);
            EditorGUILayout.PropertyField(this.m_UseOcclusionCulling, new GUILayoutOption[0]);
            EditorGUILayout.PropertiesField(EditorGUI.s_ClipingPlanesLabel, this.m_NearAndFarProperties, EditorGUI.s_NearAndFarLabels, 35f, new GUILayoutOption[0]);
            EditorGUI.indentLevel--;
            EditorGUILayout.Space();
            if (base.targets.Length == 1)
            {
                ReflectionProbe reflectionProbe = (ReflectionProbe)base.target;
                if (reflectionProbe.mode == ReflectionProbeMode.Custom && reflectionProbe.customBakedTexture != null)
                {
                    Cubemap cubemap = reflectionProbe.customBakedTexture as Cubemap;
                    if (cubemap && cubemap.mipmapCount == 1)
                    {
                        EditorGUILayout.HelpBox("No mipmaps in the cubemap, Smoothness value in Standard shader will be ignored.", MessageType.Warning);
                    }
                }
            }
            this.DoBakeButton();
            EditorGUILayout.Space();
            base.serializedObject.ApplyModifiedProperties();
        }
示例#5
0
    void Awake()
    {
        Debug.Log("Overlay Awake");

        if (premultiplyMaterial == null)
        {
            premultiplyMaterial = new Material(Shader.Find("Oculus/Alpha Premultiply"));
        }

        rend = GetComponent <Renderer>();

        if (textures.Length == 0)
        {
            textures = new Texture[] { null }
        }
        ;

        // Backward compatibility
        if (rend != null && textures[0] == null)
        {
            textures[0] = rend.material.mainTexture;
        }

        if (textures[0] != null)
        {
            cachedTextures[0] = textures[0];
            texNativePtrs[0]  = textures[0].GetNativeTexturePtr();
        }

#if UNITY_ANDROID && !UNITY_EDITOR
        if (textures.Length == 2 && textures[1] != null)
        {
            layout = (isMultiviewEnabled) ? OVRPlugin.LayerLayout.Array : OVRPlugin.LayerLayout.Stereo;
        }
        texturesPerStage = (layout == OVRPlugin.LayerLayout.Stereo) ? 2 : 1;
#endif
    }

    void OnEnable()
    {
        if (!OVRManager.isHmdPresent)
        {
            enabled = false;
            return;
        }

        OnDisable();

        for (int i = 0; i < maxInstances; ++i)
        {
            if (instances[i] == null || instances[i] == this)
            {
                layerIndex   = i;
                instances[i] = this;
                break;
            }
        }

        layerIdHandle = GCHandle.Alloc(layerId, GCHandleType.Pinned);
        layerIdPtr    = layerIdHandle.AddrOfPinnedObject();
    }

    void OnDisable()
    {
        if (layerIndex != -1)
        {
            // Turn off the overlay if it was on.
            OVRPlugin.EnqueueSubmitLayer(true, false, IntPtr.Zero, IntPtr.Zero, -1, 0, OVRPose.identity.ToPosef(), Vector3.one.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)_prevOverlayShape);
            instances[layerIndex] = null;
        }

        if (layerIdPtr != IntPtr.Zero)
        {
            OVRPlugin.EnqueueDestroyLayer(layerIdPtr);
            layerIdPtr = IntPtr.Zero;
            layerIdHandle.Free();
        }

        layerIndex = -1;
    }

    int prevFrameIndex = -1;

    void OnRenderObject()
    {
        // The overlay must be specified every eye frame, because it is positioned relative to the
        // current head location.  If frames are dropped, it will be time warped appropriately,
        // just like the eye buffers.
        if (!Camera.current.CompareTag("MainCamera") || Camera.current.cameraType != CameraType.Game || layerIndex == -1 || currentOverlayType == OverlayType.None || textures.Length < texturesPerStage)
        {
            return;
        }


        // Don't submit the same frame twice.
        if (Time.frameCount <= prevFrameIndex)
        {
            return;
        }
        prevFrameIndex = Time.frameCount;

#if !UNITY_ANDROID || UNITY_EDITOR
        if (currentOverlayShape == OverlayShape.OffcenterCubemap)
        {
            Debug.LogWarning("Overlay shape " + currentOverlayShape + " is not supported on current platform");
        }
#endif

        for (int i = 0; i < texturesPerStage; ++i)
        {
            if (textures[i] != cachedTextures[i])
            {
                cachedTextures[i] = textures[i];
                if (cachedTextures[i] != null)
                {
                    texNativePtrs[i] = cachedTextures[i].GetNativeTexturePtr();
                }
            }

            if (currentOverlayShape == OverlayShape.Cubemap)
            {
                if (textures[i] != null && textures[i].GetType() != typeof(Cubemap))
                {
                    Debug.LogError("Need Cubemap texture for cube map overlay");
                    return;
                }
            }
        }

        if (cachedTextures[0] == null || texNativePtrs[0] == IntPtr.Zero)
        {
            return;
        }

        bool overlay    = (currentOverlayType == OverlayType.Overlay);
        bool headLocked = false;
        for (var t = transform; t != null && !headLocked; t = t.parent)
        {
            headLocked |= (t == Camera.current.transform);
        }

        OVRPose pose  = (headLocked) ? transform.ToHeadSpacePose() : transform.ToTrackingSpacePose();
        Vector3 scale = transform.lossyScale;
        for (int i = 0; i < 3; ++i)
        {
            scale[i] /= Camera.current.transform.lossyScale[i];
        }
#if !UNITY_ANDROID
        if (currentOverlayShape == OverlayShape.Cubemap)
        {
            pose.position = Camera.current.transform.position;
        }
#endif
        // Pack the offsetCenter directly into pose.position for offcenterCubemap
        if (currentOverlayShape == OverlayShape.OffcenterCubemap)
        {
            pose.position = transform.position;
            if (pose.position.magnitude > 1.0f)
            {
                Debug.LogWarning("your cube map center offset's magnitude is greater than 1, which will cause some cube map pixel always invisible .");
            }
        }
        // Cylinder overlay sanity checking
        if (currentOverlayShape == OverlayShape.Cylinder)
        {
            float arcAngle = scale.x / scale.z / (float)Math.PI * 180.0f;
            if (arcAngle > 180.0f)
            {
                Debug.LogError("Cylinder overlay's arc angle has to be below 180 degree, current arc angle is " + arcAngle + " degree.");
                return;
            }
        }

        OVRPlugin.Sizei size = new OVRPlugin.Sizei()
        {
            w = textures[0].width, h = textures[0].height
        };
        int           flags                 = (int)OVRPlugin.LayerFlags.TextureOriginAtBottomLeft;
        int           mipLevels             = 1;
        int           sampleCount           = 1;
        TextureFormat txFormat              = TextureFormat.BGRA32;
        OVRPlugin.EyeTextureFormat etFormat = OVRPlugin.EyeTextureFormat.B8G8R8A8_sRGB;
        RenderTextureFormat        rtFormat = RenderTextureFormat.BGRA32;

        var tex2D = textures[0] as Texture2D;
        if (tex2D != null)
        {
            if (tex2D.format == TextureFormat.RGBAHalf || tex2D.format == TextureFormat.RGBAFloat)
            {
                txFormat = TextureFormat.RGBAHalf;
                etFormat = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP;
                rtFormat = RenderTextureFormat.ARGBHalf;
            }
        }

        var rt = textures[0] as RenderTexture;
        if (rt != null)
        {
            sampleCount = rt.antiAliasing;

            if (rt.format == RenderTextureFormat.ARGBHalf)
            {
                txFormat = TextureFormat.RGBAHalf;
                etFormat = OVRPlugin.EyeTextureFormat.R16G16B16A16_FP;
                rtFormat = RenderTextureFormat.ARGBHalf;
            }
        }

        bool needsSetup = (
            !layerDesc.TextureSize.Equals(size) ||
            layerDesc.SampleCount != sampleCount ||
            layerDesc.LayerFlags != flags ||
            layerDesc.Shape != (OVRPlugin.OverlayShape)currentOverlayShape ||
            layerDesc.Layout != layout ||
            layerDesc.Format != etFormat);

        OVRPlugin.LayerDesc desc = new OVRPlugin.LayerDesc();

        if (layerIdPtr != IntPtr.Zero && needsSetup)
        {
            if ((int)layerIdHandle.Target != 0)
            {
                OVRPlugin.EnqueueDestroyLayer(layerIdPtr);
            }

            desc = OVRPlugin.CalculateLayerDesc((OVRPlugin.OverlayShape)currentOverlayShape, layout, size, mipLevels, sampleCount, etFormat, flags);
            OVRPlugin.EnqueueSetupLayer(desc, layerIdPtr);
            layerId = (int)layerIdHandle.Target;

            if (layerId > 0)
            {
                layerDesc = desc;
            }
        }

        if (layerId > 0)
        {
            // For newer SDKs, blit directly to the surface that will be used in compositing.

            int stageCount = OVRPlugin.GetLayerTextureStageCount(layerId);

            if (externalTextures == null)
            {
                frameIndex       = 0;
                externalTextures = new Texture[texturesPerStage][];
            }

            for (int eyeId = 0; eyeId < texturesPerStage; ++eyeId)
            {
                if (externalTextures[eyeId] == null)
                {
                    externalTextures[eyeId] = new Texture[stageCount];
                }

                int stage = frameIndex % stageCount;

                IntPtr externalTex = OVRPlugin.GetLayerTexture(layerId, stage, (OVRPlugin.Eye)eyeId);

                if (externalTex == IntPtr.Zero)
                {
                    continue;
                }

                bool needsCopy = isDynamic;

                Texture et = externalTextures[eyeId][stage];
                if (et == null)
                {
                    bool isSrgb = (etFormat == OVRPlugin.EyeTextureFormat.B8G8R8A8_sRGB || etFormat == OVRPlugin.EyeTextureFormat.R8G8B8A8_sRGB);

                    if (currentOverlayShape != OverlayShape.Cubemap && currentOverlayShape != OverlayShape.OffcenterCubemap)
                    {
                        et = Texture2D.CreateExternalTexture(size.w, size.h, txFormat, mipLevels > 1, isSrgb, externalTex);
                    }
#if UNITY_2017_1_OR_NEWER
                    else
                    {
                        //et = Cubemap.CreateExternalTexture(size.w, size.h, txFormat, mipLevels > 1, isSrgb, externalTex);
                        et = Cubemap.CreateExternalTexture(size.w, txFormat, isSrgb, externalTex);
                    }
#endif

                    externalTextures[eyeId][stage] = et;
                    needsCopy = true;
                }

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

                        for (int face = 0; face < 6; ++face)
                        {
                            //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, 0, tempRTSrc, 0, 0);
                            Graphics.Blit(tempRTSrc, tempRTDst, premultiplyMaterial);
                            Graphics.CopyTexture(tempRTDst, 0, 0, et, face, 0);
                        }
                        RenderTexture.ReleaseTemporary(tempRTSrc);
                        RenderTexture.ReleaseTemporary(tempRTDst);
                    }
#endif
                }
            }

            bool isOverlayVisible = OVRPlugin.EnqueueSubmitLayer(overlay, headLocked, texNativePtrs[0], texNativePtrs[1], layerId, frameIndex, pose.flipZ().ToPosef(), scale.ToVector3f(), layerIndex, (OVRPlugin.OverlayShape)currentOverlayShape);
            if (isDynamic)
            {
                ++frameIndex;
            }
            _prevOverlayShape = currentOverlayShape;
            if (rend)
            {
                rend.enabled = !isOverlayVisible;
            }
        }
    }
}
		private static void Internal_Create(Cubemap mono, int size, TextureFormat format, bool mipmap){}
示例#7
0
        private void convolve_internal(Texture dstTex, Texture srcCube, bool dstRGBM, bool srcRGBM, bool linear, Camera cam, Material skyMat, Matrix4x4 matrix)
        {
            bool             prevHDR   = cam.hdr;
            CameraClearFlags prevFlags = cam.clearFlags;
            int prevMask = cam.cullingMask;

            cam.clearFlags  = CameraClearFlags.Skybox;
            cam.cullingMask = 0;
            cam.hdr         = !dstRGBM;     // might need HDR camera buffer when we're not rendering to RGBM encoded pixels

            skyMat.name   = "Internal Convolve Skybox";
            skyMat.shader = Shader.Find("Hidden/Marmoset/RGBM Convolve");

            //toggleKeywordPair("MARMO_LINEAR", "MARMO_GAMMA", linear);
            toggleKeywordPair("MARMO_RGBM_INPUT_ON", "MARMO_RGBM_INPUT_OFF", srcRGBM);
            toggleKeywordPair("MARMO_RGBM_OUTPUT_ON", "MARMO_RGBM_OUTPUT_OFF", dstRGBM);

            skyMat.SetMatrix("_SkyMatrix", matrix);
            skyMat.SetTexture("_CubeHDR", srcCube);
            bindRandomValueTable(skyMat, "_PhongRands", srcCube.width);

            Material prevSkyMat = UnityEngine.RenderSettings.skybox;

            UnityEngine.RenderSettings.skybox = skyMat;

            Cubemap       dstCube = dstTex as Cubemap;
            RenderTexture dstRT   = dstTex as RenderTexture;

            if (dstCube)
            {
                if (generateMipChain)
                {
                    int mipCount = mset.QPow.Log2i(dstCube.width) - 1;
                    int mip      = highestMipIsMirror ? 1 : 0;
                    for ( ; mip < mipCount; ++mip)
                    {
                        int   mipSize = 1 << (mipCount - mip);
                        float mipExp  = mset.QPow.clampedDownShift(this.maxExponent, highestMipIsMirror ? (mip - 1) : mip, 1);
                        skyMat.SetFloat("_SpecularExp", mipExp);
                        skyMat.SetFloat("_SpecularScale", this.convolutionScale);
                        Cubemap mipCube = new Cubemap(mipSize, dstCube.format, false);
                        cam.RenderToCubemap(mipCube);

                        for (int f = 0; f < 6; ++f)
                        {
                            CubemapFace face = (CubemapFace)f;
                            dstCube.SetPixels(mipCube.GetPixels(face), face, mip);
                        }
                        Cubemap.DestroyImmediate(mipCube);
                    }
                    dstCube.Apply(false);
                }
                else
                {
                    skyMat.SetFloat("_SpecularExp", this.maxExponent);
                    skyMat.SetFloat("_SpecularScale", this.convolutionScale);
                    cam.RenderToCubemap(dstCube);
                }
            }
            else if (dstRT)
            {
                skyMat.SetFloat("_SpecularExp", this.maxExponent);
                skyMat.SetFloat("_SpecularScale", this.convolutionScale);
                cam.RenderToCubemap(dstRT);
            }

            cam.clearFlags  = prevFlags;
            cam.cullingMask = prevMask;
            cam.hdr         = prevHDR;
            UnityEngine.RenderSettings.skybox = prevSkyMat;
        }
示例#8
0
 public bool RenderToCubemap(Cubemap cubemap) => _obj.RenderToCubemap(cubemap);
示例#9
0
        public void ConvertIES(string filePath, string targetPath, bool createSpotlightCookies, bool rawImport, bool applyVignette, out Cubemap pointLightCookie, out Texture2D spotlightCookie, out EXRData exrData, out string targetFilename)
        {
            IESData iesdata = ParseIES.Parse(filePath, rawImport ? NormalizationMode.Linear : this.NormalizationMode);

            this._iesTexture = IESToTexture.ConvertIesData(iesdata);
            if (!rawImport)
            {
                exrData = default(EXRData);
                this.RegularImport(filePath, targetPath, createSpotlightCookies, applyVignette, out pointLightCookie, out spotlightCookie, out targetFilename, iesdata);
            }
            else
            {
                pointLightCookie = null;
                spotlightCookie  = null;
                this.RawImport(iesdata, filePath, targetPath, createSpotlightCookies, out exrData, out targetFilename);
            }
            if (this._iesTexture != null)
            {
                UnityEngine.Object.Destroy(this._iesTexture);
            }
        }
示例#10
0
        public override Cubemap LoadCubemap(string[] filepaths)
        {
            if (filepaths.Length != 6)
                throw new Exception("A cubemap is made up of exactly six textures. " + filepaths.Length + " textures were supplied.");
            GL.Enable(EnableCap.TextureCubeMap);
            GL.Enable(EnableCap.TextureCubeMapSeamless);
            int id = Texture.GenTextureID();
            Cubemap res = new Cubemap(id);
            res.Use();
            for (int i = 0; i < filepaths.Length; i++)
            {
                Bitmap bmp = new Bitmap(filepaths[i]);
                BitmapData bmp_data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                GL.TexImage2D(TextureTarget.TextureCubeMapPositiveX + i, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0,
                    OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);

                bmp.UnlockBits(bmp_data);
            }
            GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
            GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
            GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapR, (int)TextureWrapMode.ClampToEdge);
            GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.TextureCubeMap, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            res.GenerateMipmap();
            GL.BindTexture(TextureTarget.TextureCubeMap, 0);
            return res;
        }
示例#11
0
 // public void RemoveAllCommandBuffers() => _obj.RemoveAllCommandBuffers();
 // public void RemoveCommandBuffer(CameraEvent evt, CommandBuffer buffer) => _obj.RemoveCommandBuffer(evt, buffer);
 // public void RemoveCommandBuffers(CameraEvent evt) => _obj.RemoveCommandBuffers(evt);
 // public void Render() => _obj.Render();
 // public void RenderDontRestore() => _obj.RenderDontRestore();
 public bool RenderToCubemap(Cubemap cubemap, int faceMask) => _obj.RenderToCubemap(cubemap, faceMask);
示例#12
0
		private bool Internal_RenderToCubemapTexture(Cubemap cubemap, int faceMask){}
示例#13
0
		public bool RenderToCubemap(Cubemap cubemap, int faceMask){}
示例#14
0
		public bool RenderToCubemap(Cubemap cubemap){}
 public static extern void MarkCubemapReadable(Cubemap cubemapRef, bool readable);
示例#16
0
 private void RegularImport(string filePath, string targetPath, bool createSpotlightCookies, bool applyVignette, out Cubemap pointLightCookie, out Texture2D spotlightCookie, out string targetFilename, IESData iesData)
 {
     if ((createSpotlightCookies && iesData.VerticalType != VerticalType.Full) || iesData.PhotometricType == PhotometricType.TypeA)
     {
         pointLightCookie = null;
         base.GetComponent <IESToSpotlightCookie>().CreateSpotlightCookie(this._iesTexture, iesData, this.Resolution, applyVignette, false, out spotlightCookie);
     }
     else
     {
         spotlightCookie = null;
         base.GetComponent <IESToCubemap>().CreateCubemap(this._iesTexture, iesData, this.Resolution, out pointLightCookie);
     }
     this.BuildTargetFilename(Path.GetFileNameWithoutExtension(filePath), targetPath, pointLightCookie != null, false, this.NormalizationMode, iesData, out targetFilename);
 }
 public static extern int GetCubemapStreamingMipmapsPriority(Cubemap cubemap);
示例#18
0
        // Use this for initialization
        public void Awake()
        {
            OnDestroy();
            if (UseCustomResolution)
            {
                _targetResolution = new Resolution
                {
                    width  = CustomResolution.x,
                    height = CustomResolution.y
                }
            }
            ;
            else
            {
                _targetResolution = Screen.currentResolution;
            }

            AmbientOcclusionDrt.Init("AmbientOcclusion", _targetResolution, RenderTextureFormat.ARGBFloat, TextureDimension.Tex2DArray, 2);

            // Create Render Texture
            _deferredOutput = new RenderTexture(_targetResolution.width, _targetResolution.height, 0,
                                                RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear)
            {
                enableRandomWrite = true
            };
            _deferredOutput.Create();

            _sphereTracingData = new RenderTexture(_targetResolution.width, _targetResolution.height, 0,
                                                   RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear)
            {
                enableRandomWrite = true,
                useMipMap         = false,
                autoGenerateMips  = false,
                dimension         = TextureDimension.Tex2DArray,
                volumeDepth       = 6
            };
            _sphereTracingData.Create();

            _sphereTracingDataLow = new RenderTexture(AmbientOcclusionDrt.Resolution.width, AmbientOcclusionDrt.Resolution.height, 0,
                                                      RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear)
            {
                enableRandomWrite = true,
                useMipMap         = false,
                autoGenerateMips  = false,
                dimension         = TextureDimension.Tex2DArray,
                volumeDepth       = 6
            };
            _sphereTracingDataLow.Create();

            _fakeCubemapRenderTexture = new RenderTexture(CubemapResolution, CubemapResolution, 0,
                                                          RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear)
            {
                enableRandomWrite = true,
                useMipMap         = false,
                autoGenerateMips  = false,
                anisoLevel        = 0,
                dimension         = TextureDimension.Tex2DArray,
                volumeDepth       = 6
            };
            _fakeCubemapRenderTexture.Create();

            _fakeCubemapArrayRenderTexture = new RenderTexture(CubemapResolution, CubemapResolution, 0,
                                                               RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear)
            {
                enableRandomWrite = true,
                useMipMap         = false,
                autoGenerateMips  = false,
                anisoLevel        = 0,
                dimension         = TextureDimension.Tex2DArray,
                volumeDepth       = 6 * ConvolutionLayerCount
            };
            _fakeCubemapArrayRenderTexture.Create();

            _environmentMap = new Cubemap(CubemapResolution, TextureFormat.RGBAHalf, false)
            {
                hideFlags  = HideFlags.HideAndDontSave,
                wrapMode   = TextureWrapMode.Clamp,
                anisoLevel = 0
            };

            _convolutedEnvironmentMapArray = new CubemapArray(CubemapResolution, ConvolutionLayerCount, TextureFormat.RGBAHalf, false)
            {
                hideFlags  = HideFlags.HideAndDontSave,
                wrapMode   = TextureWrapMode.Clamp,
                filterMode = FilterMode.Trilinear,
                anisoLevel = 0
            };

            _sphereTracingFKernels            = InitComputeKernels(SphereTracingShader, _targetResolution, 1, "SphereTracingFPassH", "SphereTracingFPassM", "SphereTracingFPassL");
            _sphereTracingKKernels            = InitComputeKernels(SphereTracingShader, _targetResolution, 1, "SphereTracingKPassH", "SphereTracingKPassM", "SphereTracingKPassL");
            _sphereTracingDownSamplerKernels  = InitComputeKernels(SphereTracingDownSampler, AmbientOcclusionDrt.Resolution, 2, "SphereTracingDownSampleH", "SphereTracingDownSampleM", "SphereTracingDownSampleL");
            _sphereTracingAoKernels           = InitComputeKernels(AmbientOcclusionShader, AmbientOcclusionDrt.Resolution, 1, "AmbientOcclusionH", "AmbientOcclusionM", "AmbientOcclusionL");
            _sphereTracingAoUpSamplerKernels  = InitComputeKernels(AmbientOcclusionUpSampler, _targetResolution, 2, "AmbientOcclusionUpSampleH", "AmbientOcclusionUpSampleM", "AmbientOcclusionUpSampleL");
            _horizontalBilateralFilterKernels = InitComputeKernels(BilateralFilterShader, _targetResolution, 2, "AOHorizontalH", "AOHorizontalM", "AOHorizontalL");
            _verticalBilateralFilterKernels   = InitComputeKernels(BilateralFilterShader, _targetResolution, 2, "AOVerticalH", "AOVerticalM", "AOVerticalL");
            _deferredKernels = InitComputeKernels(DeferredShader, _targetResolution, 1, "DeferredH", "DeferredM", "DeferredL");

            var environmentMapResolution = new Resolution {
                width = CubemapResolution, height = CubemapResolution
            };

            //With 6 z Dispatch groups, one for each side of cubemap
            _environmentMapRendererKernels = InitComputeKernels(EnvironmentMapRenderer, environmentMapResolution, 6, "RenderEnvironmentMapH", "RenderEnvironmentMapM", "RenderEnvironmentMapL");
            //With 6 * ConvolutionLayerCount z Dispatch groups. One for each side of cubemap per convoluted cubemap
            _environmentMapConvolutionKernels = InitComputeKernels(EnvironmentMapConvolution, environmentMapResolution, 6 * ConvolutionLayerCount, "ConvoluteEnvironmentMapH", "ConvoluteEnvironmentMapM", "ConvoluteEnvironmentMapL");

            GenerateAmbientOcclusionSamples();

            InitLights();
            InitMaterials();
            InitMatrices();
            SetShaderPropertiesOnce();

            //At least we have to render environmentmap one
            RenderEnvironmentMap();
        }
示例#19
0
        public void convolve(Cubemap targetCube, Texture sourceCube, bool dstRGBM, bool srcRGBM, bool linear)
        {
            if (targetCube == null)
            {
                return;
            }
            //buildRandomValueCode();

            /*
             * bool tempRT = false;
             * if(cubeRT == null) {
             *      tempRT = true;
             *      //everything's rendered in HDR render buffer for now
             *      cubeRT = RenderTexture.GetTemporary(targetCube.width, targetCube.width, 24, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear);
             *      cubeRT.isCubemap = true;
             *      cubeRT.useMipMap = true;
             *      cubeRT.generateMips = true;
             * }
             */

            GameObject go = new GameObject("_temp_probe");

            go.hideFlags = HideFlags.HideInHierarchy | HideFlags.HideAndDontSave;
            go.SetActive(true);
            Camera cam = go.AddComponent <Camera>();

            cam.renderingPath       = renderPath;
            cam.useOcclusionCulling = false;

            Material skyMat = new Material(Shader.Find("Hidden/Marmoset/RGBM Cube"));

            Matrix4x4 matrix = Matrix4x4.identity;

            this.copy_internal(targetCube, sourceCube, dstRGBM, srcRGBM, linear, cam, skyMat, matrix);
            //NOTE: cubeRT is needed to make sure sourceCube is mipmapped (for importance sampling), however cubeRT cannot be used because D3D9 renders skybox gamma wrong >_<

            /*
             * this.copy_internal(cubeRT,       sourceCube, false,   srcRGBM, linear, cam, skyMat, matrix);
             * this.convolve_internal(targetCube,	cubeRT,	dstRGBM, false,   linear, cam, skyMat, matrix);
             * this.copy_internal		(targetCube, sourceCube, dstRGBM, srcRGBM, linear, cam, skyMat, matrix);
             */
            int me = this.maxExponent;

            //HACK: dx11 seems to be the only shader model that supports 128 texture samples, convolve twice on all other platforms
            this.maxExponent = 2 * me;
            this.convolve_internal(targetCube, sourceCube, dstRGBM, srcRGBM, linear, cam, skyMat, matrix);
            this.maxExponent = 8 * me;
            this.convolve_internal(targetCube, targetCube, dstRGBM, dstRGBM, linear, cam, skyMat, matrix);
            this.maxExponent = me;

            //make sure the old sky and matrix vars are bound again
            mset.SkyManager mgr = mset.SkyManager.Get();
            if (mgr)
            {
                mgr.GlobalSky = mgr.GlobalSky;
            }
            Material.DestroyImmediate(skyMat);

            //if(tempRT) RenderTexture.ReleaseTemporary(cubeRT);
            GameObject.DestroyImmediate(go);
        }
    void PrefilterEnvMapSpecular()
    {
        List <Cubemap> lstCubemaps = new List <Cubemap>();

        if (mPBRObject == null)
        {
            //创建一个球
            mPBRObject       = GameObject.CreatePrimitive(PrimitiveType.Cube);
            mPBRObject.layer = LayerMask.NameToLayer("RenderToCubemap");
            mPBRObject.transform.position = Vector3.zero;
            mPBRObject.transform.rotation = Quaternion.identity;
        }
        //if (mCameraObject == null)
        //{
        //    mCameraObject = new GameObject("RenderToCubemap");
        //    mCameraObject.transform.position = mPBRObject.transform.position;
        //    mCameraObject.transform.rotation = Quaternion.identity;
        //}

        Camera camera = mPBRObject.GetComponent <Camera>();

        if (camera != null)
        {
            //camera = mCameraObject.AddComponent<Camera>();
            mCamera = camera;
        }
        else
        {
            mCamera = mPBRObject.AddComponent <Camera>();
        }

        mCamera.clearFlags      = CameraClearFlags.SolidColor;
        mCamera.backgroundColor = Color.black;
        mCamera.cullingMask     = 1 << LayerMask.NameToLayer("RenderToCubemap");
        mCamera.targetTexture   = null;

        if (mPrefilterEnvSpecularMaterial == null)
        {
            Shader prefilterCube = Shader.Find("liangairan/pbr/prefilterSpecularMap");
            mPrefilterEnvSpecularMaterial = new Material(prefilterCube);
            //camera.SetReplacementShader(prefilterCube, "RenderType");
            mPrefilterEnvSpecularMaterial.SetTexture("_Cube", mEnvironmentMap);
        }

        mPBRObject.GetComponent <Renderer>().sharedMaterial = mPrefilterEnvSpecularMaterial;

        int cubeMapSize = mOutputSpecularMapSize;
        int mipmapsNum  = (int)Mathf.Log(cubeMapSize, 2) + 1;

        for (int i = 0; i < mipmapsNum; ++i)
        {
            int     width     = cubeMapSize >> i;
            Cubemap cubeMap   = new Cubemap(width, TextureFormat.RGBAHalf, false);
            float   roughness = i / (float)(mipmapsNum - 1);
            mPrefilterEnvSpecularMaterial.SetFloat("_roughness", roughness);

            camera.RenderToCubemap(cubeMap, 63);
            lstCubemaps.Add(cubeMap);
            //AssetDatabase.CreateAsset(lstCubemaps[i], "Assets/pbr by liangairan/specularPrefilter_" + i + ".cubemap");
        }

        //camera.targetTexture = mCubeMapSpecular;
        //camera.RenderToCubemap(mCubeMapSpecular, 63);
        //camera.targetTexture = null;

        Cubemap specularPrefilterMap = (Cubemap)AssetDatabase.LoadAssetAtPath(mOutputPath + "specularPrefilter.cubemap", typeof(Cubemap));
        bool    bNewAsset            = false;

        if (specularPrefilterMap == null)
        {
            specularPrefilterMap = new Cubemap(cubeMapSize, TextureFormat.RGBAHalf, true);
            bNewAsset            = true;
        }

        for (int i = 0; i < lstCubemaps.Count; ++i)
        {
            Cubemap mipmap = lstCubemaps[i];
            for (int j = 0; j < 6; ++j)
            {
                specularPrefilterMap.SetPixels(mipmap.GetPixels((CubemapFace)j), (CubemapFace)j, i);
            }
        }

        if (bNewAsset)
        {
            AssetDatabase.CreateAsset(specularPrefilterMap, mOutputPath + "specularPrefilter.cubemap");
        }

        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();

        //TextureImporter textureImporter = AssetImporter.GetAtPath(mOutputPath + "specularPrefilter.cubemap") as TextureImporter;
        //textureImporter.textureType = TextureImporterType.Default;
        //textureImporter.textureShape = TextureImporterShape.TextureCube;
        //textureImporter.mipmapEnabled = true;
        //textureImporter.sRGBTexture = true;
        //AssetDatabase.ImportAsset(mOutputPath + "specularPrefilter.cubemap", ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport);

        for (int i = 0; i < lstCubemaps.Count; ++i)
        {
            DestroyImmediate(lstCubemaps[i]);
        }
        lstCubemaps.Clear();
    }
示例#21
0
        public Cubemap BakeReflection()
        {
            if (Application.isPlaying || !bakeable)
            {
                return(null);
            }

            CreateData();

            int resolution = GetComponent <ReflectionProbe>().resolution;

            RenderPair pair;

            if (!targets.TryGetValue(resolution, out pair))
            {
                return(null);
            }

            Cubemap   cubemap = new Cubemap(resolution, TextureFormat.RGBAFloat, true);
            Texture2D reader  = new Texture2D(resolution, resolution, TextureFormat.RGBAFloat, true, true);

            Camera camera = Camera;

            camera.gameObject.SetActive(true);
            camera.transform.position = transform.position;
            camera.targetTexture      = pair.Render;

            SetCameraSettings(camera);

            Texture2D cubemap2D = new Texture2D(resolution * 6, resolution, TextureFormat.RGBAFloat, true);

            for (int face = 0; face < 6; face++)
            {
                camera.transform.rotation = orientations[face];

                Shader.EnableKeyword("NO_REFLECTION");
                camera.Render();
                Shader.DisableKeyword("NO_REFLECTION");

                Graphics.Blit(pair.Render, pair.Mirror, mirror);

                RenderTexture source      = pair.Mirror;
                RenderTexture destination = pair.Render;
                for (int i = 0; i < effects.Length; i++)
                {
                    if (effects[i].Render(source, destination))
                    {
                        RenderTexture temp = source;
                        source      = destination;
                        destination = temp;
                    }
                }

                RenderTexture.active = source;
                reader.ReadPixels(new Rect(0, 0, resolution, resolution), 0, 0);
                var colors = reader.GetPixels();
                cubemap.SetPixels(colors, (CubemapFace)face);

                Color[] flipColors = new Color[resolution * resolution];
                for (int height = 0; height < resolution; ++height)
                {
                    for (int width = 0; width < resolution; ++width)
                    {
                        flipColors[height * resolution + width] = colors[(resolution - 1 - height) * resolution + width];
                    }
                }
                cubemap2D.SetPixels(face * resolution, 0, resolution, resolution, flipColors);
                flipColors = null;

                Clear(pair);

                RenderTexture.active = null;
            }

            cubemap2D.Apply();
            byte[] bytes     = cubemap2D.EncodeToEXR();
            var    imagePath = UnityEditor.EditorUtility.SaveFilePanel("Save Cubemap as EXR", Application.dataPath, cubemap.name, "exr");

            if (imagePath.Length != 0 && bytes != null)
            {
                File.WriteAllBytes(imagePath, bytes);
            }
            AssetDatabase.ImportAsset(imagePath, ImportAssetOptions.ForceUpdate);
            AssetDatabase.Refresh();
            var             relativepath = "Assets" + imagePath.Substring(Application.dataPath.Length);
            TextureImporter tImporter    = AssetImporter.GetAtPath(relativepath) as TextureImporter;

            if (tImporter)
            {
                TextureImporterSettings tImporterSettings = new TextureImporterSettings();
                tImporterSettings.generateCubemap    = TextureImporterGenerateCubemap.AutoCubemap;
                tImporterSettings.cubemapConvolution = TextureImporterCubemapConvolution.Specular;
                tImporterSettings.seamlessCubemap    = true;
                tImporterSettings.npotScale          = TextureImporterNPOTScale.ToNearest;
                tImporterSettings.mipmapEnabled      = true;
                tImporterSettings.textureShape       = TextureImporterShape.TextureCube;
                tImporterSettings.wrapMode           = TextureWrapMode.Clamp;
                tImporterSettings.filterMode         = FilterMode.Trilinear;
                tImporterSettings.sRGBTexture        = true;
                tImporter.SetTextureSettings(tImporterSettings);
                tImporter.SaveAndReimport();
            }

            cubemap.Apply();
            GetComponent <ReflectionProbe>().customBakedTexture = cubemap;
            baked = cubemap;

            DestroyImmediate(reader);
            DestroyImmediate(camera.gameObject);

            ResetReflection();

            return(cubemap);
        }
    private void OnGUI()
    {
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("output irradiance map size:");
        mOutputIrradianceDiffuseMapSize = EditorGUILayout.IntField(mOutputIrradianceDiffuseMapSize);
        EditorGUILayout.EndHorizontal();


        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("output specular cubemap size:");
        mOutputSpecularMapSize = EditorGUILayout.IntField(mOutputSpecularMapSize);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("enviroment map:");
        mEnvironmentMap = EditorGUILayout.ObjectField(mEnvironmentMap, typeof(Cubemap), true) as Cubemap;
        if (mEnvironmentMap != null)
        {
            mSourceEnvironmentMapSize = mEnvironmentMap.width;
        }
        EditorGUILayout.EndHorizontal();

        //EditorGUILayout.BeginHorizontal();
        //GUILayout.Label("prefliter specular map:");
        //mCubeMapSpecular = EditorGUILayout.ObjectField(mCubeMapSpecular, typeof(RenderTexture), true) as RenderTexture;
        //EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("current scene path:");
        EditorGUILayout.EndHorizontal();
        Scene scene = SceneManager.GetActiveScene();

        mOutputPath = scene.path;
        int lastSlash = mOutputPath.LastIndexOf("/");

        if (lastSlash >= 0)
        {
            mOutputPath = mOutputPath.Substring(0, lastSlash + 1);
        }
        EditorGUILayout.BeginHorizontal();
        mOutputPath = EditorGUILayout.TextField(mOutputPath);

        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("brdflut create compute shader:");
        brdfCompute = EditorGUILayout.ObjectField(brdfCompute, typeof(ComputeShader), true) as ComputeShader;

        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        genBRDFLutByGPU = EditorGUILayout.Toggle("gen brdflut by CPU?", genBRDFLutByGPU);
        EditorGUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        //GUILayout.Label("Render to cubemap");
        if (GUILayout.Button("Prefilter cubemap"))
        {
            PrefilterEnvMapIrradiance();
            PrefilterEnvMapSpecular();
            RenderToBRDFMap();
        }
        EditorGUILayout.EndHorizontal();
    }
 public void SetComputeShaderIBLBuffer(ComputeShader targetShader, int kernel, CommandBuffer buffer, Cubemap defaultMap)
 {
     buffer.SetComputeBufferParam(targetShader, kernel, ShaderIDs._ReflectionIndices, reflectionIndices);
     buffer.SetComputeBufferParam(targetShader, kernel, ShaderIDs._ReflectionData, probeBuffer);
     for (int i = 0; i < reflectionCount; ++i)
     {
         Texture tx = reflectProbes[i].texture;
         if (!tx)
         {
             tx = defaultMap;
         }
         buffer.SetComputeTextureParam(targetShader, kernel, reflectionCubemapIDs[i], tx);
     }
     for (int i = reflectionCount; i < maximumProbe; ++i)
     {
         buffer.SetComputeTextureParam(targetShader, kernel, reflectionCubemapIDs[i], defaultMap);
     }
 }
    void PrefilterEnvMapIrradiance()
    {
        if (mPBRObject == null)
        {
            //创建一个cube
            mPBRObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
            mPBRObject.AddComponent <Camera>();
            mPBRObject.layer = LayerMask.NameToLayer("RenderToCubemap");
            mPBRObject.transform.position = Vector3.zero;
            mPBRObject.transform.rotation = Quaternion.identity;
        }
        //if (mCameraObject == null)
        //{
        //    mCameraObject = new GameObject("RenderToCubemap");
        //    mCameraObject.transform.position = mPBRObject.transform.position;
        //    mCameraObject.transform.rotation = Quaternion.identity;
        //}

        Camera camera = mPBRObject.GetComponent <Camera>();

        if (camera != null)
        {
            //camera = mCameraObject.AddComponent<Camera>();
            mCamera = camera;
        }
        else
        {
            mCamera = mPBRObject.AddComponent <Camera>();
        }

        mCamera.clearFlags      = CameraClearFlags.SolidColor;
        mCamera.backgroundColor = Color.black;
        mCamera.targetTexture   = null;
        mCamera.cullingMask     = 1 << LayerMask.NameToLayer("RenderToCubemap");


        if (mPrefilterIrradianceDiffuseMaterial == null)
        {
            Shader prefilterCube = Shader.Find("liangairan/pbr/prefilterIrradianceCubemap");
            mPrefilterIrradianceDiffuseMaterial = new Material(prefilterCube);
            mPrefilterIrradianceDiffuseMaterial.SetTexture("_Cube", mEnvironmentMap);
        }

        mPBRObject.GetComponent <Renderer>().sharedMaterial = mPrefilterIrradianceDiffuseMaterial;


        Cubemap irradianceDiffuseMap = (Cubemap)AssetDatabase.LoadAssetAtPath(mOutputPath + "irradianceDiffuseMap.cubemap", typeof(Cubemap));
        bool    bNewAsset            = false;

        if (irradianceDiffuseMap == null)
        {
            irradianceDiffuseMap = new Cubemap(mOutputIrradianceDiffuseMapSize, TextureFormat.RGBAHalf, true);

            bNewAsset = true;
        }
        camera.RenderToCubemap(irradianceDiffuseMap, 63);
        irradianceDiffuseMap.Apply();


        if (bNewAsset)
        {
            AssetDatabase.CreateAsset(irradianceDiffuseMap, mOutputPath + "irradianceDiffuseMap.cubemap");
        }
        else
        {
            AssetDatabase.SaveAssets();
        }

        irradianceDiffuseMap = null;
        //DestroyImmediate(irradianceDiffuseMap);
    }
 private void renderCube(Cubemap envMap, Vector3 cameraPos, int layerMask, float nearClip, float farClip)
 {
     cameraSetup(cameraPos, layerMask, nearClip, farClip);
     reflectionCamera.RenderToCubemap(envMap);
 }
 static void PostprocessCubemap(Cubemap tex, string pathName)
 {
     object[] args = { tex };
     CallPostProcessMethods("OnPostprocessCubemap", args);
 }
 public static extern void SetSourceTexture(Cubemap cubemapRef, CubemapFace face, Texture2D tex);
    private AlienTexture LoadTexture(int EntryIndex, int paktype = 0, bool loadV1 = true)
    {
        AlienTexture toReturn = new AlienTexture();

        alien_textures AlienTextures = GetTexturesTable(paktype);

        if (EntryIndex < 0 || EntryIndex >= AlienTextures.PAK.Header.EntryCount)
        {
            Debug.LogWarning("Asked to load texture at index " + EntryIndex + ", which is out of bounds!");
            return(null);
        }

        alien_pak_entry           Entry     = AlienTextures.PAK.Entries[EntryIndex];
        alien_texture_bin_texture InTexture = AlienTextures.BIN.Textures[Entry.BINIndex];

        Vector2 textureDims;
        int     textureLength = 0;
        int     mipLevels     = 0;

        if (loadV1)
        {
            textureDims   = new Vector2(InTexture.Size_V1[0], InTexture.Size_V1[1]);
            textureLength = InTexture.Length_V1;
            mipLevels     = InTexture.MipLevelsV1;
        }
        else
        {
            textureDims   = new Vector2(InTexture.Size_V2[0], InTexture.Size_V2[1]);
            textureLength = InTexture.Length_V2;
            mipLevels     = InTexture.MipLevelsV2;
        }

        if (textureLength == 0)
        {
            Debug.LogWarning("LENGTH ZERO - NOT LOADING");
            return(toReturn);
        }

        UnityEngine.TextureFormat format = UnityEngine.TextureFormat.BC7;
        switch (InTexture.Format)
        {
        case alien_texture_format.Alien_R32G32B32A32_SFLOAT:
            format = UnityEngine.TextureFormat.RGBA32;
            break;

        case alien_texture_format.Alien_FORMAT_R8G8B8A8_UNORM:
            format = UnityEngine.TextureFormat.ETC2_RGBA8;     //?
            break;

        case alien_texture_format.Alien_FORMAT_R8G8B8A8_UNORM_0:
            format = UnityEngine.TextureFormat.ETC2_RGBA8;     //?
            break;

        case alien_texture_format.Alien_FORMAT_SIGNED_DISTANCE_FIELD:
            Debug.LogWarning("SDF! NOT LOADED");
            return(toReturn);

        case alien_texture_format.Alien_FORMAT_R8:
            format = UnityEngine.TextureFormat.R8;
            break;

        case alien_texture_format.Alien_FORMAT_BC1:
            format = UnityEngine.TextureFormat.DXT1;
            break;

        case alien_texture_format.Alien_FORMAT_BC2:
            Debug.LogWarning("BC2! NOT LOADED");
            return(toReturn);

        case alien_texture_format.Alien_FORMAT_BC5:
            format = UnityEngine.TextureFormat.BC5;     //Is this correct?
            break;

        case alien_texture_format.Alien_FORMAT_BC3:
            format = UnityEngine.TextureFormat.DXT5;
            break;

        case alien_texture_format.Alien_FORMAT_BC7:
            format = UnityEngine.TextureFormat.BC7;
            break;

        case alien_texture_format.Alien_FORMAT_R8G8:
            format = UnityEngine.TextureFormat.BC5;     // is this correct?
            break;
        }

        BinaryReader tempReader = new BinaryReader(new MemoryStream(AlienTextures.PAK.DataStart));

        tempReader.BaseStream.Position = Entry.Offset;

        if (InTexture.Type == 7)
        {
            Cubemap cubemapTex = new Cubemap((int)textureDims.x, format, true);
            cubemapTex.name = AlienTextures.BIN.TextureFilePaths[Entry.BINIndex];
            cubemapTex.SetPixelData(tempReader.ReadBytes(textureLength / 6), 0, CubemapFace.PositiveX);
            cubemapTex.SetPixelData(tempReader.ReadBytes(textureLength / 6), 0, CubemapFace.NegativeX);
            cubemapTex.SetPixelData(tempReader.ReadBytes(textureLength / 6), 0, CubemapFace.PositiveY);
            cubemapTex.SetPixelData(tempReader.ReadBytes(textureLength / 6), 0, CubemapFace.NegativeY);
            cubemapTex.SetPixelData(tempReader.ReadBytes(textureLength / 6), 0, CubemapFace.PositiveZ);
            cubemapTex.SetPixelData(tempReader.ReadBytes(textureLength / 6), 0, CubemapFace.NegativeZ);
            cubemapTex.Apply();
            toReturn.cubemap = cubemapTex;
            //AssetDatabase.CreateAsset(cubemapTex, "Assets/Cubemaps/" + Path.GetFileNameWithoutExtension(cubemapTex.name) + ".cubemap");
        }
        else
        {
            Texture2D texture = new Texture2D((int)textureDims[0], (int)textureDims[1], format, mipLevels, true);
            texture.name = AlienTextures.BIN.TextureFilePaths[Entry.BINIndex];
            texture.LoadRawTextureData(tempReader.ReadBytes(textureLength));
            texture.Apply();
            toReturn.texture = texture;
        }

        tempReader.Close();
        return(toReturn);
    }
 public static extern void CopyCubemapFaceIntoTexture(Cubemap cubemapRef, CubemapFace face, Texture2D textureRef);
示例#30
0
        protected void ApplyPresetBase(TunnellingPresetBase p)
        {
            if (p.overrideEffectCoverage)
            {
                effectCoverage = p.effectCoverage;
            }
            if (p.overrideEffectColor)
            {
                effectColor = p.effectColor;
            }
            if (p.overrideEffectFeather)
            {
                effectFeather = p.effectFeather;
            }
            if (p.overrideApplyColorToBackground)
            {
                applyColorToBackground = p.applyColorToBackground;
            }
            if (p.overrideSkybox)
            {
                effectSkybox = p.skybox;
            }

            if (p.overrideAngularVelocity)
            {
                useAngularVelocity       = p.angularVelocity.use;
                angularVelocityStrength  = p.angularVelocity.strength;
                angularVelocityMin       = p.angularVelocity.min;
                angularVelocityMax       = p.angularVelocity.max;
                angularVelocitySmoothing = p.angularVelocity.smoothing;
            }

            if (p.overrideAcceleration)
            {
                useAcceleration       = p.acceleration.use;
                accelerationStrength  = p.acceleration.strength;
                accelerationMin       = p.acceleration.min;
                accelerationMax       = p.acceleration.max;
                accelerationSmoothing = p.acceleration.smoothing;
            }

            if (p.overrideVelocity)
            {
                useVelocity       = p.velocity.use;
                velocityStrength  = p.velocity.strength;
                velocityMin       = p.velocity.min;
                velocityMax       = p.velocity.max;
                velocitySmoothing = p.velocity.smoothing;
            }

            if (p.overrideUseCounterMotion)
            {
                useCounterMotion = p.useCounterMotion;
            }
            if (p.overrideCounterRotationPerAxis)
            {
                counterRotationPerAxis = p.counterRotationPerAxis;
            }

            if (p.overrideUseArtificialTilt)
            {
                useArtificialTilt = p.useArtificialTilt;
            }

            if (p.overrideFramerateDivision)
            {
                framerateDivision = p.framerateDivision;
            }
            if (p.overrideDivideTranslation)
            {
                divideTranslation = p.divideTranslation;
            }
            if (p.overrideDividerotation)
            {
                divideRotation = p.divideRotation;
            }
        }
 public static extern bool IsCubemapReadable(Cubemap cubemapRef);
示例#32
0
 void OnPostprocessCubemap(Cubemap texture)
 {
 }
 public static extern bool GetCubemapStreamingMipmaps(Cubemap cubemap);
        Texture ConvolveProbeTexture(CommandBuffer cmd, Texture texture)
        {
            // Probes can be either Cubemaps (for baked probes) or RenderTextures (for realtime probes)
            Cubemap       cubeTexture   = texture as Cubemap;
            RenderTexture renderTexture = texture as RenderTexture;

            RenderTexture convolutionSourceTexture = null;

            if (cubeTexture != null)
            {
                // if the size if different from the cache probe size or if the input texture format is compressed, we need to convert it
                // 1) to a format for which we can generate mip maps
                // 2) to the proper reflection probe cache size
                bool sizeMismatch   = cubeTexture.width != m_ProbeSize || cubeTexture.height != m_ProbeSize;
                bool formatMismatch = cubeTexture.format != TextureFormat.RGBAHalf; // Temporary RT for convolution is always FP16
                if (formatMismatch || sizeMismatch)
                {
                    if (sizeMismatch)
                    {
                        Debug.LogWarningFormat("Baked Reflection Probe {0} does not match HDRP Reflection Probe Cache size of {1}. Consider baking it at the same size for better loading performance.", texture.name, m_ProbeSize);
                    }
                    else if (cubeTexture.format == TextureFormat.BC6H)
                    {
                        Debug.LogWarningFormat("Baked Reflection Probe {0} is compressed but the HDRP Reflection Probe Cache is not. Consider removing compression from the input texture for better quality.", texture.name);
                    }
                    ConvertTexture(cmd, cubeTexture, m_TempRenderTexture);
                }
                else
                {
                    for (int f = 0; f < 6; f++)
                    {
                        cmd.CopyTexture(cubeTexture, f, 0, m_TempRenderTexture, f, 0);
                    }
                }

                // Ideally if input is not compressed and has mipmaps, don't do anything here. Problem is, we can't know if mips have been already convolved offline...
                cmd.GenerateMips(m_TempRenderTexture);
                convolutionSourceTexture = m_TempRenderTexture;
            }
            else
            {
                Debug.Assert(renderTexture != null);
                if (renderTexture.dimension != TextureDimension.Cube)
                {
                    Debug.LogError("Realtime reflection probe should always be a Cube RenderTexture.");
                    return(null);
                }

                // TODO: Do a different case for downsizing, in this case, instead of doing ConvertTexture just use the relevant mipmaps.
                bool sizeMismatch = renderTexture.width != m_ProbeSize || renderTexture.height != m_ProbeSize;
                if (sizeMismatch)
                {
                    ConvertTexture(cmd, renderTexture, m_TempRenderTexture);
                    convolutionSourceTexture = m_TempRenderTexture;
                }
                else
                {
                    convolutionSourceTexture = renderTexture;
                }
                // Generate unfiltered mipmaps as a base for convolution
                // TODO: Make sure that we don't first convolve everything on the GPU with the legacy code path executed after rendering the probe.
                cmd.GenerateMips(convolutionSourceTexture);
            }

            m_IBLFilterGGX.FilterCubemap(cmd, convolutionSourceTexture, m_ConvolutionTargetTexture);

            return(m_ConvolutionTargetTexture);
        }
 public static extern void SetCubemapStreamingMipmaps(Cubemap cubemapRef, bool streaming);
示例#36
0
		private static void INTERNAL_CALL_SetPixel(Cubemap self, CubemapFace face, int x, int y, ref Color color){}