EnableKeyword() private method

private EnableKeyword ( string keyword ) : void
keyword string
return void
        /// <summary>
        /// Initializes the primary mesh material.
        /// Note: for good explanation of Renderer.materials see http://answers.unity3d.com/questions/228744/material-versus-shared-material.html
        /// </summary>
        /// <param name="material">The material.</param>
        private void InitializePrimaryMeshMaterial(Material material) {
            if (!material.IsKeywordEnabled(UnityConstants.StdShader_RenderModeKeyword_FadeTransparency)) {
                material.EnableKeyword(UnityConstants.StdShader_RenderModeKeyword_FadeTransparency);
            }
            if (!material.IsKeywordEnabled(UnityConstants.StdShader_MapKeyword_Metallic)) {
                material.EnableKeyword(UnityConstants.StdShader_MapKeyword_Metallic);
            }
            /*******************************************************************************************
            * These values were set when I wasn't using the metal material's MetallicMap, opting
            * instead to set these. UNCLEAR Why I don't know, but not using the MatallicMap kept the
            * colors from showing up on the element unless the shader tab was clicked in the inspector.
            *
            * if (material.GetFloat(UnityConstants.StdShader_Property_MetallicFloat) != 0.25F) {
            *     material.SetFloat(UnityConstants.StdShader_Property_MetallicFloat, 0.25F);
            * }
            * if (material.GetFloat(UnityConstants.StdShader_Property_SmoothnessFloat) != 0.4F) {
            *     material.SetFloat(UnityConstants.StdShader_Property_SmoothnessFloat, 0.4F);
            * }
            *******************************************************************************************/

            if (!material.IsKeywordEnabled(UnityConstants.StdShader_MapKeyword_Normal)) {
                material.EnableKeyword(UnityConstants.StdShader_MapKeyword_Normal);
            }
            if (material.GetFloat(UnityConstants.StdShader_Property_NormalScaleFloat) != 1.25F) {
                material.SetFloat(UnityConstants.StdShader_Property_NormalScaleFloat, 1.25F);
            }
        }
    private void SetColorRange(Material material)
    {
        switch (ColorRange)
        {
            case TOD_ColorRangeType.Auto:
                if (Components.Camera && Components.Camera.HDR)
                {
                    material.EnableKeyword("HDR");
                    material.DisableKeyword("LDR");
                }
                else
                {
                    material.DisableKeyword("HDR");
                    material.EnableKeyword("LDR");
                }
                break;

            case TOD_ColorRangeType.HDR:
                material.EnableKeyword("HDR");
                material.DisableKeyword("LDR");
                break;

            case TOD_ColorRangeType.LDR:
                material.DisableKeyword("HDR");
                material.EnableKeyword("LDR");
                break;
        }
    }
 public override Material CloneMaterial(Material src, int nth)
 {
     Material m = new Material(src);
     m.SetInt("g_batch_begin", nth * m_instances_par_batch);
     m.SetBuffer("particles", m_world.GetParticleBuffer());
     if (m_hdr)
     {
         m.SetInt("_SrcBlend", (int)BlendMode.One);
         m.SetInt("_DstBlend", (int)BlendMode.One);
     }
     else
     {
         m.SetInt("_SrcBlend", (int)BlendMode.DstColor);
         m.SetInt("_DstBlend", (int)BlendMode.Zero);
     }
     if(m_enable_shadow)
     {
         m.EnableKeyword("ENABLE_SHADOW");
         switch (m_sample)
         {
             case Sample.Fast:
                 m.EnableKeyword("QUALITY_FAST");
                 break;
             case Sample.Medium:
                 m.EnableKeyword("QUALITY_MEDIUM");
                 break;
             case Sample.High:
                 m.EnableKeyword("QUALITY_HIGH");
                 break;
         }
     }
     return m;
 }
	private void GenerateWireframeMeshsAndMaterials() {
		foreach (MeshNMaterial subObj in subObjects) {
			//添加AmazingWireframeGenerator
			subObj.gameObject.AddComponent<TheAmazingWireframeGenerator>();
			for (int i = 0;i < subObj.originalMaterials.Length;i++) {
				Material wireframeNoTexMat = new Material(
					Shader.Find("VacuumShaders/The Amazing Wireframe/Unlit/NoTex"));
				wireframeNoTexMat.SetColor("_Color", subObj.originalMaterials[i].GetColor("_Color"));
				wireframeNoTexMat.EnableKeyword("V_WIRE_ANTIALIASING_ON");
				wireframeNoTexMat.EnableKeyword("V_WIRE_LIGHT_ON");
				subObj.wireframeNoTexMaterials[i] = wireframeNoTexMat;
				Material wireframeTexMat = new Material(
						Shader.Find("VacuumShaders/The Amazing Wireframe/Deferred/Bumped Specular"));
				wireframeTexMat.SetColor("_Color", subObj.originalMaterials[i].GetColor("_Color"));
				if (subObj.originalMaterials[i].HasProperty("_SpecColor"))
					wireframeTexMat.SetColor("_SpecColor", subObj.originalMaterials[i].GetColor("_SpecColor"));
				if (subObj.originalMaterials[i].HasProperty("_Shininess"))
					wireframeTexMat.SetFloat("_Shininess", subObj.originalMaterials[i].GetFloat("_Shininess"));
				wireframeTexMat.SetTexture("_MainTex", subObj.originalMaterials[i].GetTexture("_MainTex"));
				if (subObj.originalMaterials[i].HasProperty("_BumpMap"))
					wireframeTexMat.SetTexture("_BumpMap", subObj.originalMaterials[i].GetTexture("_BumpMap"));
				wireframeTexMat.EnableKeyword("V_WIRE_ANTIALIASING_ON");
				wireframeTexMat.EnableKeyword("V_WIRE_LIGHT_ON");
				subObj.wireframeTexMaterials[i] = wireframeTexMat;
			}
		}
	}
    private void SetColorSpace(Material material)
    {
        switch (ColorSpace)
        {
            case TOD_ColorSpaceType.Auto:
                if (QualitySettings.activeColorSpace == UnityEngine.ColorSpace.Linear)
                {
                    material.EnableKeyword("LINEAR");
                    material.DisableKeyword("GAMMA");
                }
                else
                {
                    material.DisableKeyword("LINEAR");
                    material.EnableKeyword("GAMMA");
                }
                break;

            case TOD_ColorSpaceType.Linear:
                material.EnableKeyword("LINEAR");
                material.DisableKeyword("GAMMA");
                break;

            case TOD_ColorSpaceType.Gamma:
                material.DisableKeyword("LINEAR");
                material.EnableKeyword("GAMMA");
                break;
        }
    }
Beispiel #6
0
        private static UnityEngine.Material CreateMaterial(EditorMaterial editorMat)
        {
            bool doubleSided = editorMat.PolygonType.HasFlag(PolyType.DOUBLESIDED);
            bool transparent = editorMat.PolygonType.HasFlag(PolyType.TRANS);
            bool water       = editorMat.PolygonType.HasFlag(PolyType.WATER);
            bool glow        = editorMat.PolygonType.HasFlag(PolyType.GLOW);
            bool lava        = editorMat.PolygonType.HasFlag(PolyType.LAVA);
            bool fall        = editorMat.PolygonType.HasFlag(PolyType.FALL);

            UnityEngine.Material mat;
            if (doubleSided && transparent)
            {
                mat = MaterialsDatabase.ArxMatDoubleSidedTransparent;
            }
            else if (doubleSided)
            {
                mat = MaterialsDatabase.ArxMatDoubleSided;
            }
            else if (transparent)
            {
                mat = MaterialsDatabase.ArxMatTransparent;
            }
            else
            {
                mat = MaterialsDatabase.ArxMat;
            }
            mat             = UnityEngine.Object.Instantiate(mat);
            mat.name        = editorMat.TexturePath;
            mat.mainTexture = LevelEditor.TextureDatabase[editorMat.TexturePath];
            if (transparent)
            {//transparents look better with point filtering
                //TODO: check transval
                if (mat.mainTexture != null)
                {
                    mat.mainTexture.filterMode = FilterMode.Point;//should do this on an instance of the tex, but that would break the caching.. ughhhh TODO!!!
                }
            }
            //The following keywords cause scrolling of the texture etc, so its done using shader variants
            if (water)
            {
                mat.EnableKeyword("WATER");
            }
            if (lava)
            {
                mat.EnableKeyword("LAVA");
            }
            if (glow)
            {
                mat.EnableKeyword("GLOW");
            }
            if (fall)
            {
                mat.EnableKeyword("FALL");
            }
            return(mat);
        }
 private void RefreshDrawSelfShadowKeyword(bool drawSelfshadow, UnityEngine.Material material)
 {
     if (drawSelfshadow)
     {
         material.EnableKeyword("SELFSHADOW_ON");
         material.DisableKeyword("SELFSHADOW_OFF");
     }
     else
     {
         material.DisableKeyword("SELFSHADOW_ON");
         material.EnableKeyword("SELFSHADOW_OFF");
     }
 }
        private void InitializePrimaryMeshMaterial(Material material) {
            // no need to enable RenderingMode.Opaque as it is the default            // for now, color is green
            if (material.IsKeywordEnabled(UnityConstants.StdShader_MapKeyword_Metallic)) {
                material.EnableKeyword(UnityConstants.StdShader_MapKeyword_Metallic);
            }
            material.SetFloat(UnityConstants.StdShader_Property_MetallicFloat, Constants.ZeroF);
            material.SetFloat(UnityConstants.StdShader_Property_SmoothnessFloat, 0.20F);

            if (!material.IsKeywordEnabled(UnityConstants.StdShader_MapKeyword_Normal)) {
                material.EnableKeyword(UnityConstants.StdShader_MapKeyword_Normal);
            }
            material.SetFloat(UnityConstants.StdShader_Property_NormalScaleFloat, 1F);
        }
    public static void SetMaterialRenderingMode(Material material, StandardShaderRenderingMode mode)
    {
        switch (mode)
        {
        case StandardShaderRenderingMode.Opaque:
            material.SetOverrideTag("RenderType", "");
            material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
            material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
            material.SetInt("_ZWrite", 1);
            material.DisableKeyword("_ALPHATEST_ON");
            material.DisableKeyword("_ALPHABLEND_ON");
            material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
            material.renderQueue = -1;
            break;

        case StandardShaderRenderingMode.Cutout:
            material.SetOverrideTag("RenderType", "TransparentCutout");
            material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
            material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
            material.SetInt("_ZWrite", 1);
            material.EnableKeyword("_ALPHATEST_ON");
            material.DisableKeyword("_ALPHABLEND_ON");
            material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
            material.renderQueue = 2450;
            break;

        case StandardShaderRenderingMode.Fade:
            material.SetOverrideTag("RenderType", "Transparent");
            material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
            material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
            material.SetInt("_ZWrite", 0);
            material.DisableKeyword("_ALPHATEST_ON");
            material.EnableKeyword("_ALPHABLEND_ON");
            material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
            material.renderQueue = 3000;
            break;

        case StandardShaderRenderingMode.Transparent:
            material.SetOverrideTag("RenderType", "Transparent");
            material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
            material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
            material.SetInt("_ZWrite", 0);
            material.DisableKeyword("_ALPHATEST_ON");
            material.DisableKeyword("_ALPHABLEND_ON");
            material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
            material.renderQueue = 3000;
            break;
        }
    }
Beispiel #10
0
    private Material MakeMaterial()
    {
        Material newMaterial = new Material(Shader.Find("Standard"));
        newMaterial.SetFloat("_Mode", 1.0f);
        newMaterial.EnableKeyword("_ALPHATEST_ON");
        newMaterial.EnableKeyword("_NORMALMAP");
        newMaterial.SetTexture("_BumpMap", AssetDatabase.LoadAssetAtPath<Texture>("Assets/Sprites/Frogs/" + referencePath + "/Processed/" + referencePath.Replace(" ", "") + spriteName + "_NORMALS.png"));
        //newMaterial.SetTexture("_SpecGlossMap", AssetDatabase.LoadAssetAtPath<Texture>("Assets/Sprites/Frogs/" + referencePath + "/Processed/" + referencePath.Replace(" ", "") + spriteName + "_SPECULAR.png"));
        newMaterial.SetTexture("_ParallaxMap", AssetDatabase.LoadAssetAtPath<Texture>("Assets/Sprites/Frogs/" + referencePath + "/Processed/" + referencePath.Replace(" ", "") + spriteName + "_DEPTH.png"));
        newMaterial.SetTexture("_OcclusionMap", AssetDatabase.LoadAssetAtPath<Texture>("Assets/Sprites/Frogs/" + referencePath + "/Processed/" + referencePath.Replace(" ", "") + spriteName + "_OCCLUSION.png"));
        newMaterial.SetFloat("_Glossiness", 0);
        AssetDatabase.CreateAsset(newMaterial, "Assets/Sprites/Frogs/" + referencePath + "/" + referencePath.Replace(" ", "") + spriteName + ".mat");

        return AssetDatabase.LoadAssetAtPath<Material>("Assets/Sprites/Frogs/" + referencePath + "/" + referencePath.Replace(" ", "") + spriteName + ".mat");
    }
Beispiel #11
0
    IEnumerator Start()
    {
        foreach (var r in GetComponentsInChildren<Renderer>()) {
            renderers.Add(r);
            originalMaterials[r] = r.sharedMaterial;

            var material = new Material(r.material);
            material.SetFloat("_Mode", 2);
            material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
            material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
            material.SetInt("_ZWrite", 0);
            material.DisableKeyword("_ALPHATEST_ON");
            material.EnableKeyword("_ALPHABLEND_ON");
            material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
            material.renderQueue = 3000;
            r.material = material;
        }

        for (float t = 0; t < 1f; t += Time.deltaTime) {
            if (!UpdateRenderers(t)) {
                yield break;
            }

            yield return null;
        }

        foreach (var r in renderers) {
            if (r) {
                r.material = originalMaterials[r];
            }
        }

        Destroy(this);
    }
 static void SetKeyword(Material m, string keyword, bool state)
 {
     if (state)
         m.EnableKeyword(keyword);
     else
         m.DisableKeyword(keyword);
 }
        protected override RenderQueue?ApplyTransmission(
            ref Color baseColorLinear,
            IGltfReadable gltf,
            Transmission transmission,
            Material material,
            RenderQueue?renderQueue
            )
        {
            if (supportsCameraOpaqueTexture)
            {
                if (transmission.transmissionFactor > 0f)
                {
                    material.EnableKeyword("TRANSMISSION");
                    material.SetFloat(transmissionFactorPropId, transmission.transmissionFactor);
                    renderQueue = RenderQueue.Transparent;
                    if (TrySetTexture(transmission.transmissionTexture, material, transmissionTexturePropId, gltf))
                    {
                    }
                }
                return(renderQueue);
            }

            return(base.ApplyTransmission(
                       ref baseColorLinear,
                       gltf,
                       transmission,
                       material,
                       renderQueue
                       ));
        }
 public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode)
 {
     switch (blendMode)
     {
     case BlendMode.Opaque:
         material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
         material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
         material.SetInt("_ZWrite", 1);
         material.DisableKeyword("_ALPHATEST_ON");
         material.DisableKeyword("_ALPHABLEND_ON");
         material.renderQueue = -1;
         break;
     case BlendMode.Cutout:
         material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
         material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
         material.SetInt("_ZWrite", 1);
         material.EnableKeyword("_ALPHATEST_ON");
         material.DisableKeyword("_ALPHABLEND_ON");
         material.renderQueue = 2450;
         break;
     case BlendMode.Transparent:
         material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
         material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
         material.SetInt("_ZWrite", 0);
         material.DisableKeyword("_ALPHATEST_ON");
         material.EnableKeyword("_ALPHABLEND_ON");
         material.renderQueue = 3000;
         break;
     }
 }
Beispiel #15
0
 public static void SetAlphaModeMask(UnityEngine.Material material)
 {
     material.SetFloat(modePropId, (int)StandardShaderMode.Cutout);
     material.SetOverrideTag("RenderType", "TransparentCutout");
     material.EnableKeyword("_ALPHATEST_ON");
     material.renderQueue = 2450;
 }
Beispiel #16
0
        protected override RenderQueue?ApplyTransmission(
            ref Color baseColorLinear,
            ref Texture[] textures,
            ref Image[] schemaImages,
            ref Dictionary <int, Texture2D>[] imageVariants,
            Transmission transmission,
            Material material,
            RenderQueue?renderQueue
            )
        {
            if (supportsCameraOpaqueTexture)
            {
                if (transmission.transmissionFactor > 0f)
                {
                    material.EnableKeyword("TRANSMISSION");
                    material.SetFloat(transmissionFactorPropId, transmission.transmissionFactor);
                    renderQueue = RenderQueue.Transparent;
                    if (TrySetTexture(transmission.transmissionTexture, material, transmissionTexturePropId, ref textures, ref schemaImages, ref imageVariants))
                    {
                    }
                }
                return(renderQueue);
            }

            return(base.ApplyTransmission(
                       ref baseColorLinear,
                       ref textures,
                       ref schemaImages,
                       ref imageVariants,
                       transmission,
                       material,
                       renderQueue
                       ));
        }
 static void TrySetTextureTransform(
     Schema.TextureInfo textureInfo,
     UnityEngine.Material material,
     int propertyId
     )
 {
     if (textureInfo.extensions != null && textureInfo.extensions.KHR_texture_transform != null)
     {
         var tt = textureInfo.extensions.KHR_texture_transform;
         if (tt.texCoord != 0)
         {
             Debug.LogError("Multiple UV sets are not supported!");
         }
         if (tt.offset != null)
         {
             material.SetTextureOffset(propertyId, new Vector2(tt.offset[0], 1 - tt.offset[1]));
         }
         if (tt.rotation != 0)
         {
             float cos = Mathf.Cos(tt.rotation);
             float sin = Mathf.Sin(tt.rotation);
             material.SetVector(StandardShaderHelper.mainTexRotatePropId, new Vector4(cos, -sin, sin, cos));
             material.EnableKeyword(StandardShaderHelper.KW_UV_ROTATION);
         }
         if (tt.scale != null)
         {
             material.SetTextureScale(propertyId, new Vector2(tt.scale[0], -tt.scale[1]));
         }
     }
 }
Beispiel #18
0
        private static void TrySetTextureTransform(
            Schema.TextureInfo textureInfo,
            UnityEngine.Material material,
            int propertyId,
            bool flipY = false
            )
        {
            // Scale (x,y) and Transform (z,w)
            float4 textureST = new float4(
                1, 1, // scale
                0, 0  // transform
                );

            if (textureInfo.extensions != null && textureInfo.extensions.KHR_texture_transform != null)
            {
                var tt = textureInfo.extensions.KHR_texture_transform;
                if (tt.texCoord != 0)
                {
                    Debug.LogError(ERROR_MULTI_UVS);
                }

                float cos = 1;
                float sin = 0;

                if (tt.offset != null)
                {
                    textureST.z = tt.offset[0];
                    textureST.w = 1 - tt.offset[1];
                }
                if (tt.scale != null)
                {
                    textureST.x = tt.scale[0];
                    textureST.y = tt.scale[1];
                }
                if (tt.rotation != 0)
                {
                    cos = math.cos(tt.rotation);
                    sin = math.sin(tt.rotation);

                    var newRot = new Vector2(textureST.x * sin, textureST.y * -sin);
                    material.SetVector(mainTexRotation, newRot);
                    textureST.x *= cos;
                    textureST.y *= cos;

                    material.EnableKeyword(KW_UV_ROTATION);
                    textureST.z -= newRot.y; // move offset to move rotation point (horizontally)
                }

                textureST.w -= textureST.y * cos; // move offset to move flip axis point (vertically)
            }

            if (flipY)
            {
                textureST.z = 1 - textureST.z; // flip offset in Y
                textureST.y = -textureST.y;    // flip scale in Y
            }

            material.SetVector(mainTexScaleTransform, textureST);
        }
Beispiel #19
0
        public UnityEngine.Material CreateMaterial(PbrMaterial vpxMaterial, TableBehavior table, StringBuilder debug = null)
        {
            var unityMaterial = new UnityEngine.Material(GetShader())
            {
                name = vpxMaterial.Id
            };

            // apply some basic manipulations to the color. this just makes very
            // very white colors be clipped to 0.8204 aka 204/255 is 0.8
            // this is to give room to lighting values. so there is more modulation
            // of brighter colors when being lit without blow outs too soon.
            var col = vpxMaterial.Color.ToUnityColor();

            if (vpxMaterial.Color.IsGray() && col.grayscale > 0.8)
            {
                debug?.AppendLine("Color manipulation performed, brightness reduced.");
                col.r = col.g = col.b = 0.8f;
            }

            // alpha for color depending on blend mode
            ApplyBlendMode(unityMaterial, vpxMaterial.MapBlendMode);
            if (vpxMaterial.MapBlendMode == BlendMode.Translucent)
            {
                col.a = Mathf.Min(1, Mathf.Max(0, vpxMaterial.Opacity));
            }

            unityMaterial.SetColor(BaseColor, col);

            // validate IsMetal. if true, set the metallic value.
            // found VPX authors setting metallic as well as translucent at the
            // same time, which does not render correctly in unity so we have
            // to check if this value is true and also if opacity <= 1.
            if (vpxMaterial.IsMetal && (!vpxMaterial.IsOpacityActive || vpxMaterial.Opacity >= 1))
            {
                unityMaterial.SetFloat(Metallic, 1f);
                debug?.AppendLine("Metallic set to 1.");
            }

            // roughness / glossiness
            unityMaterial.SetFloat(Smoothness, vpxMaterial.Roughness);


            // map
            if (table != null && vpxMaterial.HasMap)
            {
                unityMaterial.SetTexture(BaseMap, table.GetTexture(vpxMaterial.Map.Name));
            }

            // normal map
            if (table != null && vpxMaterial.HasNormalMap)
            {
                unityMaterial.EnableKeyword("_NORMALMAP");

                unityMaterial.SetTexture(BumpMap, table.GetTexture(vpxMaterial.NormalMap.Name)
                                         );
            }

            return(unityMaterial);
        }
Beispiel #20
0
        void Start()
        {
            material = GetComponentInChildren<Renderer>().material;
            material.EnableKeyword("_EMISSION");

            timer = 0f;
            t = 0f;
        }
 public static void SetShaderBlendMode(BlendMode blendMode, ref Material material)
 {
     switch (blendMode) {
         case BlendMode.Opaque:
             material.SetFloat("_Mode", (float)BlendMode.Opaque);
             material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
             material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
             material.SetInt("_ZWrite", 1);
             material.DisableKeyword("_ALPHATEST_ON");
             material.DisableKeyword("_ALPHABLEND_ON");
             material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
             material.renderQueue = -1;
             break;
         case BlendMode.Cutout:
             material.SetFloat("_Mode", (float)BlendMode.Cutout);
             material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
             material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
             material.SetInt("_ZWrite", 1);
             material.EnableKeyword("_ALPHATEST_ON");
             material.DisableKeyword("_ALPHABLEND_ON");
             material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
             material.renderQueue = 2450;
             break;
         case BlendMode.Fade:
             material.SetFloat("_Mode", (float)BlendMode.Fade);
             material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
             material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
             material.SetInt("_ZWrite", 0);
             material.DisableKeyword("_ALPHATEST_ON");
             material.EnableKeyword("_ALPHABLEND_ON");
             material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
             material.renderQueue = 3000;
             break;
         case BlendMode.Transparent:
             material.SetFloat("_Mode", (float)BlendMode.Transparent);
             material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
             material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
             material.SetInt("_ZWrite", 0);
             material.DisableKeyword("_ALPHATEST_ON");
             material.DisableKeyword("_ALPHABLEND_ON");
             material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
             material.renderQueue = 3000;
             break;
     }
 }
Beispiel #22
0
 protected override void SetShaderModeBlend(Schema.Material gltfMaterial, Material material)
 {
     material.SetOverrideTag(TAG_RENDER_TYPE, TAG_RENDER_TYPE_TRANSPARENT);
     material.EnableKeyword(KW_SURFACE_TYPE_TRANSPARENT);
     material.EnableKeyword(KW_DISABLE_SSR_TRANSPARENT);
     material.EnableKeyword(KW_ENABLE_FOG_ON_TRANSPARENT);
     material.SetShaderPassEnabled(k_ShaderPassTransparentDepthPrepass, false);
     material.SetShaderPassEnabled(k_ShaderPassTransparentDepthPostpass, false);
     material.SetShaderPassEnabled(k_ShaderPassTransparentBackface, false);
     material.SetShaderPassEnabled(k_ShaderPassRayTracingPrepass, false);
     material.SetShaderPassEnabled(k_ShaderPassDepthOnlyPass, false);
     material.SetFloat(srcBlendPropId, (int)BlendMode.SrcAlpha);                //5
     material.SetFloat(dstBlendPropId, (int)BlendMode.OneMinusSrcAlpha);        //10
     material.SetFloat(k_ZTestGBufferPropId, (int)CompareFunction.Equal);       //3
     material.SetFloat(k_AlphaDstBlendPropId, (int)BlendMode.OneMinusSrcAlpha); //10
     material.SetFloat(k_Surface, 1);
     material.SetFloat(zWritePropId, 0);
 }
Beispiel #23
0
        protected virtual void SetAlphaModeMask(Schema.Material gltfMaterial, Material material)
        {
            material.SetFloat(cutoffPropId, gltfMaterial.alphaCutoff);
#if USING_HDRP_10_OR_NEWER || USING_URP_12_OR_NEWER
            material.EnableKeyword(KW_ALPHATEST_ON);
            material.SetOverrideTag(TAG_RENDER_TYPE, TAG_RENDER_TYPE_CUTOUT);
            material.SetFloat(k_ZTestGBufferPropId, (int)CompareFunction.Equal); //3
#endif
        }
Beispiel #24
0
 public static void SetAlphaModeBlend(UnityEngine.Material material)
 {
     material.SetFloat(modePropId, (int)StandardShaderMode.Transparent);
     material.SetFloat(dstBlendPropId, 10);
     material.SetOverrideTag("RenderType", "Transparent");
     material.DisableKeyword("_ALPHATEST_ON");
     material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
     material.renderQueue = 3000;
 }
Beispiel #25
0
        private static void ApplyBlendMode(UnityEngine.Material unityMaterial, BlendMode blendMode)
        {
            switch (blendMode)
            {
            case BlendMode.Opaque:
                unityMaterial.SetFloat(Mode, 0);
                unityMaterial.SetInt(SrcBlend, (int)UnityEngine.Rendering.BlendMode.One);
                unityMaterial.SetInt(DstBlend, (int)UnityEngine.Rendering.BlendMode.Zero);
                unityMaterial.SetInt(ZWrite, 1);
                unityMaterial.DisableKeyword("_ALPHATEST_ON");
                unityMaterial.DisableKeyword("_ALPHABLEND_ON");
                unityMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                unityMaterial.renderQueue = -1;
                break;

            case BlendMode.Cutout:
                unityMaterial.SetFloat(Mode, 1);
                unityMaterial.SetInt(SrcBlend, (int)UnityEngine.Rendering.BlendMode.One);
                unityMaterial.SetInt(DstBlend, (int)UnityEngine.Rendering.BlendMode.Zero);
                unityMaterial.SetInt(ZWrite, 1);
                unityMaterial.EnableKeyword("_ALPHATEST_ON");
                unityMaterial.DisableKeyword("_ALPHABLEND_ON");
                unityMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                unityMaterial.renderQueue = 2450;
                break;

            case BlendMode.Translucent:
                unityMaterial.SetFloat(Mode, 3);
                unityMaterial.SetInt(SrcBlend, (int)UnityEngine.Rendering.BlendMode.One);
                unityMaterial.SetInt(DstBlend, (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                //!!!!!!! this is normally switched off but somehow enabling it seems to resolve so many issues.. keep an eye out for weirld opacity issues
                //unityMaterial.SetInt("_ZWrite", 0);
                unityMaterial.SetInt(ZWrite, 1);
                unityMaterial.DisableKeyword("_ALPHATEST_ON");
                unityMaterial.DisableKeyword("_ALPHABLEND_ON");
                unityMaterial.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                unityMaterial.renderQueue = 3000;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #26
0
 public void EnsureKeyword(Material material, string name, bool enabled)
 {
     if (enabled != material.IsKeywordEnabled(name))
     {
         if (enabled)
             material.EnableKeyword(name);
         else
             material.DisableKeyword(name);
     }
 }
 private void setMaterialToFade(Material m)
 {
     m.SetFloat("_Mode", 2);
     m.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
     m.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
     m.SetInt("_ZWrite", 0);
     m.DisableKeyword("_ALPHATEST_ON");
     m.EnableKeyword("_ALPHABLEND_ON");
     m.DisableKeyword("_ALPHAPREMULTIPLY_ON");
     m.renderQueue = 3000;
 }
 protected void SetKeywordState(UnityEngine.Material material, string keyword, bool activate)
 {
     if (activate)
     {
         material.EnableKeyword(keyword);
     }
     else
     {
         material.DisableKeyword(keyword);
     }
 }
Beispiel #29
0
 void Transparent(Material material)
 {
     material.SetFloat("_Mode", 3);
     material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
     material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
     material.SetInt("_ZWrite", 0);
     material.DisableKeyword("_ALPHATEST_ON");
     material.DisableKeyword("_ALPHABLEND_ON");
     material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
     material.renderQueue = 3000;
 }
 public static void SetTransparent(Material material)
 {
     material.SetOverrideTag("RenderType", "Transparent");
     material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
     material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
     material.SetInt("_ZWrite", 0);
     material.DisableKeyword("_ALPHATEST_ON");
     material.DisableKeyword("_ALPHABLEND_ON");
     material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
     material.renderQueue = 3000;
 }
Beispiel #31
0
 /// <summary>
 /// sets rendering mode of 'material' to transparent
 /// </summary>
 public static void MakeMaterialTransparent(UnityEngine.Material material)
 {
     material.SetFloat("_Mode", 2);
     material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
     material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
     material.SetInt("_ZWrite", 0);
     material.DisableKeyword("_ALPHATEST_ON");
     material.EnableKeyword("_ALPHABLEND_ON");
     material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
     material.renderQueue = 3000;
 }
        static void TrySetTextureTransform(
            Schema.TextureInfo textureInfo,
            UnityEngine.Material material,
            int propertyId,
            bool flipY = false
            )
        {
            Vector2 offset = Vector2.zero;
            Vector2 scale  = Vector2.one;

            if (textureInfo.extensions != null && textureInfo.extensions.KHR_texture_transform != null)
            {
                var tt = textureInfo.extensions.KHR_texture_transform;
                if (tt.texCoord != 0)
                {
                    Debug.LogError("Multiple UV sets are not supported!");
                }

                float cos = 1;
                float sin = 0;

                if (tt.offset != null)
                {
                    offset.x = tt.offset[0];
                    offset.y = 1 - tt.offset[1];
                }
                if (tt.scale != null)
                {
                    scale.x = tt.scale[0];
                    scale.y = tt.scale[1];
                    material.SetTextureScale(propertyId, scale);
                }
                if (tt.rotation != 0)
                {
                    cos = Mathf.Cos(tt.rotation);
                    sin = Mathf.Sin(tt.rotation);
                    material.SetVector(StandardShaderHelper.mainTexRotatePropId, new Vector4(cos, sin, -sin, cos));
                    material.EnableKeyword(StandardShaderHelper.KW_UV_ROTATION);
                    offset.x += scale.y * sin;
                }
                offset.y -= scale.y * cos;
                material.SetTextureOffset(propertyId, offset);
            }

            if (flipY)
            {
                offset.y = 1 - offset.y;
                scale.y  = -scale.y;
            }

            material.SetTextureOffset(propertyId, offset);
            material.SetTextureScale(propertyId, scale);
        }
Beispiel #33
0
 protected void SetKeyword(UnityEngine.Material material, bool b, int keywordIndex)
 {
     if (b && _keywords != null && _keywords.Length > keywordIndex && _keywords.Length > 0)
     {
         CleanKeywords(material);
         material.EnableKeyword(_keywords[keywordIndex]);
     }
     else
     {
         CleanKeywords(material);
     }
 }
 public static void SetAlphaModeBlend(UnityEngine.Material material)
 {
     material.SetFloat(modePropId, (int)StandardShaderMode.Transparent);
     material.SetOverrideTag("RenderType", "Transparent");
     material.SetInt(srcBlendPropId, (int)UnityEngine.Rendering.BlendMode.SrcAlpha);         //5
     material.SetInt(dstBlendPropId, (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); //10
     material.SetInt(zWritePropId, 0);
     material.DisableKeyword("_ALPHATEST_ON");
     material.EnableKeyword("_ALPHABLEND_ON");
     material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
     material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;  //3000
 }
Beispiel #35
0
 void Start()
 {
     Material m = new Material(Shader.Find("Custom/StandardDepthBuffer"));
     m.SetFloat("_Mode", 2);
     m.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
     m.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
     m.SetInt("_ZWrite", 0);
     m.DisableKeyword("_ALPHATEST_ON");
     m.EnableKeyword("_ALPHABLEND_ON");
     m.DisableKeyword("_ALPHAPREMULTIPLY_ON");
     m.renderQueue = 3000;
 }
 public static void SetAlphaModeMask(UnityEngine.Material material, Schema.Material gltfMaterial)
 {
     material.SetFloat(modePropId, (int)StandardShaderMode.Cutout);
     material.SetOverrideTag("RenderType", "TransparentCutout");
     material.SetInt(srcBlendPropId, (int)UnityEngine.Rendering.BlendMode.One);
     material.SetInt(dstBlendPropId, (int)UnityEngine.Rendering.BlendMode.Zero);
     material.SetInt(zWritePropId, 1);
     material.EnableKeyword("_ALPHATEST_ON");
     material.DisableKeyword("_ALPHABLEND_ON");
     material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
     material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;  //2450
     material.SetFloat(cutoffPropId, gltfMaterial.alphaCutoff);
 }
 void ApplyTransparent(Color col)
 {
     rend = this.gameObject.GetComponent<Renderer>().material;
     rend.SetFloat("_Mode", 3f);
     rend.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
     rend.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
     rend.SetInt("_ZWrite", 0);
     rend.DisableKeyword("_ALPHATEST_ON");
     rend.DisableKeyword("_ALPHABLEND_ON");
     rend.EnableKeyword("_ALPHAPREMULTIPLY_ON");
     rend.renderQueue = 3000;
     StartCoroutine(colorLerp1(rend.GetColor("_Color"), col));
 }
 Material CreateMaterial(Color emissionColor)
 {
     Material m = new Material(outlineBufferShader);
     m.SetColor("_Color", emissionColor);
     m.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
     m.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
     m.SetInt("_ZWrite", 0);
     m.DisableKeyword("_ALPHATEST_ON");
     m.EnableKeyword("_ALPHABLEND_ON");
     m.DisableKeyword("_ALPHAPREMULTIPLY_ON");
     m.renderQueue = 3000;
     return m;
 }
Beispiel #39
0
 static public int EnableKeyword(IntPtr l)
 {
     try {
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         System.String        a1;
         checkType(l, 2, out a1);
         self.EnableKeyword(a1);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
    private void SetCloudQuality(Material material)
    {
        switch (CloudQuality)
        {
            case TOD_CloudQualityType.Fastest:
                material.EnableKeyword("FASTEST");
                material.DisableKeyword("DENSITY");
                material.DisableKeyword("BUMPED");
                break;

            case TOD_CloudQualityType.Density:
                material.DisableKeyword("FASTEST");
                material.EnableKeyword("DENSITY");
                material.DisableKeyword("BUMPED");
                break;

            case TOD_CloudQualityType.Bumped:
                material.DisableKeyword("FASTEST");
                material.DisableKeyword("DENSITY");
                material.EnableKeyword("BUMPED");
                break;
        }
    }
 static public int EnableKeyword(IntPtr l)
 {
     try {
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         System.String        a1;
         checkType(l, 2, out a1);
         self.EnableKeyword(a1);
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Beispiel #42
0
    public Body(double m, float r, float x, float y, float z, string id, Color color = default(Color))
    {
        mass          = m;
        radius        = 10 * r;
        volume        = (4 / 3) * pi * (r * r * r);
        density       = mass / volume;
        xPos          = x;
        yPos          = y;
        zPos          = z;
        accelerationX = 0;
        accelerationY = 0;
        accelerationZ = 0;
        ID            = id;

        appearance = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        appearance.transform.position   = new Vector3(xPos / 100, yPos / 100, zPos / 100);
        appearance.transform.localScale = new Vector3((10 * 2 * r) / 100, (10 * 2 * r) / 100, (10 * 2 * r) / 100);
        rigidBody = appearance.AddComponent <Rigidbody>();
        rigidBody.detectCollisions = false;

        trail      = appearance.AddComponent <TrailRenderer>();
        trail.time = 5;
        trail.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
        trail.receiveShadows    = false;
        trail.widthMultiplier   = 5;

        UnityEngine.Material mat = new UnityEngine.Material(Shader.Find("Standard"));
        if (color == default(Color))
        {
            color  = Color.gray;
            isStar = 0;
        }
        else
        {
            isStar = 1;
            mat.EnableKeyword("_EMISSION");
            mat.SetColor("_EmissionColor", new Color(255, 187, 0));
            //mat.EnableKeyword("_EMISSION");
            //mat.SetColor("_EmissionColor", new Color(255, 187, 0));
        }
        mat.color = color;
        appearance.GetComponent <Renderer>().material = mat;

        //Apply texture

        /*UnityEngine.Material mater = Earth;
         * mater.EnableKeyword("_EMISSION");
         * mater.SetColor("_EmissionColor", new Color(255, 187, 0));
         * appearance.GetComponent<Renderer>().material = mater;*/
    }
 static int EnableKeyword(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 2);
         UnityEngine.Material obj = (UnityEngine.Material)ToLua.CheckObject(L, 1, typeof(UnityEngine.Material));
         string arg0 = ToLua.CheckString(L, 2);
         obj.EnableKeyword(arg0);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
        public static Material GetMaterial(ObjectType objectType, RenderMode renderMode, BlendMode blendMode)
        {
            if (blendMode == BlendMode.Normal)
            {
                if (objectType == ObjectType.MeshDefault)
                {
                    var mat = new Material(Shader.Find("Diffuse"));
                    mat.hideFlags = HideFlags.HideAndDontSave;
                    return mat;
                }
                else if (objectType == ObjectType.SpriteDefault)
                {
                    var mat = new Material(Shader.Find("Sprites/Default"));
                    mat.hideFlags = HideFlags.HideAndDontSave;
                    return mat;
                }
                else if (objectType == ObjectType.ParticleDefault)
                {
                    var mat = new Material(Shader.Find("Particles/Additive"));
                    mat.hideFlags = HideFlags.HideAndDontSave;
                    return mat;
                }
                else return null;
            }

            // Framebuffer won't work in the editor, so fallback to Grab mode.
            if (Application.isEditor && renderMode == RenderMode.Framebuffer) renderMode = RenderMode.Grab;

            // Disable caching for mesh and particle materials, as they are sharing them.
            if (objectType != ObjectType.MeshDefault && objectType != ObjectType.ParticleDefault &&
                cachedMaterials.ContainsKey(objectType) &&
                cachedMaterials[objectType].ContainsKey(renderMode) &&
                cachedMaterials[objectType][renderMode].ContainsKey(blendMode))
                return cachedMaterials[objectType][renderMode][blendMode];
            else
            {
                var mat = new Material(Resources.Load<Shader>(string.Format("BlendModes/{0}/{1}", objectType, renderMode)));
                mat.hideFlags = HideFlags.HideAndDontSave;
                mat.EnableKeyword("BM" + blendMode.ToString());

                if (!cachedMaterials.ContainsKey(objectType)) cachedMaterials.Add(objectType, new Dictionary<RenderMode, Dictionary<BlendMode, Material>>());
                if (!cachedMaterials[objectType].ContainsKey(renderMode)) cachedMaterials[objectType].Add(renderMode, new Dictionary<BlendMode, Material>());
                if (!cachedMaterials[objectType][renderMode].ContainsKey(blendMode)) cachedMaterials[objectType][renderMode].Add(blendMode, mat);

                return mat;
            }
        }
    private void Start()
    {
        theLight = GetComponent<Light>();
        mRend = GetComponent<MeshRenderer>();

        normalMaterial = mRend.material;
        normalMaterial.EnableKeyword("_EMISSION");

        _currentColor = normalMaterial.GetColor("_Color");
        //print (_currentColor);
        _newColor.w = 2.0f;

        theLight.range = initialRange;
        theLight.color = _currentColor;

        aSource = transform.parent.GetComponent<AudioSource>();
    }
    private void Start()
    {
        mRend = GetComponent<MeshRenderer>();

        cController = GetComponent<CharacterController>();
        cam = Camera.main;
        atSurface = false;
        defaultScale = transform.localScale;

        normalMaterial = mRend.material;
        normalMaterial.EnableKeyword("_EMISSION");

        _initialColor = normalMaterial.color;
        _currentColor = normalMaterial.GetColor("_Color");

        //if (GameManager.Instance.player != null && GameManager.Instance.follow != null)
            //Physics.IgnoreCollision(GameManager.Instance.playerCollider, GameManager.Instance.followCollider);
    }
Beispiel #47
0
        public static void SetTransparent(Material material, Color? newcolor = null)
        {
            material.SetOverrideTag("RenderType", "Transparent");
            material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
            material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
            material.SetInt("_ZWrite", 0);
            material.DisableKeyword("_ALPHATEST_ON");
            material.DisableKeyword("_ALPHABLEND_ON");
            material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
            material.SetFloat("_Metallic", 0f);
            material.SetFloat("_Glossiness", 0f);
            material.renderQueue = 3000;
            material.mainTexture = null;

            if (newcolor != null)
            {
                material.color = newcolor.Value;
            }
        }
Beispiel #48
0
 void OnCollisionEnter(Collision coll)
 {
     switch (coll.gameObject.tag) {
     case "DestroyPlayerOnImpact":
         this.gameObject.GetComponent<PlayerPowerUpController> ().DeactivatePowerUp (null);
         DeathController.KillPlayer (this.gameObject, DeathController.DeathCause.Lava);
         break;
     case "Bouncy":
         bouncyForce = rb.mass * 275.0F;
         bounceVector = new Vector3 (0, bouncyForce, 0);
         rb.AddForce (bounceVector);
         currBouncePadMat = coll.gameObject.GetComponent<MeshRenderer>().material;
         currBouncePadMat.EnableKeyword("_EMISSION");
         timePassed = 0.0f;
         bouncePadMatActive = true;
         break;
     case "Icey":
         pc.OnIce ();
         break;
     }
 }
    public static UnityEngine.Material ToUnityMaterial(this Elements.Material material)
    {
        var uMaterial = new UnityEngine.Material(Shader.Find("Standard"));

        uMaterial.name  = material.Name;
        uMaterial.color = material.Color.ToUnityColor();
        uMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
        if (material.Color.Alpha < 1.0f)
        {
            uMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
            uMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
            uMaterial.SetInt("_ZWrite", 0);
            uMaterial.DisableKeyword("_ALPHATEST_ON");
            uMaterial.DisableKeyword("_ALPHABLEND_ON");
            uMaterial.EnableKeyword("_ALPHAPREMULTIPLY_ON");
            uMaterial.SetFloat("_Glossiness", material.GlossinessFactor);
            // uMaterial.SetFloat("_Metallic", material.SpecularFactor);
            uMaterial.renderQueue = 3000;
        }

        return(uMaterial);
    }
Beispiel #50
0
	private void Init()
	{
		switch (algo) 
		{
			case Algo.NAIVE: m_Shader = Shader.Find ("hidden/naive_gaussian_blur");break;
			case Algo.TWO_PASS: m_Shader = Shader.Find ("hidden/two_pass_gaussian_blur");break;
			case Algo.TWO_PASS_LINEAR_SAMPLING: m_Shader = Shader.Find ("hidden/two_pass_linear_sampling_gaussian_blur");break;
		}
		if (m_Shader.isSupported == false)
		{
			enabled = false;
			Debug.LogWarning ("Shader not supported");
			return;
		}
		if (algo == Algo.NAIVE && quality == Quality.BIG_KERNEL) 
		{
			quality = Quality.MEDIUM_KERNEL;
			Debug.LogWarning("Some graphic's driver crash with Algo.NAIVE and Quality.BIG_KERNEL !");
		}
		m_Material = new Material (m_Shader);
		m_Material.EnableKeyword (quality.ToString ());
	}
Beispiel #51
0
        public static void SetTransparent(Material material, Color? newcolor = null)
        {
            if (material.shader != StandardShader)
                Debug.LogWarning("Trying to set transparent mode on non-standard shader. Please use the Standard Shader instead or modify this method.");

            material.SetOverrideTag("RenderType", "Transparent");
            material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
            material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
            material.SetInt("_ZWrite", 0);
            material.DisableKeyword("_ALPHATEST_ON");
            material.DisableKeyword("_ALPHABLEND_ON");
            material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
            material.SetFloat("_Metallic", 0f);
            material.SetFloat("_Glossiness", 0f);
            material.renderQueue = 3000;
            material.mainTexture = null;

            if (newcolor != null)
            {
                material.color = newcolor.Value;
            }
        }
        /// <summary>
        /// Apply all the Properties Collection to the Target Material by its Name/Id.
        /// This method is only used by this base class to generate the Materials for the Cache
        /// </summary>
        /// <param name="PropCollection">Our source helper Prop Collection Dictionary.</param>
        /// <param name="CollectionName">Set the Collection by its Name/Id.</param>
        /// <param name="Target">Target material.</param>
        private void SetProperties(Dictionary<string, PropertiesCollection> PropCollection, string CollectionName, Material Target)
        {
            //Querry the Dictionary by the CollectionId and apply all properties to the Target Material
            if (PropCollection.ContainsKey(CollectionName))
            {
                //Apply all Textures
                foreach (var tex in PropCollection[CollectionName].Textures)
                {
                    Target.SetTexture(tex.Target.GetString(), tex.Value);
                }

                //Apply all Float Values
                foreach (var val in PropCollection[CollectionName].Floats)
                {
                    Target.SetFloat(val.Target.GetString(), val.Value);
                }

                //Apply all Color tints
                foreach (var tints in PropCollection[CollectionName].Tints)
                {
                    Target.SetColor(tints.Target.GetString(), tints.Value);
                }

                //Apply for all Shader Features
                foreach (var feature in PropCollection[CollectionName].Features)
                {
                    if (feature.Value)
                        Target.EnableKeyword(feature.Target.GetString());
                    else
                        Target.DisableKeyword(feature.Target.GetString());
                }
            }
            else
            {
                Debug.LogError("There is no matching Id on this Collection");
            }
        }
        public UnityEngine.Material CreateMaterial(PbrMaterial vpxMaterial, TableBehavior table, StringBuilder debug = null)
        {
            var unityMaterial = new UnityEngine.Material(GetShader())
            {
                name = vpxMaterial.Id
            };

            // apply some basic manipulations to the color. this just makes very
            // very white colors be clipped to 0.8204 aka 204/255 is 0.8
            // this is to give room to lighting values. so there is more modulation
            // of brighter colors when being lit without blow outs too soon.
            var col = vpxMaterial.Color.ToUnityColor();

            if (vpxMaterial.Color.IsGray() && col.grayscale > 0.8)
            {
                debug?.AppendLine("Color manipulation performed, brightness reduced.");
                col.r = col.g = col.b = 0.8f;
            }

            // alpha for color depending on blend mode
            ApplyBlendMode(unityMaterial, vpxMaterial.MapBlendMode);
            if (vpxMaterial.MapBlendMode == Engine.VPT.BlendMode.Translucent)
            {
                col.a = Mathf.Min(1, Mathf.Max(0, vpxMaterial.Opacity));
            }
            unityMaterial.SetColor(BaseColor, col);

            // validate IsMetal. if true, set the metallic value.
            // found VPX authors setting metallic as well as translucent at the
            // same time, which does not render correctly in unity so we have
            // to check if this value is true and also if opacity <= 1.
            if (vpxMaterial.IsMetal && (!vpxMaterial.IsOpacityActive || vpxMaterial.Opacity >= 1))
            {
                unityMaterial.SetFloat(Metallic, 1f);
                debug?.AppendLine("Metallic set to 1.");
            }

            // roughness / glossiness
            unityMaterial.SetFloat(Smoothness, vpxMaterial.Roughness);

            // map
            if (table != null && vpxMaterial.HasMap)
            {
                unityMaterial.SetTexture(BaseColorMap, table.GetTexture(vpxMaterial.Map.Name));
            }

            // normal map
            if (table != null && vpxMaterial.HasNormalMap)
            {
                unityMaterial.EnableKeyword("_NORMALMAP");
                unityMaterial.EnableKeyword("_NORMALMAP_TANGENT_SPACE");

                unityMaterial.SetInt(NormalMapSpace, 0);                 // 0 = TangentSpace, 1 = ObjectSpace
                unityMaterial.SetFloat(NormalScale, 0f);                 // TODO FIXME: setting the scale to 0 for now. anything above 0 makes the entire unity editor window become black which is more likely a unity bug

                unityMaterial.SetTexture(NormalMap, table.GetTexture(vpxMaterial.NormalMap.Name));
            }

            // GI hack. This is a necessary step, see respective code in BaseUnlitGUI.cs of the HDRP source
            SetupMainTexForAlphaTestGI(unityMaterial, "_BaseColorMap", "_BaseColor");

            return(unityMaterial);
        }
        protected virtual MaterialCacheData CreateMaterial(GLTF.Schema.Material def, int materialIndex)
        {
            MaterialCacheData materialWrapper = null;

            if (materialIndex < 0 || _assetCache.MaterialCache[materialIndex] == null)
            {
                Shader shader;

                // get the shader to use for this material
                try
                {
                    if (_root.ExtensionsUsed != null && _root.ExtensionsUsed.Contains("KHR_materials_pbrSpecularGlossiness"))
                    {
                        shader = _shaderCache[MaterialType.KHR_materials_pbrSpecularGlossiness];
                    }
                    else if (def.PbrMetallicRoughness != null)
                    {
                        shader = _shaderCache[MaterialType.PbrMetallicRoughness];
                    }
                    else if (_root.ExtensionsUsed != null && _root.ExtensionsUsed.Contains("KHR_materials_common") &&
                             def.CommonConstant != null)
                    {
                        shader = _shaderCache[MaterialType.CommonConstant];
                    }
                    else
                    {
                        shader = _shaderCache[MaterialType.PbrMetallicRoughness];
                    }
                }
                catch (KeyNotFoundException)
                {
                    Debug.LogWarningFormat("No shader supplied for type of glTF material {0}, using Standard fallback", def.Name);
                    shader = Shader.Find("Standard");
                }

                shader.maximumLOD = MaximumLod;

                var material = new UnityEngine.Material(shader);

                if (def.AlphaMode == AlphaMode.MASK)
                {
                    material.SetOverrideTag("RenderType", "TransparentCutout");
                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    material.SetInt("_ZWrite", 1);
                    material.EnableKeyword("_ALPHATEST_ON");
                    material.DisableKeyword("_ALPHABLEND_ON");
                    material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
                    material.SetFloat("_Cutoff", (float)def.AlphaCutoff);
                }
                else if (def.AlphaMode == AlphaMode.BLEND)
                {
                    material.SetOverrideTag("RenderType", "Transparent");
                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                    material.SetInt("_ZWrite", 0);
                    material.DisableKeyword("_ALPHATEST_ON");
                    material.EnableKeyword("_ALPHABLEND_ON");
                    material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
                }
                else
                {
                    material.SetOverrideTag("RenderType", "Opaque");
                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    material.SetInt("_ZWrite", 1);
                    material.DisableKeyword("_ALPHATEST_ON");
                    material.DisableKeyword("_ALPHABLEND_ON");
                    material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    material.renderQueue = -1;
                }

                if (def.DoubleSided)
                {
                    material.SetInt("_Cull", (int)CullMode.Off);
                }
                else
                {
                    material.SetInt("_Cull", (int)CullMode.Back);
                }

                if (def.PbrMetallicRoughness != null)
                {
                    var pbr = def.PbrMetallicRoughness;

                    material.SetColor("_Color", pbr.BaseColorFactor.ToUnityColor());

                    if (pbr.BaseColorTexture != null)
                    {
                        var textureDef = pbr.BaseColorTexture.Index.Value;
                        material.SetTexture("_MainTex", CreateTexture(textureDef));

                        ApplyTextureTransform(pbr.BaseColorTexture, material, "_MainTex");
                    }

                    material.SetFloat("_Metallic", (float)pbr.MetallicFactor);

                    if (pbr.MetallicRoughnessTexture != null)
                    {
                        var texture = pbr.MetallicRoughnessTexture.Index.Value;
                        material.SetTexture("_MetallicRoughnessMap", CreateTexture(texture));

                        ApplyTextureTransform(pbr.MetallicRoughnessTexture, material, "_MetallicRoughnessMap");
                    }

                    material.SetFloat("_Roughness", (float)pbr.RoughnessFactor);
                }

                if (_root.ExtensionsUsed != null && _root.ExtensionsUsed.Contains(KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME))
                {
                    KHR_materials_pbrSpecularGlossinessExtension specGloss = def.Extensions[KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME] as KHR_materials_pbrSpecularGlossinessExtension;

                    if (specGloss.DiffuseTexture != null)
                    {
                        var texture = specGloss.DiffuseTexture.Index.Value;
                        material.SetTexture("_MainTex", CreateTexture(texture));

                        ApplyTextureTransform(specGloss.DiffuseTexture, material, "_MainTex");
                    }
                    else
                    {
                        material.SetColor("_Color", specGloss.DiffuseFactor.ToUnityColor());
                    }

                    if (specGloss.SpecularGlossinessTexture != null)
                    {
                        var texture = specGloss.SpecularGlossinessTexture.Index.Value;
                        material.SetTexture("_SpecGlossMap", CreateTexture(texture));
                        material.EnableKeyword("_SPECGLOSSMAP");

                        ApplyTextureTransform(specGloss.SpecularGlossinessTexture, material, "_SpecGlossMap");
                    }
                    else
                    {
                        material.SetVector("_SpecColor", specGloss.SpecularFactor.ToUnityVector3());
                        material.SetFloat("_Glossiness", (float)specGloss.GlossinessFactor);
                    }
                }

                if (def.CommonConstant != null)
                {
                    material.SetColor("_AmbientFactor", def.CommonConstant.AmbientFactor.ToUnityColor());

                    if (def.CommonConstant.LightmapTexture != null)
                    {
                        material.EnableKeyword("LIGHTMAP_ON");

                        var texture = def.CommonConstant.LightmapTexture.Index.Value;
                        material.SetTexture("_LightMap", CreateTexture(texture));
                        material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord);

                        ApplyTextureTransform(def.CommonConstant.LightmapTexture, material, "_LightMap");
                    }

                    material.SetColor("_LightFactor", def.CommonConstant.LightmapFactor.ToUnityColor());
                }

                if (def.NormalTexture != null)
                {
                    var texture = def.NormalTexture.Index.Value;
                    material.SetTexture("_BumpMap", CreateTexture(texture));
                    material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale);
                    material.EnableKeyword("_NORMALMAP");

                    ApplyTextureTransform(def.NormalTexture, material, "_BumpMap");
                }

                if (def.OcclusionTexture != null)
                {
                    var texture = def.OcclusionTexture.Index;

                    material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);

                    if (def.PbrMetallicRoughness != null &&
                        def.PbrMetallicRoughness.MetallicRoughnessTexture != null &&
                        def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == texture.Id)
                    {
                        material.EnableKeyword("OCC_METAL_ROUGH_ON");
                    }
                    else
                    {
                        material.SetTexture("_OcclusionMap", CreateTexture(texture.Value));

                        ApplyTextureTransform(def.OcclusionTexture, material, "_OcclusionMap");
                    }
                }

                if (def.EmissiveTexture != null)
                {
                    var texture = def.EmissiveTexture.Index.Value;
                    material.EnableKeyword("EMISSION_MAP_ON");
                    material.EnableKeyword("_EMISSION");
                    material.SetTexture("_EmissionMap", CreateTexture(texture));
                    material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord);

                    ApplyTextureTransform(def.EmissiveTexture, material, "_EmissionMap");
                }

                material.SetColor("_EmissionColor", def.EmissiveFactor.ToUnityColor());

                materialWrapper = new MaterialCacheData
                {
                    UnityMaterial = material,
                    UnityMaterialWithVertexColor = new UnityEngine.Material(material),
                    GLTFMaterial = def
                };

                materialWrapper.UnityMaterialWithVertexColor.EnableKeyword("VERTEX_COLOR_ON");

                if (materialIndex > 0)
                {
                    _assetCache.MaterialCache[materialIndex] = materialWrapper;
                }
            }

            return(materialIndex > 0 ? _assetCache.MaterialCache[materialIndex] : materialWrapper);
        }
Beispiel #55
0
		//material
		public static void EnableBlending(Material mat, bool enable) {
			if(!internalBlendingSupport) return;
			if(enable) {
				mat.EnableKeyword("MARMO_SKY_BLEND_ON");
				mat.DisableKeyword("MARMO_SKY_BLEND_OFF");
			} else {
				mat.DisableKeyword("MARMO_SKY_BLEND_ON");
				mat.EnableKeyword("MARMO_SKY_BLEND_OFF");
			}
		}
        protected virtual void CreateUnityMaterial(GLTF.Schema.Material def, int materialIndex)
        {
            Extension specularGlossinessExtension = null;
            bool      isSpecularPBR = def.Extensions != null && def.Extensions.TryGetValue("KHR_materials_pbrSpecularGlossiness", out specularGlossinessExtension);

            Shader shader = isSpecularPBR ? Shader.Find("Standard (Specular setup)") : Shader.Find("Standard");

            var material = new UnityEngine.Material(shader);

            material.hideFlags = HideFlags.DontUnloadUnusedAsset;             // Avoid material to be deleted while being built
            material.name      = def.Name;

            //Transparency
            if (def.AlphaMode == AlphaMode.MASK)
            {
                GLTFUtils.SetupMaterialWithBlendMode(material, GLTFUtils.BlendMode.Cutout);
                material.SetFloat("_Mode", 1);
                material.SetFloat("_Cutoff", (float)def.AlphaCutoff);
            }
            else if (def.AlphaMode == AlphaMode.BLEND)
            {
                GLTFUtils.SetupMaterialWithBlendMode(material, GLTFUtils.BlendMode.Fade);
                material.SetFloat("_Mode", 3);
            }

            if (def.NormalTexture != null)
            {
                var       texture       = def.NormalTexture.Index.Id;
                Texture2D normalTexture = getTexture(texture) as Texture2D;

                //Automatically set it to normal map
                TextureImporter im = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(normalTexture)) as TextureImporter;
                im.textureType = TextureImporterType.NormalMap;
                im.SaveAndReimport();
                material.SetTexture("_BumpMap", getTexture(texture));
                material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale);
            }

            if (def.EmissiveTexture != null)
            {
                material.EnableKeyword("EMISSION_MAP_ON");
                var texture = def.EmissiveTexture.Index.Id;
                material.SetTexture("_EmissionMap", getTexture(texture));
                material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord);
            }

            // PBR channels
            if (specularGlossinessExtension != null)
            {
                KHR_materials_pbrSpecularGlossinessExtension pbr = (KHR_materials_pbrSpecularGlossinessExtension)specularGlossinessExtension;
                material.SetColor("_Color", pbr.DiffuseFactor.ToUnityColor().gamma);
                if (pbr.DiffuseTexture != null)
                {
                    var texture = pbr.DiffuseTexture.Index.Id;
                    material.SetTexture("_MainTex", getTexture(texture));
                }

                if (pbr.SpecularGlossinessTexture != null)
                {
                    var texture = pbr.SpecularGlossinessTexture.Index.Id;
                    material.SetTexture("_SpecGlossMap", getTexture(texture));
                    material.SetFloat("_GlossMapScale", (float)pbr.GlossinessFactor);
                    material.SetFloat("_Glossiness", (float)pbr.GlossinessFactor);
                }
                else
                {
                    material.SetFloat("_Glossiness", (float)pbr.GlossinessFactor);
                }

                Vector3 specularVec3 = pbr.SpecularFactor.ToUnityVector3();
                material.SetColor("_SpecColor", new Color(specularVec3.x, specularVec3.y, specularVec3.z, 1.0f));

                if (def.OcclusionTexture != null)
                {
                    var texture = def.OcclusionTexture.Index.Id;
                    material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);
                    material.SetTexture("_OcclusionMap", getTexture(texture));
                }

                GLTFUtils.SetMaterialKeywords(material, GLTFUtils.WorkflowMode.Specular);
            }
            else if (def.PbrMetallicRoughness != null)
            {
                var pbr = def.PbrMetallicRoughness;

                material.SetColor("_Color", pbr.BaseColorFactor.ToUnityColor().gamma);
                if (pbr.BaseColorTexture != null)
                {
                    var texture = pbr.BaseColorTexture.Index.Id;
                    material.SetTexture("_MainTex", getTexture(texture));
                }

                material.SetFloat("_Metallic", (float)pbr.MetallicFactor);
                material.SetFloat("_Glossiness", 1.0f - (float)pbr.RoughnessFactor);

                if (pbr.MetallicRoughnessTexture != null)
                {
                    var texture = pbr.MetallicRoughnessTexture.Index.Id;
                    UnityEngine.Texture2D inputTexture  = getTexture(texture) as Texture2D;
                    List <Texture2D>      splitTextures = splitMetalRoughTexture(inputTexture, def.OcclusionTexture != null, (float)pbr.MetallicFactor, (float)pbr.RoughnessFactor);
                    material.SetTexture("_MetallicGlossMap", splitTextures[0]);

                    if (def.OcclusionTexture != null)
                    {
                        material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);
                        material.SetTexture("_OcclusionMap", splitTextures[1]);
                    }
                }

                GLTFUtils.SetMaterialKeywords(material, GLTFUtils.WorkflowMode.Metallic);
            }

            material.SetColor("_EmissionColor", def.EmissiveFactor.ToUnityColor().gamma);
            material = _assetManager.saveMaterial(material, materialIndex);
            _assetManager._parsedMaterials.Add(material);
            material.hideFlags = HideFlags.None;
        }
        private UnityEngine.Material CreateMaterial(Material def, bool useVertexColors)
        {
            UnityEngine.Material material = new UnityEngine.Material(useVertexColors ? ColorMaterial : NoColorMaterial);

            material.shader.maximumLOD = MaximumLod;

            if (def.AlphaMode == AlphaMode.MASK)
            {
                material.SetOverrideTag("RenderType", "TransparentCutout");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.EnableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
                material.SetFloat("_Cutoff", (float)def.AlphaCutoff);
            }
            else if (def.AlphaMode == AlphaMode.BLEND)
            {
                material.SetOverrideTag("RenderType", "Transparent");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.DisableKeyword("_ALPHATEST_ON");
                material.EnableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
            }
            else
            {
                material.SetOverrideTag("RenderType", "Opaque");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = -1;
            }

            if (def.DoubleSided)
            {
                material.SetInt("_Cull", (int)CullMode.Off);
            }
            else
            {
                material.SetInt("_Cull", (int)CullMode.Back);
            }

            if (useVertexColors)
            {
                material.EnableKeyword("VERTEX_COLOR_ON");
            }

            if (def.PbrMetallicRoughness != null)
            {
                var pbr = def.PbrMetallicRoughness;

                material.SetColor("_Color", pbr.BaseColorFactor);

                if (pbr.BaseColorTexture != null)
                {
                    var texture = pbr.BaseColorTexture.Index.Value;
                    material.SetTexture("_MainTex", _imageCache[texture.Source.Value]);
                }

                material.SetFloat("_Metallic", (float)pbr.MetallicFactor);

                if (pbr.MetallicRoughnessTexture != null)
                {
                    var texture = pbr.MetallicRoughnessTexture.Index.Value;
                    material.SetTexture("_MetallicRoughnessMap", _imageCache[texture.Source.Value]);
                }

                material.SetFloat("_Roughness", (float)pbr.RoughnessFactor);
            }

            if (def.CommonConstant != null)
            {
                material.SetColor("_AmbientFactor", def.CommonConstant.AmbientFactor);

                if (def.CommonConstant.LightmapTexture != null)
                {
                    material.EnableKeyword("LIGHTMAP_ON");

                    var texture = def.CommonConstant.LightmapTexture.Index.Value;
                    material.SetTexture("_LightMap", _imageCache[texture.Source.Value]);
                    material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord);
                }

                material.SetColor("_LightFactor", def.CommonConstant.LightmapFactor);
            }

            if (def.NormalTexture != null)
            {
                var texture = def.NormalTexture.Index.Value;
                material.EnableKeyword("_NORMALMAP");
                material.SetTexture("_BumpMap", _imageCache[texture.Source.Value]);
                material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale);
            }
            else
            {
                material.SetTexture("_BumpMap", null);
                material.DisableKeyword("_NORMALMAP");
            }

            if (def.OcclusionTexture != null)
            {
                var texture = def.OcclusionTexture.Index;

                material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);

                if (def.PbrMetallicRoughness != null &&
                    def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == texture.Id)
                {
                    material.EnableKeyword("OCC_METAL_ROUGH_ON");
                }
                else
                {
                    material.SetTexture("_OcclusionMap", _imageCache[texture.Value.Source.Value]);
                }
            }

            if (def.EmissiveTexture != null)
            {
                var texture = def.EmissiveTexture.Index.Value;
                material.EnableKeyword("_EMISSION");
                material.EnableKeyword("EMISSION_MAP_ON");
                material.SetTexture("_EmissionMap", _imageCache[texture.Source.Value]);
                material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord);
            }

            material.SetColor("_EmissionColor", def.EmissiveFactor);

            return(material);
        }
        private static void ApplyBlendMode(UnityEngine.Material unityMaterial, BlendMode blendMode)
        {
            // disable shader passes
            unityMaterial.SetShaderPassEnabled("DistortionVectors", false);
            unityMaterial.SetShaderPassEnabled("MOTIONVECTORS", false);
            unityMaterial.SetShaderPassEnabled("TransparentDepthPrepass", false);
            unityMaterial.SetShaderPassEnabled("TransparentDepthPostpass", false);
            unityMaterial.SetShaderPassEnabled("TransparentBackface", false);

            // reset existing blend modes, will be enabled explicitly
            unityMaterial.DisableKeyword("_BLENDMODE_ALPHA");
            unityMaterial.DisableKeyword("_BLENDMODE_ADD");
            unityMaterial.DisableKeyword("_BLENDMODE_PRE_MULTIPLY");

            switch (blendMode)
            {
            case Engine.VPT.BlendMode.Opaque:

                // required for the blend mode
                unityMaterial.SetInt(SrcBlend, (int)UnityEngine.Rendering.BlendMode.One);
                unityMaterial.SetInt(DstBlend, (int)UnityEngine.Rendering.BlendMode.Zero);
                unityMaterial.SetInt(ZWrite, 1);

                // properties
                unityMaterial.SetFloat(SurfaceType, 0);                         // 0 = Opaque; 1 = Transparent
                unityMaterial.SetFloat(AlphaCutoffEnable, 0);

                // render queue
                unityMaterial.renderQueue = -1;

                break;

            case Engine.VPT.BlendMode.Cutout:

                // set render type
                unityMaterial.SetOverrideTag("RenderType", "TransparentCutout");

                // keywords
                unityMaterial.EnableKeyword("_ALPHATEST_ON");
                unityMaterial.EnableKeyword("_NORMALMAP_TANGENT_SPACE");

                // required for the blend mode
                unityMaterial.SetInt(SrcBlend, (int)UnityEngine.Rendering.BlendMode.One);
                unityMaterial.SetInt(DstBlend, (int)UnityEngine.Rendering.BlendMode.Zero);
                unityMaterial.SetInt(ZWrite, 1);

                // properties
                unityMaterial.SetFloat(SurfaceType, 0);                         // 0 = Opaque; 1 = Transparent
                unityMaterial.SetFloat(AlphaCutoffEnable, 1);

                unityMaterial.SetFloat(ZTestDepthEqualForOpaque, 3);
                unityMaterial.SetFloat(ZTestModeDistortion, 4);
                unityMaterial.SetFloat(ZTestGBuffer, 3);

                // render queue
                unityMaterial.renderQueue = 2450;

                break;

            case Engine.VPT.BlendMode.Translucent:

                // set render type
                unityMaterial.SetOverrideTag("RenderType", "Transparent");

                // keywords
                //unityMaterial.EnableKeyword("_ALPHATEST_ON"); // required for _AlphaCutoffEnable
                unityMaterial.EnableKeyword("_BLENDMODE_PRESERVE_SPECULAR_LIGHTING");
                unityMaterial.EnableKeyword("_BLENDMODE_PRE_MULTIPLY");
                unityMaterial.EnableKeyword("_ENABLE_FOG_ON_TRANSPARENT");
                unityMaterial.EnableKeyword("_NORMALMAP_TANGENT_SPACE");
                unityMaterial.EnableKeyword("_SURFACE_TYPE_TRANSPARENT");

                // required for the blend mode
                unityMaterial.SetInt(SrcBlend, (int)UnityEngine.Rendering.BlendMode.One);
                unityMaterial.SetInt(DstBlend, (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                unityMaterial.SetInt(ZWrite, 0);

                // properties
                unityMaterial.SetFloat(SurfaceType, 1);                       // 0 = Opaque; 1 = Transparent
                //unityMaterial.SetFloat("_AlphaCutoffEnable", 1); // enable keyword _ALPHATEST_ON if this is required
                unityMaterial.SetFloat(BlendMode, 4);                         // 0 = Alpha, 1 = Additive, 4 = PreMultiply

                // render queue
                const int transparentRenderQueueBase = 3000;
                const int transparentSortingPriority = 0;
                unityMaterial.SetInt(TransparentSortPriority, transparentSortingPriority);
                unityMaterial.renderQueue = transparentRenderQueueBase + transparentSortingPriority;

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        //
        // Start generates a USD scene procedurally, containing a single cube with a material, shader
        // and texture bound. It then inspects the cube to discover the material. A Unity material is
        // constructed and the parameters are copied in a generic way. Similarly, the texture is
        // discovered and loaded as a Unity Texture2D and bound to the material.
        //
        // Also See: https://docs.unity3d.com/Manual/MaterialsAccessingViaScript.html
        //
        void Start()
        {
            // Create a scene for this test, but could also be read from disk.
            Scene usdScene = CreateSceneWithShading();

            // Read the material and shader ID.
            var    usdMaterial = new MaterialSample();
            string shaderId;

            // ReadMaterial was designed for Unity and assumes there is one "surface" shader bound.
            if (!MaterialSample.ReadMaterial(usdScene, kCubePath, usdMaterial, out shaderId))
            {
                throw new System.Exception("Failed to read material");
            }

            // Map the shader ID to the corresponding Unity/USD shader pair.
            ShaderPair shader;

            if (shaderId == null || !m_shaderMap.TryGetValue(shaderId, out shader))
            {
                throw new System.Exception("Material had no surface bound");
            }

            //
            // Read and process the shader-specific parameters.
            //

            // UsdShade requires all connections target an attribute, but we actually want to deserialize
            // the entire prim, so we get just the prim path here.
            var shaderPath = new pxr.SdfPath(usdMaterial.surface.connectedPath).GetPrimPath();

            usdScene.Read(shaderPath, shader.usdShader);

            //
            // Construct material & process the inputs, textures, and keywords.
            //

            var mat = new UnityEngine.Material(shader.unityShader);

            // Apply material keywords.
            foreach (string keyword in usdMaterial.requiredKeywords ?? new string[0])
            {
                mat.EnableKeyword(keyword);
            }

            // Iterate over all input parameters and copy values and/or construct textures.
            foreach (var param in shader.usdShader.GetInputParameters())
            {
                if (!SetMaterialParameter(mat, param.unityName, param.value))
                {
                    throw new System.Exception("Incompatible shader data type: " + param.ToString());
                }
            }

            foreach (var param in shader.usdShader.GetInputTextures())
            {
                if (string.IsNullOrEmpty(param.connectedPath))
                {
                    // Not connected to a texture.
                    continue;
                }

                // Only 2D textures are supported in this example.
                var usdTexture = new Texture2DSample();

                // Again, we want the prim path, not the attribute path.
                var texturePath = new pxr.SdfPath(param.connectedPath).GetPrimPath();
                usdScene.Read(texturePath, usdTexture);

                // This example also only supports explicit sourceFiles, they cannot be connected.
                if (string.IsNullOrEmpty(usdTexture.sourceFile.defaultValue))
                {
                    continue;
                }

                // For details, see: https://docs.unity3d.com/Manual/MaterialsAccessingViaScript.html
                foreach (string keyword in param.requiredShaderKeywords)
                {
                    mat.EnableKeyword(keyword);
                }

                var data     = System.IO.File.ReadAllBytes(usdTexture.sourceFile.defaultValue);
                var unityTex = new Texture2D(2, 2);
                unityTex.LoadImage(data);
                mat.SetTexture(param.unityName, unityTex);
                Debug.Log("Set " + param.unityName + " to " + usdTexture.sourceFile.defaultValue);

                unityTex.Apply(updateMipmaps: true, makeNoLongerReadable: false);
            }

            //
            // Create and bind the geometry.
            //

            // Create a cube and set the material.
            // Note that geometry is handled minimally here and is incomplete.
            var cubeSample = new CubeSample();

            usdScene.Read(kCubePath, cubeSample);

            var go = GameObject.CreatePrimitive(PrimitiveType.Cube);

            go.transform.SetParent(transform, worldPositionStays: false);
            go.transform.localScale = Vector3.one * (float)cubeSample.size;
            m_cube = transform;

            go.GetComponent <MeshRenderer>().material = mat;
        }
Beispiel #60
0
        void TrySetTextureTransform(
            Schema.TextureInfo textureInfo,
            UnityEngine.Material material,
            int texturePropertyId,
            int scaleTransformPropertyId = -1,
            int rotationPropertyId       = -1,
            int uvChannelPropertyId      = -1,
            bool flipY = false
            )
        {
            // Scale (x,y) and Transform (z,w)
            float4 textureST = new float4(
                1, 1, // scale
                0, 0  // transform
                );

            var texCoord = textureInfo.texCoord;

            if (textureInfo.extensions != null && textureInfo.extensions.KHR_texture_transform != null)
            {
                var tt = textureInfo.extensions.KHR_texture_transform;
                if (tt.texCoord >= 0)
                {
                    texCoord = tt.texCoord;
                }

                float cos = 1;
                float sin = 0;

                if (tt.offset != null)
                {
                    textureST.z = tt.offset[0];
                    textureST.w = 1 - tt.offset[1];
                }
                if (tt.scale != null)
                {
                    textureST.x = tt.scale[0];
                    textureST.y = tt.scale[1];
                }
                if (tt.rotation != 0)
                {
                    cos = math.cos(tt.rotation);
                    sin = math.sin(tt.rotation);

                    var newRot = new Vector2(textureST.x * sin, textureST.y * -sin);

                    Assert.IsTrue(rotationPropertyId >= 0, "Texture rotation property invalid!");
                    material.SetVector(rotationPropertyId, newRot);

                    textureST.x *= cos;
                    textureST.y *= cos;

                    material.EnableKeyword(KW_UV_ROTATION);
                    textureST.z -= newRot.y; // move offset to move rotation point (horizontally)
                }
                else
                {
                    // In case _UV_ROTATION keyword is set (because another texture is rotated),
                    // make sure the rotation is properly nulled
                    material.SetVector(rotationPropertyId, Vector4.zero);
                }

                textureST.w -= textureST.y * cos; // move offset to move flip axis point (vertically)
            }

            if (texCoord != 0)
            {
                if (uvChannelPropertyId >= 0 && texCoord < 2f)
                {
                    material.EnableKeyword(KW_UV_CHANNEL_SELECT);
                    material.SetFloat(uvChannelPropertyId, texCoord);
                }
                else
                {
                    logger?.Error(LogCode.UVMulti, texCoord.ToString());
                }
            }

            if (flipY)
            {
                textureST.w = 1 - textureST.w; // flip offset in Y
                textureST.y = -textureST.y;    // flip scale in Y
            }

            material.SetTextureOffset(texturePropertyId, textureST.zw);
            material.SetTextureScale(texturePropertyId, textureST.xy);
            Assert.IsTrue(scaleTransformPropertyId >= 0, "Texture scale/transform property invalid!");
            material.SetVector(scaleTransformPropertyId, textureST);
        }