SetFloat() private method

private SetFloat ( int nameID, float value ) : void
nameID int
value float
return void
        /// <summary>
        /// Copy Shader properties from source to destination material.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static void CopyMaterialProperties(Material source, Material destination)
        {
            MaterialProperty[] source_prop = MaterialEditor.GetMaterialProperties(new Material[] { source });

            for (int i = 0; i < source_prop.Length; i++)
            {
                int property_ID = Shader.PropertyToID(source_prop[i].name);
                if (destination.HasProperty(property_ID))
                {
                    //Debug.Log(source_prop[i].name + "  Type:" + ShaderUtil.GetPropertyType(source.shader, i));
                    switch (ShaderUtil.GetPropertyType(source.shader, i))
                    {
                        case ShaderUtil.ShaderPropertyType.Color:
                            destination.SetColor(property_ID, source.GetColor(property_ID));                          
                            break;
                        case ShaderUtil.ShaderPropertyType.Float:
                            destination.SetFloat(property_ID, source.GetFloat(property_ID));
                            break;
                        case ShaderUtil.ShaderPropertyType.Range:
                            destination.SetFloat(property_ID, source.GetFloat(property_ID));
                            break;
                        case ShaderUtil.ShaderPropertyType.TexEnv:
                            destination.SetTexture(property_ID, source.GetTexture(property_ID));
                            break;
                        case ShaderUtil.ShaderPropertyType.Vector:
                            destination.SetVector(property_ID, source.GetVector(property_ID));
                            break;
                    }
                }
            }

        }
示例#2
0
 // Use this for initialization
 void Start()
 {
     mat = GetComponent<Renderer> ().material;
     mat.SetColor ("_EnergyColor", energyColor);
     mat.SetFloat ("_Visibility", visibility);
     mat.SetFloat ("_CollisionTime", -99f); // To ensure that animation is already "over" by the time we start.
 }
示例#3
0
    // Use this for initialization
    void Start () {

        waterZones = GameObject.FindGameObjectsWithTag("InteractableWater");

        currentWeather = Weather.CLEAR;
        day = true;

        skybox = RenderSettings.skybox;

        skybox.SetFloat("_DayToNight", 0f);
        skybox.SetFloat("_RainToSnow", 0f);
        skybox.SetFloat("_NormalToRainSnow", 0f);
        skybox.SetFloat("_RainSnowToSpecial", 0f);

        mainLight = FindObjectOfType<Light>();

        foreach (Material m in materials)
        {
            m.SetFloat("_Snow", 0f);
        }

        rain = GameObject.Find("PS_Rain");
        snow = GameObject.Find("PS_Snowflakes");
        other = GameObject.Find("PS_weather");

        rain.SetActive(false);
        snow.SetActive(false);
        other.SetActive(false);

        tM = FindObjectOfType<TrackManager>();

        SetAurore(false);
    }
        private void AddOverlay(TextureSet mTexture, TextureSet dTexture, float altitude, float fadeDistance, float pqsfadeDistance)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            string[] resources = assembly.GetManifestResourceNames();

            StreamReader shaderStreamReader = new StreamReader(assembly.GetManifestResourceStream("CityLights.Shaders.Compiled-SphereCityLights.shader"));

            Log("read stream");
            String shaderString = shaderStreamReader.ReadToEnd();
            Material lightMaterial = new Material(shaderString);
            Material pqsLightMaterial = new Material(shaderString);

            lightMaterial.SetTexture("_MainTex", mTexture.Texture);
            lightMaterial.SetTexture("_DetailTex", dTexture.Texture);
            lightMaterial.SetFloat("_DetailScale", dTexture.Scale);
            lightMaterial.SetVector("_DetailOffset", dTexture.Offset);
            lightMaterial.SetFloat("_FadeDist", fadeDistance);
            lightMaterial.SetFloat("_FadeScale", 1);

            pqsLightMaterial.SetTexture("_MainTex", mTexture.Texture);
            pqsLightMaterial.SetTexture("_DetailTex", dTexture.Texture);
            pqsLightMaterial.SetFloat("_DetailScale", dTexture.Scale);
            pqsLightMaterial.SetVector("_DetailOffset", dTexture.Offset);
            pqsLightMaterial.SetFloat("_FadeDist", pqsfadeDistance);
            pqsLightMaterial.SetFloat("_FadeScale", .02f);

            overlayList.Add(Overlay.GeneratePlanetOverlay("Kerbin", altitude, lightMaterial, pqsLightMaterial, mTexture.StartOffset, false, true));
        }
	void Update()
	{
		terrain = GetComponent<Terrain>();
		tData = terrain ? terrain.terrainData : null;
		tMaterial = terrain ? terrain.materialTemplate : null;
		if (!terrain || !tData || !tMaterial)
			return;
		
		if(disableBasemap && !Application.isPlaying && GetComponent<Terrain>().basemapDistance != 1000000) // only reset on update in edit mode
			GetComponent<Terrain>().basemapDistance = 1000000;
		if (cutoutMode)
		{
			if (tMaterial.HasProperty("_CutoutModeHideAlpha") && tMaterial.GetFloat("_CutoutModeHideAlpha") != cutoutModeHideAlpha)
				tMaterial.SetFloat("_CutoutModeHideAlpha", cutoutModeHideAlpha);
		}
		else
			if (tMaterial.HasProperty("_CutoutModeHideAlpha") && tMaterial.GetFloat("_CutoutModeHideAlpha") != -1)
				tMaterial.SetFloat("_CutoutModeHideAlpha", -1);

		if (!Application.isPlaying)
			ApplyTransparencyMap();
		else
			if (!transparencyMap && autoUpdateTransparencyMap)
			{
				UpdateTransparencyMap();
				ApplyTransparencyMap();
			}
			else
				ApplyTransparencyMap();
	}
示例#6
0
    public static void DrawProteinsAtoms(Material renderProteinsMaterial, Camera camera, RenderBuffer instanceId, RenderBuffer atomId, RenderBuffer depthBuffer, int pass)
    {
        // Protein params
        renderProteinsMaterial.SetInt("_EnableLod", Convert.ToInt32(GlobalProperties.Get.EnableLod));
        renderProteinsMaterial.SetFloat("_Scale", GlobalProperties.Get.Scale);
        renderProteinsMaterial.SetFloat("_FirstLevelBeingRange", GlobalProperties.Get.FirstLevelOffset);
        renderProteinsMaterial.SetVector("_CameraForward", camera.transform.forward);

        renderProteinsMaterial.SetBuffer("_LodLevelsInfos", GPUBuffers.Get.LodInfo);
        renderProteinsMaterial.SetBuffer("_ProteinInstanceInfo", GPUBuffers.Get.ProteinInstancesInfo);
        renderProteinsMaterial.SetBuffer("_ProteinInstancePositions", GPUBuffers.Get.ProteinInstancePositions);
        renderProteinsMaterial.SetBuffer("_ProteinInstanceRotations", GPUBuffers.Get.ProteinInstanceRotations);

        renderProteinsMaterial.SetBuffer("_ProteinColors", GPUBuffers.Get.IngredientsColors);
        renderProteinsMaterial.SetBuffer("_ProteinAtomInfo", GPUBuffers.Get.ProteinAtomInfo);
        renderProteinsMaterial.SetBuffer("_ProteinAtomPositions", GPUBuffers.Get.ProteinAtoms);
        renderProteinsMaterial.SetBuffer("_ProteinClusterPositions", GPUBuffers.Get.ProteinAtomClusters);
        renderProteinsMaterial.SetBuffer("_ProteinSphereBatchInfos", GPUBuffers.Get.SphereBatches);

        /****/
        renderProteinsMaterial.SetInt("_NumCutObjects", SceneManager.Get.NumCutObjects);
        renderProteinsMaterial.SetInt("_NumIngredientTypes", SceneManager.Get.NumAllIngredients);
        

        renderProteinsMaterial.SetBuffer("_CutInfos", GPUBuffers.Get.CutInfo);
        renderProteinsMaterial.SetBuffer("_CutScales", GPUBuffers.Get.CutScales);
        renderProteinsMaterial.SetBuffer("_CutPositions", GPUBuffers.Get.CutPositions);
        renderProteinsMaterial.SetBuffer("_CutRotations", GPUBuffers.Get.CutRotations);
        /****/

        Graphics.SetRenderTarget(new[] { instanceId, atomId }, depthBuffer);
        renderProteinsMaterial.SetPass(1);
        Graphics.DrawProceduralIndirect(MeshTopology.Points, GPUBuffers.Get.ArgBuffer);
    }
    public static void DrawProteinSphereBatches(Material renderProteinsMaterial, Camera camera, RenderBuffer colorBuffer, RenderBuffer depthBuffer, int pass, bool animated = false)
    {
        // Protein params
        renderProteinsMaterial.SetInt("_EnableLod", Convert.ToInt32(PersistantSettings.Instance.EnableLod));
        renderProteinsMaterial.SetFloat("_Scale", PersistantSettings.Instance.Scale);
        renderProteinsMaterial.SetFloat("_FirstLevelBeingRange", PersistantSettings.Instance.FirstLevelOffset);
        renderProteinsMaterial.SetVector("_CameraForward", camera.transform.forward);

        renderProteinsMaterial.SetBuffer("_LodLevelsInfos", GPUBuffers.Instance.LodInfo);
        renderProteinsMaterial.SetBuffer("_ProteinInstanceInfo", GPUBuffers.Instance.ProteinInstanceInfo);

        if(animated) renderProteinsMaterial.SetBuffer("_ProteinInstancePositions", GPUBuffers.Instance.ProteinAnimationPositions);
        else renderProteinsMaterial.SetBuffer("_ProteinInstancePositions", GPUBuffers.Instance.ProteinInstancePositions);

        if (animated) renderProteinsMaterial.SetBuffer("_ProteinInstanceRotations", GPUBuffers.Instance.ProteinAnimationRotations);
        else renderProteinsMaterial.SetBuffer("_ProteinInstanceRotations", GPUBuffers.Instance.ProteinInstanceRotations);

        renderProteinsMaterial.SetBuffer("_ProteinAtomCount", GPUBuffers.Instance.ProteinAtomCount);
        renderProteinsMaterial.SetBuffer("_ProteinColors", GPUBuffers.Instance.ProteinColors);
        renderProteinsMaterial.SetBuffer("_ProteinAtomPositions", GPUBuffers.Instance.ProteinAtoms);
        renderProteinsMaterial.SetBuffer("_ProteinClusterPositions", GPUBuffers.Instance.ProteinAtomClusters);
        renderProteinsMaterial.SetBuffer("_ProteinSphereBatchInfos", GPUBuffers.Instance.SphereBatches);

        Graphics.SetRenderTarget(colorBuffer, depthBuffer);
        renderProteinsMaterial.SetPass(pass);
        Graphics.DrawProceduralIndirect(MeshTopology.Points, GPUBuffers.Instance.ArgBuffer);
    }
    void updateSprite(SpriteRenderer spriteRenderer, AlphaMaskScript mask)
    {
        Texture2D a = mask.clipTexture;
        Texture2D b = spriteRenderer.sprite.texture;
        float w1 = (float)a.width;
        float h1 = (float)a.height;
        float w2 = (float)b.width;
        float h2 = (float)b.height;
        float xScale = h1 / h2;
        float yScale = w1 / w2;
        float adjustScale = xScale > yScale ? yScale : xScale;
        xScale = xScale / adjustScale / mask.scale;
        yScale = yScale / adjustScale / mask.scale;
        float xOffset = mask.xOffsetPixel / w2;
        float yOffset = mask.yOffsetPixel / h2;

        var mat = new Material(Shader.Find("Unlit/AlphaMask"));
        mat.name = mask.ToName();
        mat.SetTexture("_ClipTex", mask.clipTexture);
        mat.SetFloat("_xScale", xScale);
        mat.SetFloat("_yScale", yScale);
        mat.SetFloat("_xOffset", xOffset);
        mat.SetFloat("_yOffset", yOffset);

        spriteRenderer.sharedMaterial = mat;

        Debug.Log(string.Format(
            "update alpha mask target={0}x{1} mask={2}x{3}",
            w1,
            h1,
            w2,
            h2
        ));
    }
    public void UpdateMeshHeights(Material material, float minHeight, float maxHeight)
    {
        savedMinHeight = minHeight;
        savedMaxHeight = maxHeight;

        material.SetFloat("minHeight", minHeight);
        material.SetFloat("maxHeight", maxHeight);
    }
示例#10
0
    private void createMaterials()
    {
        gameMaterial = new Material(GameShader);
        gameMaterial.SetFloat("_GridStepX", 1.0f/Width);
        gameMaterial.SetFloat("_GridStepY", 1.0f/Height);

        edgeDetectMaterial = new Material(EdgeDetectShader);
    }
示例#11
0
	public Material getMaterial(){
		if (material == null) {
			material = new Material(Shader.Find("Custom/2D Tile Shader"));
			material.SetTexture("_Tex", texture);
			material.SetFloat("_Width", width);
			material.SetFloat("_Height", height);
		}
		return material;
	}
		public void Apply(ConfigNode node)
		{
			//create scaled material and set proprties to defaults
			scaledMaterial = new Material (Shaders.EmissiveScaled);
			scaledMaterial.SetTextureScale ("_EmissiveMap", Vector2.one);
			scaledMaterial.SetTextureOffset ("_EmissiveMap", Vector2.zero);
			scaledMaterial.SetColor ("_Color", new Color (1f, 1f, 1f));
			scaledMaterial.SetFloat ("_Brightness", 1.25f);
			scaledMaterial.SetFloat ("_Transparency", 0.75f);
		}
 // Use this for initialization
 void Awake()
 {
     MeshRenderer rend = GetComponent<MeshRenderer>();
     shockwaveDistortionMat = rend.material = Instantiate(rend.material);
     Callback.DoLerp((float l) =>
     {
         shockwaveDistortionMat.SetFloat("_MaxRange", l / 2);
         shockwaveDistortionMat.SetFloat("_Annulus", 1 - (l * l));
     }, time, this);
 }
示例#14
0
 void Awake()
 {
     if(!grayscaleMaterial)
     {
         grayscaleMaterial = new Material(BDAShaderLoader.GrayscaleEffectShader);
         grayscaleMaterial.SetTexture("_RampTex", textureRamp);
         grayscaleMaterial.SetFloat("_RedPower", rampOffset);
         grayscaleMaterial.SetFloat("_RedDelta", rampOffset);
     }
 }
 public void Start()
 {
     fxRes = GetComponent<IndieEffects>();
     mat = new Material(shader);
     mat.SetColor("_Lift", Lift);
     mat.SetFloat("_LiftB", Mathf.Clamp(LiftBright, 0f, 2f));
     mat.SetColor("_Gamma", Gamma);
     mat.SetFloat("_GammaB", Mathf.Clamp(GammaBright, 0f, 2f));
     mat.SetColor("_Gain", Gain);
     mat.SetFloat("_GainB", Mathf.Clamp(GainBright, 0f, 2f));
 }
示例#16
0
 public void SetWaveMat(Material mat, GameObject gamin)
 {
     float meshWidth =  gamin.GetComponent<MeshFilter>().sharedMesh.bounds.size.x;
     //float meshWidth = gamin.transform.lossyScale.x * gamin.transform.lossyScale.x;
     mat.SetFloat ("_TimeCostum", Time.time);
     mat.SetVector ("_ObjectScale", gamin.transform.lossyScale);
     mat.SetFloat ("_SineAmplitude", amplitude);
     mat.SetVector ("_SineFrequency", new Vector4 (sineFrequency.x, sineFrequency.y, 0, 0));
     mat.SetVector ("_Speed", new Vector4 (waveSpeed.x, waveSpeed.y, 0, 0));
     mat.SetVector ("_Steepness", new Vector4 (steepness.x, steepness.y, 0, 0));
     mat.SetVector ("_Dir", new Vector4 (waveDirection1.x, waveDirection1.y, waveDirection1.z, 0));
     mat.SetVector ("_Dir2", new Vector4 (waveDirection2.x, waveDirection2.y, waveDirection2.z, 0));
 }
        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);
        }
示例#18
0
 private void Start()
 {
     Debug.Assert(_chargeSpeed > 0f);
     Material mat = new Material(Shader.Find(_shaderName));
     _guitarBodyRenderer.material = mat;
     _currHeight = _bottomHeight;
     mat.SetVector("_PlanePos", new Vector4(0, _bottomHeight, 0, 1));
     mat.SetVector("_PlaneNormal", new Vector4(0, 1, 0, 0));
     mat.SetFloat("_ThresDist", _currHeight);
     mat.SetTexture("_MainTex", _guitarBodyTex);
     mat.SetFloat("_EmissionSwitch", 0f);
     mat.SetFloat("_EmissionIntensity", _EmissionIntensity);
 }
示例#19
0
        /// <summary>
        /// Create a Masking Material Instance for the given ID
        /// </summary>
        /// <param name="baseMaterial"></param>
        /// <param name="stencilID"></param>
        /// <returns></returns>
        public static Material GetStencilMaterial(Material baseMaterial, int stencilID)
        {
            // Check if Material supports masking
            if (!baseMaterial.HasProperty(ShaderUtilities.ID_StencilID))
            {
                Debug.LogWarning("Selected Shader does not support Stencil Masking. Please select the Distance Field or Mobile Distance Field Shader.");
                return baseMaterial;
            }

            Material stencilMaterial = null;

            // Check if baseMaterial already has a masking material associated with it.
            int index = m_materialList.FindIndex(item => item.baseMaterial == baseMaterial && item.stencilID == stencilID);

            if (index == -1)
            {
                //Create new Masking Material Instance for this Base Material 
                stencilMaterial = new Material(baseMaterial);
                stencilMaterial.hideFlags = HideFlags.HideAndDontSave;
                stencilMaterial.name += " Masking ID:" + stencilID;
                stencilMaterial.shaderKeywords = baseMaterial.shaderKeywords;

                // Set Stencil Properties
                ShaderUtilities.GetShaderPropertyIDs();
                stencilMaterial.SetFloat(ShaderUtilities.ID_StencilID, stencilID);
                stencilMaterial.SetFloat(ShaderUtilities.ID_StencilComp, 4);

                MaskingMaterial temp = new MaskingMaterial();
                temp.baseMaterial = baseMaterial;
                temp.stencilMaterial = stencilMaterial;
                temp.stencilID = stencilID;
                temp.count = 1;

                m_materialList.Add(temp);

                //Debug.Log("Masking material for " + baseMaterial.name + " DOES NOT exists. Creating new " + maskingMaterial.name + " with ID " + maskingMaterial.GetInstanceID() + " which is used " + temp.count + " time(s).");

            }
            else
            {
                stencilMaterial = m_materialList[index].stencilMaterial;
                m_materialList[index].count += 1;

                //Debug.Log("Masking material for " + baseMaterial.name + " already exists. Passing reference to " + maskingMaterial.name + " with ID " + maskingMaterial.GetInstanceID() + " which is used " + m_materialList[index].count + " time(s).");
            }

            // Used for Debug
            ListMaterials();
            
            return stencilMaterial;
        }
示例#20
0
			// Constructor
			public RendererCache(Renderer r, Material sharedOpaqueMaterial, float zTest, float stencilRef)
			{
				data = new List<Data>();
				renderer = r;
				go = r.gameObject;

				Material[] materials = r.sharedMaterials;

				if (materials != null)
				{
					for (int i = 0; i < materials.Length; i++)
					{
						Material sourceMat = materials[i];

						if (sourceMat == null) { continue; }

						Data d = new Data();
						
						string tag = sourceMat.GetTag("RenderType", true, "Opaque");
						if (tag == "Transparent" || tag == "TransparentCutout")
						{
							Material replacementMat = new Material(transparentShader);
							replacementMat.SetFloat(ShaderPropertyID._ZTest, zTest);
							replacementMat.SetFloat(ShaderPropertyID._StencilRef, stencilRef);
							if (sourceMat.HasProperty(ShaderPropertyID._MainTex))
							{
								replacementMat.SetTexture(ShaderPropertyID._MainTex, sourceMat.mainTexture);
								replacementMat.SetTextureOffset("_MainTex", sourceMat.mainTextureOffset);
								replacementMat.SetTextureScale("_MainTex", sourceMat.mainTextureScale);
							}
							
							int cutoff = ShaderPropertyID._Cutoff;
							replacementMat.SetFloat(cutoff, sourceMat.HasProperty(cutoff) ? sourceMat.GetFloat(cutoff) : transparentCutoff);

							d.material = replacementMat;
							d.transparent = true;
						}
						else
						{
							d.material = sharedOpaqueMaterial;
							d.transparent = false;
						}

						d.submeshIndex = i;
						data.Add(d);
					}
				}

				visible = IsVisible();
			}
示例#21
0
    void Awake()
    {
        for (int i = 0; i < maxRipples; ++i) {
            ripples.Add(new Ripple());
        }
        material = GetComponent<Renderer>().material;
        previousPosition = transform.position;

        material.SetFloat("_MaxRadius_c", maxRadius);
        material.SetFloat("_RippleWidth_c", rippleWidth);
        material.SetFloat("_RippleSpacing_c", rippleSpacing);
        material.SetFloat("_NumConcentricRipples_c", numConcentricRipples);
        material.SetFloat("_RippleAlpha_c", rippleAlpha);
        material.SetVector("_RippleColor", rippleColor);
    }
示例#22
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");
    }
示例#23
0
        public static IEnumerator LinearDissolve(Material mat, float from, float to, float time)
        {
            float elapsedTime = 0f;

            while (elapsedTime < time) {
                if (mat.HasProperty(dissolveAmountID)) {
                    mat.SetFloat(dissolveAmountID, Mathf.Lerp(from, to, elapsedTime/time));
                }
                elapsedTime += Time.deltaTime;
                yield return null;
            }

            if (mat.HasProperty(dissolveAmountID)) {
                mat.SetFloat (dissolveAmountID, to);
            }
        }
示例#24
0
	protected void SetGenericMaterialProperty(Material destination, string property_name, object value)
	{
		try{

			ShaderUtil.ShaderPropertyType type = GetPropertyType(destination, property_name);
			switch(type)
			{
			case ShaderUtil.ShaderPropertyType.Color:
				destination.SetColor(property_name, value.UnityBridgeObjectToColor());
				break;
			case ShaderUtil.ShaderPropertyType.Range:
			case ShaderUtil.ShaderPropertyType.Float:
				destination.SetFloat(property_name, value.UnityBridgeObjectToFloat());
				break;
			case ShaderUtil.ShaderPropertyType.Vector:
				destination.SetVector(property_name, value.UnityBridgeObjectToVector());
				break;
			case ShaderUtil.ShaderPropertyType.TexEnv:
				destination.SetTexture(property_name, TextureManager.Instance.ResolveMap( destination.name + "_" + property_name, value));
				break;
			default:
				Debug.Log("Unknown shader type " + type.ToString());
				break;
			}

		}
		catch(KeyNotFoundException e)
		{
			Debug.Log(e.Message);
		}
	}
 public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
 {
     if (material.HasProperty("_Emission"))
     {
         material.SetColor("_EmissionColor", material.GetColor("_Emission"));
     }
     base.AssignNewShaderToMaterial(material, oldShader, newShader);
     if ((oldShader == null) || !oldShader.name.Contains("Legacy Shaders/"))
     {
         SetupMaterialWithBlendMode(material, (BlendMode) ((int) material.GetFloat("_Mode")));
     }
     else
     {
         BlendMode opaque = BlendMode.Opaque;
         if (oldShader.name.Contains("/Transparent/Cutout/"))
         {
             opaque = BlendMode.Cutout;
         }
         else if (oldShader.name.Contains("/Transparent/"))
         {
             opaque = BlendMode.Fade;
         }
         material.SetFloat("_Mode", (float) opaque);
         Material[] mats = new Material[] { material };
         this.DetermineWorkflow(MaterialEditor.GetMaterialProperties(mats));
         MaterialChanged(material, this.m_WorkflowMode);
     }
 }
示例#26
0
	// Use this for initialization
	void Start () {
		//Destroy(this);
		currentMaterial = GetComponent<Renderer>().material;
		
		cycle = 6.0f;//flowSpeed * 3.0f * .1f;//.15f;
		//Debug.Log("flowSpeed: " + flowSpeed + " cycle: " + cycle);
		halfCycle = cycle * .5f;
		
		flowMapOffset0 = 0.0f;
		flowMapOffset1 = halfCycle;
		
		//flowSpeed *= -1.0f;
		
		currentMaterial.SetFloat("halfCycle", halfCycle);
		
		/*if ( currentMaterial.HasProperty("_normalStrength") ) {
			float normalStrength = currentMaterial.GetFloat("_normalStrength") * flowSpeed;
			Debug.Log("normalStrength: " + normalStrength);
			normalStrength = Mathf.Clamp(normalStrength, 0.01f, 50.0f);
				
			currentMaterial.SetFloat("_normalStrength", normalStrength);
		}
		
		if ( currentMaterial.HasProperty("flowTide") )
			hasTide = true;
		else
			hasTide = false;*/
	}
 static public int SetFloat(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (matchType(l, argc, 2, typeof(int), typeof(float)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.Int32         a1;
             checkType(l, 2, out a1);
             System.Single a2;
             checkType(l, 3, out a2);
             self.SetFloat(a1, a2);
             pushValue(l, true);
             return(1);
         }
         else if (matchType(l, argc, 2, typeof(string), typeof(float)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.String        a1;
             checkType(l, 2, out a1);
             System.Single a2;
             checkType(l, 3, out a2);
             self.SetFloat(a1, a2);
             pushValue(l, true);
             return(1);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
    static int SetFloat(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(int), typeof(float)))
            {
                UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1);
                int   arg0 = (int)LuaDLL.lua_tonumber(L, 2);
                float arg1 = (float)LuaDLL.lua_tonumber(L, 3);
                obj.SetFloat(arg0, arg1);
                return(0);
            }
            else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(string), typeof(float)))
            {
                UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1);
                string arg0 = ToLua.ToString(L, 2);
                float  arg1 = (float)LuaDLL.lua_tonumber(L, 3);
                obj.SetFloat(arg0, arg1);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Material.SetFloat"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
示例#29
0
        /// <summary>
        /// Sets the shader parameters of this renderer to the specified material.
        /// </summary>
        /// <param name="material"></param>
        public void SetShaderParams(Material material)
        {
            // Set all properties
            material.SetBuffer("HairVertexTangents", this._master.g_HairVertexTangents);
            material.SetBuffer("HairVertexPositions", this._master.g_HairVertexPositions);
            material.SetBuffer("TriangleIndicesBuffer", this.g_TriangleIndicesBuffer);
            material.SetBuffer("LineIndicesBuffer", this.g_LineIndicesBuffer);
            material.SetBuffer("GlobalRotations", this._master.g_GlobalRotations);
            material.SetBuffer("HairThicknessCoeffs", this._master.g_HairThicknessCoeffs);
            material.SetBuffer("TexCoords", this._master.g_TexCoords);
            material.SetFloat("_ThinTip", this.hairMaterial.GetFloat("_ThinTip"));
            material.SetFloat("_HairWidth", this.hairMaterial.GetFloat("_HairWidth"));
            material.SetFloat("_HairWidthMultiplier", this.hairMaterial.GetFloat("_HairWidthMultiplier"));

            SetSimulationTransformCorrection(material);
        }
示例#30
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);
    }
        public static Material createMaterial(FacadeSkin skin)
        {
            Material mat = new Material(Shader.Find("Standard (Specular setup)"));

            Texture2D colortex = getTexture(skin.colorTexturePath);
            Texture2D normaltex = getTexture(skin.normalTexturePath);
            Texture2D speculartex = getTexture(skin.specularTexturePath);

            mat.SetTexture("_MainTex", colortex);
            mat.SetTexture("_BumpMap", normaltex);
            mat.SetFloat("_BumpScale", 1.0f);
            mat.SetFloat("_Glossiness", 0.1f);
            mat.SetTexture("_SpecGlossMap", speculartex);

            return mat;
        }
示例#32
0
	public FourierGPU(int size)
	{	
		if(size > 256)
		{
			Debug.Log("FourierGPU::FourierGPU - fourier grid size must not be greater than 256, changing to 256");
			size = 256;
		}
		
		if(!Mathf.IsPowerOfTwo(size))
		{
			Debug.Log("FourierGPU::FourierGPU - fourier grid size must be pow2 number, changing to nearest pow2 number");
			size = Mathf.NextPowerOfTwo(size);
		}
		
//		Shader shader = Shader.Find("Math/Fourier");
		Shader shader = ShaderTool.GetShader2 ("CompiledFourier.shader");

		if(shader == null) Debug.Log("FourierGPU::FourierGPU - Could not find shader Math/Fourier");
	
		m_fourier = new Material(shader);

		m_size = size; //must be pow2 num
		m_fsize = (float)m_size;
		m_passes = (int)(Mathf.Log(m_fsize)/Mathf.Log(2.0f));
		
		m_butterflyLookupTable = new Texture2D[m_passes];
		
		ComputeButterflyLookupTable();
		
		m_fourier.SetFloat("_Size", m_fsize);
	}
        private void Render(RenderTexture destination)
        {
            // Make sure we have a current render target
            InitRenderTexture();

            // Set the target and dispatch the compute shader
            rtxShader.SetTexture(0, "Result", _target);

            var threadGroupsX = Mathf.CeilToInt(Screen.width / 8.0f);
            var threadGroupsY = Mathf.CeilToInt(Screen.height / 8.0f);

            rtxShader.Dispatch(0, threadGroupsX, threadGroupsY, 1);

            // Blit the result texture to the screen
            _addMaterial.SetFloat(Sample, _currentSample);
            Graphics.Blit(_target, destination, _addMaterial);
            _currentSample++;
        }
        // This is a hack for GI. PVR looks in the shader for a texture named "_MainTex" to extract the opacity of the material for baking. In the same manner, "_Cutoff" and "_Color" are also necessary.
        // Since we don't have those parameters in our shaders we need to provide a "fake" useless version of them with the right values for the GI to work.
        private static void SetupMainTexForAlphaTestGI(UnityEngine.Material unityMaterial, string colorMapPropertyName, string colorPropertyName)
        {
            if (unityMaterial.HasProperty(colorMapPropertyName))
            {
                var mainTex = unityMaterial.GetTexture(colorMapPropertyName);
                unityMaterial.SetTexture(MainTex, mainTex);
            }

            if (unityMaterial.HasProperty(colorPropertyName))
            {
                var color = unityMaterial.GetColor(colorPropertyName);
                unityMaterial.SetColor(Color, color);
            }

            if (unityMaterial.HasProperty("_AlphaCutoff"))
            {
                var cutoff = unityMaterial.GetFloat(AlphaCutoff);
                unityMaterial.SetFloat(Cutoff, cutoff);
            }
        }
示例#35
0
        Material GetUnlitMaterial(bool doubleSided = false)
        {
            if (unlitShader == null)
            {
                unlitShader = FinderShaderUnlit();
            }
            if (unlitShader == null)
            {
                return(null);
            }
            var mat = new Material(unlitShader);

            if (doubleSided)
            {
                // Turn off back-face culling
                mat.SetFloat(cullModePropId, 0);
#if UNITY_EDITOR
                mat.doubleSidedGI = true;
#endif
            }
            return(mat);
        }
示例#36
0
    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);
    }
示例#37
0
        Material GetPbrMetallicRoughnessMaterial(bool doubleSided = false)
        {
            if (pbrMetallicRoughnessShader == null)
            {
                pbrMetallicRoughnessShader = FinderShaderMetallicRoughness();
            }
            if (pbrMetallicRoughnessShader == null)
            {
                return(null);
            }
            var mat = new Material(pbrMetallicRoughnessShader);

            if (doubleSided)
            {
                // Turn off back-face culling
                mat.SetFloat(cullModePropId, 0);
#if UNITY_EDITOR
                mat.doubleSidedGI = true;
#endif
            }
            return(mat);
        }
        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,
                            gltf,
                            transmissionTexturePropId,
                            transmissionTextureScaleTransformPropId, // TODO: add support in shader
                            transmissionTextureRotationPropId,       // TODO: add support in shader
                            transmissionTextureUVChannelPropId       // TODO: add support in shader
                            ))
                    {
                    }
                }
                return(renderQueue);
            }

            return(base.ApplyTransmission(
                       ref baseColorLinear,
                       gltf,
                       transmission,
                       material,
                       renderQueue
                       ));
        }
示例#39
0
        // マテリアルの登録
        private UnityEngine.Material EntryMaterial(int i)
        {
            UnityEngine.Material mat    = new UnityEngine.Material(Shader.Find("VertexLit"));
            Material             source = matList.materials[i];
            Texture tex = null;

            // テクスチャを貼る
            if (source.TextureFileName != "")
            {
                tex             = AssetDatabase.LoadAssetAtPath(folderPath + source.TextureFileName, typeof(Texture)) as Texture;
                mat.mainTexture = tex;
                mat.SetTextureScale("_MainTex", new Vector2(1, -1));
            }

            mat.color = source.DiffuseColor;
            mat.SetColor("_SpecColor", source.SpecularColor);
            mat.SetColor("_Emission", source.EmissionColor);
            mat.SetFloat("_Shiness", source.Specularity);
            mat.name = this.fileName + "_" + source.Name;

            AssetDatabase.CreateAsset(mat, folderPath + "Materials/" + mat.name + ".asset");
            return(mat);
        }
示例#40
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);
 }
示例#41
0
 protected override void SetAlphaModeMask(Schema.Material gltfMaterial, Material material)
 {
     base.SetAlphaModeMask(gltfMaterial, material);
     material.SetFloat(k_AlphaClip, 1);
 }
示例#42
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);
        }
 public void SetSmoothness(Material material, float smoothness)
 {
     material.SetFloat(Smoothness, smoothness);
 }
示例#44
0
        private static UnityEngine.Material Convert(RenderWareStream.Material src, TextureDictionary[] txds, MaterialFlags flags)
        {
            LoadedTexture diffuse;
            LoadedTexture mask = null;

            var overrideAlpha = (flags & MaterialFlags.OverrideAlpha) == MaterialFlags.OverrideAlpha;
            var vehicle       = (flags & MaterialFlags.Vehicle) == MaterialFlags.Vehicle;

            if (!overrideAlpha && src.Colour.A != 255)
            {
                flags |= MaterialFlags.Alpha;
            }

            if (src.TextureCount > 0)
            {
                var tex = src.Textures[0];
                diffuse = txds.GetDiffuse(tex.TextureName);

                if (src.TextureCount > 1)
                {
                    Debug.LogFormat("Something has {0} textures!", src.TextureCount);
                }

                if (diffuse == null)
                {
                    Debug.LogWarningFormat("Unable to find texture {0}", tex.TextureName);
                }

                if (!string.IsNullOrEmpty(tex.MaskName))
                {
                    mask = txds.GetAlpha(tex.MaskName) ?? diffuse;
                }
                else if (vehicle)
                {
                    mask = diffuse;
                }

                if (!overrideAlpha && mask != null && mask.HasAlpha)
                {
                    flags |= MaterialFlags.Alpha;
                }
            }
            else
            {
                diffuse = WhiteTex;
            }

            var shader = GetShader(flags);
            var mat    = new UnityEngine.Material(shader);

            var clr = Types.Convert(src.Colour);

            if (vehicle)
            {
                var found = false;
                for (var i = 1; i < _sKeyColors.Length; ++i)
                {
                    var key = _sKeyColors[i];
                    if (key.r != clr.r || key.g != clr.g || key.b != clr.b)
                    {
                        continue;
                    }
                    mat.SetInt(CarColorIndexId, i);
                    found = true;
                    break;
                }

                if (found)
                {
                    mat.color = Color.white;
                }
                else
                {
                    mat.color = clr;
                }
            }
            else
            {
                mat.color = clr;
            }

            if (diffuse != null)
            {
                mat.SetTexture(MainTexId, diffuse.Texture);
            }
            if (mask != null)
            {
                mat.SetTexture(MaskTexId, mask.Texture);
            }

            mat.SetFloat(MetallicId, src.Specular);
            mat.SetFloat(SmoothnessId, src.Smoothness);

            return(mat);
        }
        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);
        }
        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);
        }
示例#47
0
        private static void ApplyBlendMode(UnityEngine.Material unityMaterial, BlendMode blendMode)
        {
            switch (blendMode)
            {
            case BlendMode.Opaque:

                // keywords
                unityMaterial.DisableKeyword("_ALPHATEST_ON");
                unityMaterial.DisableKeyword("_ALPHABLEND_ON");
                unityMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON");

                // 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(Mode, 0);

                // render queue
                unityMaterial.renderQueue = -1;

                break;

            case BlendMode.Cutout:

                // keywords
                unityMaterial.EnableKeyword("_ALPHATEST_ON");
                unityMaterial.DisableKeyword("_ALPHABLEND_ON");
                unityMaterial.DisableKeyword("_ALPHAPREMULTIPLY_ON");

                // 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(Mode, 1);

                // render queue
                unityMaterial.renderQueue = 2450;

                break;

            case BlendMode.Translucent:

                // keywords
                unityMaterial.DisableKeyword("_ALPHATEST_ON");
                unityMaterial.DisableKeyword("_ALPHABLEND_ON");
                unityMaterial.EnableKeyword("_ALPHAPREMULTIPLY_ON");

                // required for the blend mode
                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);

                // properties
                unityMaterial.SetFloat(Mode, 3);

                // render queue
                unityMaterial.renderQueue = 3000;

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
 protected override void SetDoubleSided(Schema.Material gltfMaterial, Material material)
 {
     base.SetDoubleSided(gltfMaterial, material);
     material.SetFloat(cullPropId, (int)CullMode.Off);
 }
示例#49
0
        private void CreateMaterialsForInstances(ResultSetBuilder resultSetBuilder)
        {
            for (var i = 0; i < _materialInstanceList.Count; i++)
            {
                var instanceDocument = _materialInstanceList[i];
                var parentDocument   = FindUnrealMaterialByInstanceDocument(instanceDocument);

                RaiseStepEvent(instanceDocument.FileName, MaterialCount + i);

                if (null == parentDocument)
                {
                    continue;
                }

                var processor        = new MaterialInstanceDocumentProcessor();
                var result           = processor.Convert(instanceDocument);
                var materialInstance = result.RootNode;

                var shaderPath  = "Assets/" + MakeRelativePath(_outputDirectory, MakeOutputPathForShaderGraph(parentDocument));
                var shaderAsset = AssetDatabase.LoadAssetAtPath <Shader>(shaderPath);

                if (null == shaderAsset)
                {
                    continue;
                }

                var graphData     = JsonUtility.FromJson <GraphData>(File.ReadAllText(shaderPath));
                var materialAsset = new Material(shaderAsset);

                foreach (var parameter in materialInstance.ScalarParameters)
                {
                    var parameterName  = parameter.FindPropertyValue("ParameterName") ?? FindNameFromParameterInfo(parameter);
                    var parameterValue = ValueUtil.ParseFloat(parameter.FindPropertyValue("ParameterValue") ?? "1.0");

                    if (graphData.properties.Any(p => p.displayName == parameterName))
                    {
                        var parameterReference = graphData.properties.First(p => p.displayName == parameterName).referenceName;

                        materialAsset.SetFloat(parameterReference, parameterValue);
                    }
                }

                foreach (var parameter in materialInstance.VectorParameters)
                {
                    var parameterName  = parameter.FindPropertyValue("ParameterName") ?? FindNameFromParameterInfo(parameter);
                    var parameterValue = ValueUtil.ParseVector4(parameter.FindPropertyValue("ParameterValue") ?? "(R=0.0,G=0.0,B=0.0,A=1.0)");

                    if (graphData.properties.Any(p => p.displayName == parameterName))
                    {
                        var parameterReference = graphData.properties.First(p => p.displayName == parameterName).referenceName;

                        materialAsset.SetVector(parameterReference, new Vector4(parameterValue.X, parameterValue.Y, parameterValue.Z, parameterValue.A));
                    }
                }

                foreach (var parameter in materialInstance.TextureParameters)
                {
                    var parameterName  = parameter.FindPropertyValue("ParameterName") ?? FindNameFromParameterInfo(parameter);
                    var parameterValue = ValueUtil.ParseResourceReference(parameter.FindPropertyValue("ParameterValue"));

                    if (graphData.properties.Any(p => p.displayName == parameterName))
                    {
                        var parameterReference = graphData.properties.First(p => p.displayName == parameterName).referenceName;

                        var textureAssetPath = "Assets" + Path.ChangeExtension(parameterValue.FileName, "TGA");
                        var textureAsset     = AssetDatabase.LoadAssetAtPath <Texture>(textureAssetPath);

                        materialAsset.SetTexture(parameterReference, textureAsset);
                    }
                }

                var outputPath = MakeOutputPathForMaterial(instanceDocument, true);

                Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

                AssetDatabase.CreateAsset(materialAsset, outputPath);
            }
        }
        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;
        }
示例#51
0
        // https://forum.unity.com/threads/specular-convolution-when-calculating-mip-maps-for-cubemap-render-texture.617680/
        private Cubemap GetSpecularCubeMap(Cubemap srcCubemap)
        {
            var convolutionMaterial = new UnityEngine.Material(Shader.Find("Hidden/CubeBlur"));

            GL.PushMatrix();
            GL.LoadOrtho();
            RenderTexture dstCubemap = new RenderTexture(srcCubemap.width, srcCubemap.height, 0, RenderTextureFormat.ARGBHalf);

            dstCubemap.dimension    = UnityEngine.Rendering.TextureDimension.Cube;
            dstCubemap.volumeDepth  = 6;
            dstCubemap.wrapMode     = TextureWrapMode.Clamp;
            dstCubemap.filterMode   = FilterMode.Trilinear;
            dstCubemap.isPowerOfTwo = true;
            dstCubemap.Create();
            var mip    = .2f;
            var dstMip = 0;
            var mipRes = srcCubemap.width;

            convolutionMaterial.SetTexture("_MainTex", srcCubemap);
            convolutionMaterial.SetFloat("_Texel", 1f / mipRes);
            convolutionMaterial.SetFloat("_Level", mip);

            convolutionMaterial.SetPass(0);

            Texture2D tex2d = new Texture2D(srcCubemap.width * 6, srcCubemap.height, TextureFormat.RGBAHalf, false);

            // Positive X
            Graphics.SetRenderTarget(dstCubemap, dstMip, CubemapFace.PositiveX);
            GL.Begin(GL.QUADS);
            GL.TexCoord3(1, 1, 1);
            GL.Vertex3(0, 0, 1);
            GL.TexCoord3(1, -1, 1);
            GL.Vertex3(0, 1, 1);
            GL.TexCoord3(1, -1, -1);
            GL.Vertex3(1, 1, 1);
            GL.TexCoord3(1, 1, -1);
            GL.Vertex3(1, 0, 1);
            GL.End();
            tex2d.ReadPixels(new Rect(0, 0, srcCubemap.width, srcCubemap.height), srcCubemap.width * 0, 0);

            // Negative X
            Graphics.SetRenderTarget(dstCubemap, dstMip, CubemapFace.NegativeX);
            GL.Begin(GL.QUADS);
            GL.TexCoord3(-1, 1, -1);
            GL.Vertex3(0, 0, 1);
            GL.TexCoord3(-1, -1, -1);
            GL.Vertex3(0, 1, 1);
            GL.TexCoord3(-1, -1, 1);
            GL.Vertex3(1, 1, 1);
            GL.TexCoord3(-1, 1, 1);
            GL.Vertex3(1, 0, 1);
            GL.End();
            tex2d.ReadPixels(new Rect(0, 0, srcCubemap.width, srcCubemap.height), srcCubemap.width * 1, 0);

            // Positive Y
            Graphics.SetRenderTarget(dstCubemap, dstMip, CubemapFace.PositiveY);
            GL.Begin(GL.QUADS);
            GL.TexCoord3(-1, 1, -1);
            GL.Vertex3(0, 0, 1);
            GL.TexCoord3(-1, 1, 1);
            GL.Vertex3(0, 1, 1);
            GL.TexCoord3(1, 1, 1);
            GL.Vertex3(1, 1, 1);
            GL.TexCoord3(1, 1, -1);
            GL.Vertex3(1, 0, 1);
            GL.End();
            tex2d.ReadPixels(new Rect(0, 0, srcCubemap.width, srcCubemap.height), srcCubemap.width * 2, 0);

            // Negative Y
            Graphics.SetRenderTarget(dstCubemap, dstMip, CubemapFace.NegativeY);
            GL.Begin(GL.QUADS);
            GL.TexCoord3(-1, -1, 1);
            GL.Vertex3(0, 0, 1);
            GL.TexCoord3(-1, -1, -1);
            GL.Vertex3(0, 1, 1);
            GL.TexCoord3(1, -1, -1);
            GL.Vertex3(1, 1, 1);
            GL.TexCoord3(1, -1, 1);
            GL.Vertex3(1, 0, 1);
            GL.End();
            tex2d.ReadPixels(new Rect(0, 0, srcCubemap.width, srcCubemap.height), srcCubemap.width * 3, 0);

            // Positive Z
            Graphics.SetRenderTarget(dstCubemap, dstMip, CubemapFace.PositiveZ);
            GL.Begin(GL.QUADS);
            GL.TexCoord3(-1, 1, 1);
            GL.Vertex3(0, 0, 1);
            GL.TexCoord3(-1, -1, 1);
            GL.Vertex3(0, 1, 1);
            GL.TexCoord3(1, -1, 1);
            GL.Vertex3(1, 1, 1);
            GL.TexCoord3(1, 1, 1);
            GL.Vertex3(1, 0, 1);
            GL.End();
            tex2d.ReadPixels(new Rect(0, 0, srcCubemap.width, srcCubemap.height), srcCubemap.width * 4, 0);

            // Negative Z
            Graphics.SetRenderTarget(dstCubemap, dstMip, CubemapFace.NegativeZ);
            GL.Begin(GL.QUADS);
            GL.TexCoord3(1, 1, -1);
            GL.Vertex3(0, 0, 1);
            GL.TexCoord3(1, -1, -1);
            GL.Vertex3(0, 1, 1);
            GL.TexCoord3(-1, -1, -1);
            GL.Vertex3(1, 1, 1);
            GL.TexCoord3(-1, 1, -1);
            GL.Vertex3(1, 0, 1);
            GL.End();
            tex2d.ReadPixels(new Rect(0, 0, srcCubemap.width, srcCubemap.height), srcCubemap.width * 5, 0);

            GL.PopMatrix();

            tex2d.Apply();

            for (int x = 0; x < tex2d.width; x++)
            {
                for (int y1 = 0, y2 = tex2d.height - 1; y1 < y2; y1++, y2--)
                {
                    var t1 = tex2d.GetPixel(x, y1);
                    tex2d.SetPixel(x, y1, tex2d.GetPixel(x, y2));
                    tex2d.SetPixel(x, y2, t1);
                }
            }

            UnityEngine.Object.DestroyImmediate(dstCubemap);

            var path = "Assets/temp" + DateTime.Now.ToBinary() + ".exr";

            File.WriteAllBytes(path, tex2d.EncodeToEXR());
            AssetDatabase.Refresh();
            TextureImporter im = AssetImporter.GetAtPath(path) as TextureImporter;

            im.isReadable   = true;
            im.textureShape = TextureImporterShape.TextureCube;
            im.SaveAndReimport();

            return(AssetDatabase.LoadAssetAtPath <Cubemap>(path));
        }
        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();
            }
        }
        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);
        }
    private Entity CreatePlanetEntity(Entity prefabEntity, List <int> usedIndexes)
    {
        Entity spawnedEntity = EntityManager.Instantiate(prefabEntity);

        RenderMesh renderMesh = EntityManager.GetSharedComponentData <RenderMesh>(spawnedEntity);

        UnityEngine.Material mat = new UnityEngine.Material(renderMesh.material);
        mat.SetVector("_RedMinMax", new UnityEngine.Vector4(_random.NextFloat(0f, 1f), _random.NextFloat(0f, 1f)));
        mat.SetVector("_GreenMinMax", new UnityEngine.Vector4(_random.NextFloat(0f, 1f), _random.NextFloat(0f, 1f)));
        mat.SetVector("_BlueMinMax", new UnityEngine.Vector4(_random.NextFloat(0f, 1f), _random.NextFloat(0f, 1f)));
        mat.SetFloat("_NoiseScale", _random.NextFloat(10f, 80f));
        renderMesh.material = mat;
        EntityManager.SetSharedComponentData(spawnedEntity, renderMesh);

        float rndSize           = _random.NextFloat(1f, 2.5f);
        int   rndOrbitRadiusIdx = _random.NextInt(0, SpawnRadiuses.Length);

        while (usedIndexes.Contains(rndOrbitRadiusIdx))
        {
            rndOrbitRadiusIdx = _random.NextInt(0, SpawnRadiuses.Length);
        }

        float rndOrbitRadius = SpawnRadiuses[rndOrbitRadiusIdx];
        int   rndDir         = _random.NextInt(-5, 6);

        rndDir = rndDir * 2 + 1;
        float movementSpeed = math.sign(rndDir) * 1f * rndSize / rndOrbitRadius;
        float rndPosRadians = _random.NextFloat(0f, math.PI);

        EntityManager.AddComponentData(spawnedEntity, new OrbitRadius {
            Value = rndOrbitRadius
        });
        EntityManager.AddComponentData(spawnedEntity, new MovementSpeed {
            Value = movementSpeed
        });
        EntityManager.AddComponentData(spawnedEntity, new OrbitAngle {
            Value = rndPosRadians
        });
        EntityManager.AddComponentData(spawnedEntity, new Scale {
            Value = rndSize
        });
        EntityManager.AddComponentData(spawnedEntity, new ShootCooldown {
            Value = 0.5f
        });
        EntityManager.AddComponentData(spawnedEntity, new ShootTime {
            Value = 0f
        });
        EntityManager.AddComponentData(spawnedEntity, new AddPlanetHUD());
        EntityManager.AddComponentData(spawnedEntity, new ChangeSphereColliderRadius {
            Value = rndSize * 0.5f
        });
        EntityManager.AddComponentData(spawnedEntity, new NextRocketType {
            Value = 0
        });
        BodyMass planetMass = EntityManager.GetComponentData <BodyMass>(spawnedEntity);

        planetMass.Value *= rndSize;
        EntityManager.SetComponentData(spawnedEntity, planetMass);
        SimpleSphereCollider collider = EntityManager.GetComponentData <SimpleSphereCollider>(spawnedEntity);

        collider.Radius = rndSize * 0.5f;
        EntityManager.SetComponentData(spawnedEntity, collider);
        EntityManager.SetComponentData(spawnedEntity,
                                       new Translation {
            Value = new float3(math.cos(_random.NextFloat(0f, 1f) * math.PI), 0f, math.sin(_random.NextFloat(0f, 1f) * math.PI)) * rndOrbitRadius
        });

        usedIndexes.Add(rndOrbitRadiusIdx);

        return(spawnedEntity);
    }
示例#55
0
		void UpdatePreview()
		{
			if (!this) return;
#if BVH
			if (previewBvh)
			{
				if (!entityBuffer.IsCreated) RebuildEntityBuffers();
				if (!bvhNodeBuffer.IsCreated) RebuildBvh();
			}
			else
			{
				sphereBuffer.SafeDispose();
				bvhNodeBuffer.SafeDispose();
				entityBuffer.SafeDispose();

				ActiveEntities.Clear();
			}
#endif // BVH

			if (scene)
			{
				Transform cameraTransform = targetCamera.transform;
				cameraTransform.position = scene.CameraPosition;
				cameraTransform.rotation = Quaternion.LookRotation(scene.CameraTarget - scene.CameraPosition);
				targetCamera.fieldOfView = scene.CameraFieldOfView;
			}

			Action updateDelegate = OnEditorUpdate;
			if (EditorApplication.update.GetInvocationList().All(x => x != (Delegate) updateDelegate))
				EditorApplication.update += OnEditorUpdate;

			if (opaquePreviewCommandBuffer == null)
				opaquePreviewCommandBuffer = new CommandBuffer { name = "World Preview (Opaque)" };
			if (transparentPreviewCommandBuffer == null)
				transparentPreviewCommandBuffer = new CommandBuffer { name = "World Preview (Transparent)" };

			targetCamera.RemoveAllCommandBuffers();

			targetCamera.AddCommandBuffer(CameraEvent.AfterForwardOpaque, opaquePreviewCommandBuffer);
			targetCamera.AddCommandBuffer(CameraEvent.AfterForwardAlpha, transparentPreviewCommandBuffer);

			opaquePreviewCommandBuffer.Clear();
			transparentPreviewCommandBuffer.Clear();

			foreach (UnityEngine.Material material in previewMaterials)
				DestroyImmediate(material);
			previewMaterials.Clear();

			var skybox = targetCamera.GetComponent<Skybox>();
			if (AssetDatabase.IsMainAsset(skybox.material))
				RenderSettings.skybox = skybox.material = new UnityEngine.Material(skybox.material);

			skybox.material.SetColor("_Color1", scene.SkyBottomColor);
			skybox.material.SetColor("_Color2", scene.SkyTopColor);

			EnsurePreviewObjectExists(PrimitiveType.Sphere, ref previewSphere);
			EnsurePreviewObjectExists(PrimitiveType.Quad, ref previewRect);
			EnsurePreviewObjectExists(PrimitiveType.Cube, ref previewBox);

			var previewMeshRenderer = previewSphere.GetComponent<MeshRenderer>();

			CollectActiveEntities();

			opaquePreviewCommandBuffer.EnableShaderKeyword("LIGHTPROBE_SH");
			transparentPreviewCommandBuffer.EnableShaderKeyword("LIGHTPROBE_SH");

			foreach (EntityData entity in ActiveEntities)
			{
				if (!entity.Material) continue;

				bool transparent = entity.Material.Type == MaterialType.Dielectric;
				bool emissive = entity.Material.Type == MaterialType.DiffuseLight;

				Color albedoMainColor = entity.Material.Albedo ? entity.Material.Albedo.MainColor : Color.white;
				Color color = transparent ? albedoMainColor.GetAlphaReplaced(0.5f) : albedoMainColor;
				var material = new UnityEngine.Material(previewMeshRenderer.sharedMaterial) { color = color };
				previewMaterials.Add(material);

				material.SetFloat("_Metallic", entity.Material.Type == MaterialType.Metal ? 1 : 0);
				material.SetFloat("_Glossiness",
					entity.Material.Type == MaterialType.Metal ? 1 - entity.Material.Roughness : transparent ? 1 : 0);
				material.SetTexture("_MainTex", entity.Material.Albedo ? entity.Material.Albedo.Image : null);

				if (transparent)
				{
					material.SetInt("_SrcBlend", (int) BlendMode.One);
					material.SetInt("_DstBlend", (int) BlendMode.OneMinusSrcAlpha);
					material.SetInt("_ZWrite", 0);
					material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
					material.renderQueue = 3000;
				}

				if (emissive)
				{
					material.EnableKeyword("_EMISSION");
					material.SetColor("_EmissionColor",
						entity.Material.Emission ? entity.Material.Emission.MainColor : Color.black);
				}

				CommandBuffer previewCommandBuffer =
					transparent ? transparentPreviewCommandBuffer : opaquePreviewCommandBuffer;

				switch (entity.Type)
				{
					case EntityType.Sphere:
						SphereData s = entity.SphereData;
						previewCommandBuffer.DrawMesh(previewSphere.sharedMesh,
							Matrix4x4.TRS(entity.Position, entity.Rotation, s.Radius * 2 * Vector3.one),
							material, 0,
							material.FindPass("FORWARD"));
						break;

					case EntityType.Rect:
						RectData r = entity.RectData;
						previewCommandBuffer.DrawMesh(previewRect.sharedMesh,
							Matrix4x4.TRS(entity.Position, Quaternion.LookRotation(Vector3.forward) * entity.Rotation,float3(r.Size, 1)),
							material, 0,
							material.FindPass("FORWARD"));
						break;

					case EntityType.Box:
						BoxData b = entity.BoxData;
						previewCommandBuffer.DrawMesh(previewBox.sharedMesh,
							Matrix4x4.TRS(entity.Position, entity.Rotation, b.Size), material, 0,
							material.FindPass("FORWARD"));
						break;
				}
			}
		}
        public Material CreateMaterial(PbrMaterial vpxMaterial, ITextureProvider textureProvider, StringBuilder debug = null)
        {
            Material defaultMaterial = GetDefaultMaterial(vpxMaterial.MapBlendMode);

            var unityMaterial = new Material(GetShader(vpxMaterial));

            unityMaterial.CopyPropertiesFromMaterial(defaultMaterial);
            unityMaterial.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;
            }


            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.
            float metallicValue = 0f;

            if (vpxMaterial.IsMetal && (!vpxMaterial.IsOpacityActive || vpxMaterial.Opacity >= 1))
            {
                metallicValue = 1f;
                debug?.AppendLine("Metallic set to 1.");
            }

            unityMaterial.SetFloat(Metallic, metallicValue);

            // roughness / glossiness
            SetSmoothness(unityMaterial, vpxMaterial.Roughness);

            // map
            if (vpxMaterial.HasMap)
            {
                unityMaterial.SetTexture(BaseMap, textureProvider.GetTexture(vpxMaterial.Map.Name));
            }

            // normal map
            if (vpxMaterial.HasNormalMap)
            {
                unityMaterial.EnableKeyword("_NORMALMAP");
                unityMaterial.EnableKeyword("_NORMALMAP_TANGENT_SPACE");

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

            return(unityMaterial);
        }
        private void WriteUiforms <TValue>(EditorImporter importer, UnityEngine.Material material, SeinMaterialUniform <TValue>[] uniforms)
        {
            foreach (SeinMaterialUniform <TValue> uniform in uniforms)
            {
                var name = uniform.name;
                switch (uniform.type)
                {
                case (ESeinMaterialUniformType.FLOAT):
                    material.SetFloat(name, (uniform as SeinMaterialUniformFloat).value);
                    break;

                case (ESeinMaterialUniformType.INT):
                    material.SetInt(name, (uniform as SeinMaterialUniformInt).value);
                    break;

                case (ESeinMaterialUniformType.SAMPLER_2D):
                    var tex = importer.GetTexture((uniform as SeinMaterialUniformTexture).id.Id);
                    material.SetTexture(name, tex);
                    break;

                // todo: support cubemap
                case (ESeinMaterialUniformType.SAMPLER_CUBE):
                    break;

                case (ESeinMaterialUniformType.FLOAT_VEC2):
                    var fv2 = (uniform as SeinMaterialUniformFloatVec2).value;
                    material.SetFloatArray(name, new List <float> {
                        fv2.x, fv2.y
                    });
                    break;

                case (ESeinMaterialUniformType.FLOAT_VEC3):
                    var fv3 = (uniform as SeinMaterialUniformFloatVec3).value;
                    material.SetFloatArray(name, new List <float> {
                        fv3.x, fv3.y, fv3.z
                    });
                    break;

                case (ESeinMaterialUniformType.FLOAT_VEC4):
                    if (uniform.GetType() == typeof(SeinMaterialUniformColor))
                    {
                        material.SetColor(name, (uniform as SeinMaterialUniformColor).value);
                    }
                    material.SetVector(name, (uniform as SeinMaterialUniformFloatVec4).value);
                    break;

                case (ESeinMaterialUniformType.FLOAT_MAT2):
                    material.SetMatrix(name, (uniform as SeinMaterialUniformFloatMat2).value);
                    break;

                case (ESeinMaterialUniformType.FLOAT_MAT3):
                    material.SetMatrix(name, (uniform as SeinMaterialUniformFloatMat3).value);
                    break;

                case (ESeinMaterialUniformType.FLOAT_MAT4):
                    material.SetMatrix(name, (uniform as SeinMaterialUniformFloatMat4).value);
                    break;

                default:
                    break;
                }
            }
        }
示例#58
0
        protected virtual UnityEngine.Material CreateMaterial(Material def, bool useVertexColors)
        {
            if (def.ContentsWithVC == null || def.ContentsWithoutVC == null)
            {
                Shader shader;

                // get the shader to use for this material
                try
                {
                    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 e)
                {
                    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);

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

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

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

                    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", CreateTexture(texture));
                        material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord);
                    }

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

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

                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));
                    }
                }

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

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

                def.ContentsWithoutVC = material;
                def.ContentsWithVC    = new UnityEngine.Material(material);
                def.ContentsWithVC.EnableKeyword("VERTEX_COLOR_ON");
            }

            return(def.GetContents(useVertexColors));
        }
示例#59
0
        private void ApplyBlendMode(UnityEngine.Material unityMaterial, BlendMode blendMode)
        {
            switch (blendMode)
            {
            case BlendMode.Opaque:

                // set render type
                unityMaterial.SetOverrideTag("RenderType", "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(Surface, 0);                         // 0 = Opaque; 1 = Transparent

                // render queue
                unityMaterial.renderQueue = -1;

                break;

            case BlendMode.Cutout:

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

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

                // required for 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(Surface, 0);                         // 0 = Opaque; 1 = Transparent
                unityMaterial.SetInt(AlphaClip, 1);

                // render queue
                unityMaterial.renderQueue = 2450;

                break;

            case BlendMode.Translucent:

                // disable shader passes
                unityMaterial.SetShaderPassEnabled("SHADOWCASTER", false);

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

                // keywords
                unityMaterial.EnableKeyword("_ALPHAPREMULTIPLY_ON");

                // required for 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(Surface, 1);                       // 0 = Opaque; 1 = Transparent
                unityMaterial.SetFloat(Blend, 1);                         // 0 = Alpha, 1 = Premultiply, 2 = Additive, 3 = Multiply

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

                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#60
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;
            }
            unityMaterial.SetColor(Color, 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(Glossiness, vpxMaterial.Roughness);

            // blend mode
            ApplyBlendMode(unityMaterial, vpxMaterial.MapBlendMode);
            if (vpxMaterial.MapBlendMode == BlendMode.Translucent)
            {
                col.a = Mathf.Min(1, Mathf.Max(0, vpxMaterial.Opacity));
                unityMaterial.SetColor(Color, col);
            }

            // map
            if (table != null && vpxMaterial.HasMap)
            {
                unityMaterial.SetTexture(
                    MainTex,
                    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);
        }