SetVector() 공개 메소드

Set a named vector value.

public SetVector ( int nameID, Vector4 vector ) : void
nameID int Property name ID, use Shader.PropertyToID to get it.
vector Vector4 Vector value to set.
리턴 void
예제 #1
0
파일: Init.cs 프로젝트: TheMunro/space
	void InitMaterial(Material mat)
	{
		Vector3 invWaveLength4 = new Vector3(1.0f / Mathf.Pow(m_waveLength.x, 4.0f), 1.0f / Mathf.Pow(m_waveLength.y, 4.0f), 1.0f / Mathf.Pow(m_waveLength.z, 4.0f));
		float scale = 1.0f / (m_outerRadius - m_innerRadius);

		mat.SetVector("v3LightPos", m_sun.transform.forward*-1.0f);
		mat.SetVector("v3InvWavelength", invWaveLength4);
		mat.SetFloat("fOuterRadius", m_outerRadius);
		mat.SetFloat("fOuterRadius2", m_outerRadius*m_outerRadius);
		mat.SetFloat("fInnerRadius", m_innerRadius);
		mat.SetFloat("fInnerRadius2", m_innerRadius*m_innerRadius);
		mat.SetFloat("fKrESun", m_kr*m_ESun);
		mat.SetFloat("fKmESun", m_km*m_ESun);
		mat.SetFloat("fKr4PI", m_kr*4.0f*Mathf.PI);
		mat.SetFloat("fKm4PI", m_km*4.0f*Mathf.PI);
		mat.SetFloat("fScale", scale);
		mat.SetFloat("fScaleDepth", m_scaleDepth);
		mat.SetFloat("fScaleOverScaleDepth", scale/m_scaleDepth);
		mat.SetFloat("fHdrExposure", m_hdrExposure);
		mat.SetFloat("g", m_g);
		mat.SetFloat("g2", m_g*m_g);
		mat.SetVector("v3LightPos", m_sun.transform.forward*-1.0f);
		mat.SetVector("v3Translate", transform.localPosition);

	}
예제 #2
0
 private void InitPortraitProperties(ref Material material)
 {
     material.SetVector("_Center", Center);
     material.SetVector("_Scale", Scale);
     material.SetVector("_ScaleIn", ScaleIn);
     material.SetVector("_HmdWarpParam", new Vector4(K0, K1, K2, 0));
 }
예제 #3
0
        private static void TrySetTextureTransform(
            Schema.TextureInfo textureInfo,
            UnityEngine.Material material,
            int propertyId,
            bool flipY = false
            )
        {
            // Scale (x,y) and Transform (z,w)
            float4 textureST = new float4(
                1, 1, // scale
                0, 0  // transform
                );

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

                float cos = 1;
                float sin = 0;

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

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

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

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

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

            material.SetVector(mainTexScaleTransform, textureST);
        }
 static void SetMatrix(Material material)
 {
     var r = material.GetVector("_Euler");
     var q = Quaternion.Euler(r.x, r.y, r.z);
     var m = Matrix4x4.TRS(Vector3.zero, q, Vector3.one);
     material.SetVector("_Rotation1", m.GetRow(0));
     material.SetVector("_Rotation2", m.GetRow(1));
     material.SetVector("_Rotation3", m.GetRow(2));
 }
예제 #5
0
파일: Sky.cs 프로젝트: Togene/BeCalm
    void InitMaterial(Material mat)
    {
        mat.SetTexture("_Transmittance", m_transmittance);
        mat.SetTexture("_Inscatter", m_inscatter);

        mat.SetFloat("SUN_INTENSITY", m_sunIntensity);
        mat.SetVector("SUN_DIR", m_sun.transform.forward*-1.0f);

        //Dont change this
        mat.SetVector("EARTH_POS", new Vector3(0.0f, 6360010.0f, 0.0f));
    }
예제 #6
0
 private void Start()
 {
     Debug.Assert(_chargeSpeed > 0f);
     Material mat = new Material(Shader.Find(_shaderName));
     _citizenBodyRenderer.material = mat;
     _currThres = _bottomThres;
     mat.SetVector("_PlanePos", new Vector4(_planeHeight, 0, 0, 1));
     mat.SetVector("_PlaneNormal", new Vector4(-1, 0, 0, 0));
     mat.SetFloat("_ThresDist", _currThres);
     mat.SetTexture("_BeforeTex", VFXManager.Instance.RandomRiotTex());
     mat.SetTexture("_AfterTex", _afterTex);
 }
 IEnumerator UpdateVisibility(Material FogMat)
 {
     while (active)
     {
         FogMat.SetVector(puckPos, _puck.position);
         for (int i = 0; i < _allies.Count; i++)
         {
             FogMat.SetVector(witchPos[i], _allies[i].position);
         }
         yield return null;
     }
 }
예제 #8
0
        //        protected override void Start()
        public override void Start()
        {
            base.Start();

            m_initJacobiansMat=new Material(ShaderTool.GetMatFromShader2("CompiledInitJacobians.shader"));
            m_whiteCapsPrecomputeMat=new Material(ShaderTool.GetMatFromShader2("CompiledWhiteCapsPrecompute.shader"));

            m_initJacobiansMat.SetTexture("_Spectrum01", m_spectrum01);
            m_initJacobiansMat.SetTexture("_Spectrum23", m_spectrum23);
            m_initJacobiansMat.SetTexture("_WTable", m_WTable);
            m_initJacobiansMat.SetVector("_Offset", m_offset);
            m_initJacobiansMat.SetVector("_InverseGridSizes", m_inverseGridSizes);
        }
예제 #9
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);
 }
        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));
        }
 public override void Restore()
 {
     if (null == m_Material)
     {
         return;
     }
     // end if
     if (!string.IsNullOrEmpty(m_property))
     {
         m_Material.SetVector(m_property, m_beginVector);
     }
     else if (-1 != m_propertyID)
     {
         m_Material.SetVector(m_propertyID, m_beginVector);
     } // end if
 }
예제 #12
0
		void Awake()
		{
			MeshFilter mf = GetComponent<MeshFilter>();

			if(mf == null || mf.sharedMesh == null)
				highlightType = HighlightType.Bounds;

			switch( highlightType )
			{
				case HighlightType.Wireframe:
					mesh = GenerateWireframe( mf.sharedMesh );
					material = pb_BuiltinResource.GetMaterial(pb_BuiltinResource.mat_Wireframe);
					break;

				case HighlightType.Bounds:

					Bounds bounds = mf != null && mf.sharedMesh != null ? mf.sharedMesh.bounds : new Bounds(Vector3.zero, Vector3.one);
					mesh = GenerateBounds( bounds );
					material = pb_BuiltinResource.GetMaterial(pb_BuiltinResource.mat_UnlitVertexColor);
					break;

				case HighlightType.Glow:
					mesh = mf.sharedMesh;
					material = pb_BuiltinResource.GetMaterial(pb_BuiltinResource.mat_Highlight);
					break;
			}

			mesh.RecalculateBounds();
			material.SetVector("_Center", mesh.bounds.center);
			
			Graphics.DrawMesh(mesh, transform.localToWorldMatrix, material, 0);
		}
예제 #13
0
 static public int SetVector(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (matchType(l, argc, 2, typeof(int), typeof(UnityEngine.Vector4)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.Int32         a1;
             checkType(l, 2, out a1);
             UnityEngine.Vector4 a2;
             checkType(l, 3, out a2);
             self.SetVector(a1, a2);
             pushValue(l, true);
             return(1);
         }
         else if (matchType(l, argc, 2, typeof(string), typeof(UnityEngine.Vector4)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.String        a1;
             checkType(l, 2, out a1);
             UnityEngine.Vector4 a2;
             checkType(l, 3, out a2);
             self.SetVector(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));
     }
 }
예제 #14
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);
		}
	}
    static int SetVector(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(int), typeof(UnityEngine.Vector4)))
            {
                UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1);
                int arg0 = (int)LuaDLL.lua_tonumber(L, 2);
                UnityEngine.Vector4 arg1 = ToLua.ToVector4(L, 3);
                obj.SetVector(arg0, arg1);
                return(0);
            }
            else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(string), typeof(UnityEngine.Vector4)))
            {
                UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1);
                string arg0 = ToLua.ToString(L, 2);
                UnityEngine.Vector4 arg1 = ToLua.ToVector4(L, 3);
                obj.SetVector(arg0, arg1);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Material.SetVector"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
예제 #16
0
    // Note we're exploiting some sort of Unity "magic" whereby by appending an integer
    // to a uniform array name selects the specific array element based on that integer.

    // Unity 5.4 and above provides an interface which renders this class unnecessary.

    // For more info: http://www.alanzucconi.com/2016/01/27/arrays-shaders-heatmaps-in-unity3d/

    // (It would be nice to use generics here, but unfortunately Unity itself does not
    // provide a generic interface for setting a single parameter.)

    public static void Vector3(UnityEngine.Material material, string name, Vector3[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            material.SetVector(name + i.ToString(), array[i]);
        }
    }
 static void TrySetTextureTransform(
     Schema.TextureInfo textureInfo,
     UnityEngine.Material material,
     int propertyId
     )
 {
     if (textureInfo.extensions != null && textureInfo.extensions.KHR_texture_transform != null)
     {
         var tt = textureInfo.extensions.KHR_texture_transform;
         if (tt.texCoord != 0)
         {
             Debug.LogError("Multiple UV sets are not supported!");
         }
         if (tt.offset != null)
         {
             material.SetTextureOffset(propertyId, new Vector2(tt.offset[0], 1 - tt.offset[1]));
         }
         if (tt.rotation != 0)
         {
             float cos = Mathf.Cos(tt.rotation);
             float sin = Mathf.Sin(tt.rotation);
             material.SetVector(StandardShaderHelper.mainTexRotatePropId, new Vector4(cos, -sin, sin, cos));
             material.EnableKeyword(StandardShaderHelper.KW_UV_ROTATION);
         }
         if (tt.scale != null)
         {
             material.SetTextureScale(propertyId, new Vector2(tt.scale[0], -tt.scale[1]));
         }
     }
 }
예제 #18
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);
    }
예제 #19
0
    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);
    }
예제 #20
0
 public override void OnRestore()
 {
     if (_material = material)
     {
         _material.SetVector(propertyID, _original);
     }
 }
예제 #21
0
 public void SetCurrentToTo()
 {
     if (_material = material)
     {
         _material.SetVector(propertyID, to);
     }
 }
예제 #22
0
 static public int SetVector(IntPtr l)
 {
     try{
         if (matchType(l, 2, typeof(System.String), typeof(UnityEngine.Vector4)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.String        a1;
             checkType(l, 2, out a1);
             UnityEngine.Vector4 a2;
             checkType(l, 3, out a2);
             self.SetVector(a1, a2);
             return(0);
         }
         else if (matchType(l, 2, typeof(System.Int32), typeof(UnityEngine.Vector4)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.Int32         a1;
             checkType(l, 2, out a1);
             UnityEngine.Vector4 a2;
             checkType(l, 3, out a2);
             self.SetVector(a1, a2);
             return(0);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
예제 #23
0
 public void SetCurrentToFrom()
 {
     if (_material = material)
     {
         _material.SetVector(propertyID, from);
     }
 }
예제 #24
0
        /// <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;
                    }
                }
            }

        }
예제 #25
0
		public void SetUniforms(Material mat)
		{
			//Sets uniforms that this or other gameobjects may need
			if(mat == null) return;
			
			mat.SetFloat("_Sun_Intensity", m_sunIntensity);
			mat.SetVector("_Sun_WorldSunDir", GetDirection());
		}
예제 #26
0
		public static void bindRandomValueTable(Material mat, string paramName, int inputFaceSize) {
			for(int i=0; i<sampleCount; ++i) {
				mat.SetVector(paramName + i, randomValues[i]);
			}
			float imp = inputFaceSize*inputFaceSize/(float)sampleCount;
			imp = 0.5f*Mathf.Log(imp, 2f) + 0.5f; //+0.5 is a fudge factor, ideally 0, suggested at 1, we use 0.5
			mat.SetFloat("_ImportantLog", imp);
		}
예제 #27
0
    // Called by camera to get lens correction values w/Chromatic aberration
    public Material GetMaterial_CA(bool portrait)
    {
        material_CA = (Material)Resources.Load("Scripts/OVRScripts/OVRImageEffects/OVRLensCorrection_CA", typeof(Material));
        // Set material properties
        SetPortraitProperties(portrait, ref material_CA);

        material_CA.SetVector("_HmdWarpParam",	_HmdWarpParam);

        Vector4 _CA = _ChromaticAberration;
        float rSquaredCoeffR = _CA[1] - _CA[0];
        float rSquaredCoeffB = _CA[3] - _CA[2];
        _CA[1] = rSquaredCoeffR;
        _CA[3] = rSquaredCoeffB;

        material_CA.SetVector("_ChromaticAberration", _CA);

        return material_CA;
    }
예제 #28
0
	void Start () {
		deformingMesh = GetComponent<MeshFilter>().mesh;
		originalVertices = deformingMesh.vertices;
		displacedVertices = new Vector3[originalVertices.Length];
		for (int i = 0; i < originalVertices.Length; i++) {
			displacedVertices[i] = originalVertices[i];
		}
		vertexVelocities = new Vector3[originalVertices.Length];

        meshRenderer = GetComponent<MeshRenderer>();
        material = meshRenderer.material;
		
        getPoles ();
        Vector3 leftPole = transform.TransformPoint(displacedVertices[leftPoleInd]);
        Vector3 rightPole = transform.TransformPoint(displacedVertices[rightPoleInd]);
        material.SetVector("_LeftPole", new Vector4(leftPole.x, leftPole.y, leftPole.z));
        material.SetVector("_RightPole", new Vector4(rightPole.x, rightPole.y, rightPole.z));
	}
예제 #29
0
    void DrawShaft(MeshFilter obj, Vector4 lightPos,Material exMat)
    {
        exMat.SetVector("litPos", lightPos);

        Mesh ms = obj.sharedMesh;
        Transform tr = obj.transform;
        exMat.SetPass(0);
        Graphics.DrawMeshNow(ms, tr.localToWorldMatrix);
    }
    // Use this for initialization
    void Start () {
        CSKernel = computeShader.FindKernel("CSMainGrid");

        if(Debugrender) {
            PointMaterial = new Material(PointShader);
            PointMaterial.SetVector("_worldPos", transform.position);
        }

        InitializeBuffers();	
	}
예제 #31
0
 private RenderTexture DownsampleDepth(int ssX, int ssY, Texture src, Material mat, int downsampleFactor)
 {
     Vector2 v = new Vector2(1f / (float)ssX, 1f / (float)ssX);
     ssX /= downsampleFactor;
     ssY /= downsampleFactor;
     RenderTexture temporary = RenderTexture.GetTemporary(ssX, ssY, 0);
     mat.SetVector("_PixelSize", v);
     Graphics.Blit(src, temporary, mat);
     return temporary;
 }
예제 #32
0
        public override Material CloneMaterial(Material src, int nth)
        {
            var instance_texture = m_world.GetInstanceTexture();

            Material m = new Material(src);
            m.SetInt("g_batch_begin", nth * m_instances_par_batch);
            m.SetTexture("g_instance_data", instance_texture);

            Vector4 ts = new Vector4(
                1.0f / instance_texture.width,
                1.0f / instance_texture.height,
                instance_texture.width,
                instance_texture.height);
            m.SetVector("g_instance_data_size", ts);

            if (m_hdr)
            {
                m.SetInt("_SrcBlend", (int)BlendMode.One);
                m.SetInt("_DstBlend", (int)BlendMode.One);
            }
            else
            {
                m.SetInt("_SrcBlend", (int)BlendMode.DstColor);
                m.SetInt("_DstBlend", (int)BlendMode.Zero);
            }

            if (m_enable_shadow)
            {
                m.EnableKeyword("ENABLE_SHADOW");
                switch (m_sample)
                {
                    case Sample.Fast:
                        m.EnableKeyword("QUALITY_FAST");
                        m.DisableKeyword("QUALITY_MEDIUM");
                        m.DisableKeyword("QUALITY_HIGH");
                        break;
                    case Sample.Medium:
                        m.DisableKeyword("QUALITY_FAST");
                        m.EnableKeyword("QUALITY_MEDIUM");
                        m.DisableKeyword("QUALITY_HIGH");
                        break;
                    case Sample.High:
                        m.DisableKeyword("QUALITY_FAST");
                        m.DisableKeyword("QUALITY_MEDIUM");
                        m.EnableKeyword("QUALITY_HIGH");
                        break;
                }
            }
            else
            {
                m.DisableKeyword("ENABLE_SHADOW");
            }

            return m;
        }
예제 #33
0
    RenderTexture DownsampleDepth(int ssX, int ssY, Texture src, Material mat, int downsampleFactor)
    {
        Vector2 offset = new Vector2(1.0f / ssX, 1.0f / ssX);
          ssX /= downsampleFactor;
          ssY /= downsampleFactor;
          RenderTexture lowDepth = RenderTexture.GetTemporary(ssX, ssY, 0);
          mat.SetVector("_PixelSize", offset);
          Graphics.Blit(src, lowDepth, mat);

          return lowDepth;
    }
예제 #34
0
        public static void UploadColorGradingParams(Material mat, float numSlices)
        {
            float invNumSlices = 1.0f / numSlices;
            Vector2 LUTSize = new Vector2(numSlices*numSlices, numSlices);

            Vector4 colorGradingParams1 = new Vector4();
            colorGradingParams1.x = 1.0f * invNumSlices - 1.0f / LUTSize.x;
            colorGradingParams1.y = 1.0f - 1.0f * invNumSlices;
            colorGradingParams1.z = numSlices - 1.0f;
            colorGradingParams1.w = numSlices;

            Vector4 colorGradingParams2 = new Vector4();
            colorGradingParams2.x = 0.5f / LUTSize.x;
            colorGradingParams2.y = 0.5f / LUTSize.y;
            colorGradingParams2.z = 0.0f;
            colorGradingParams2.w = invNumSlices;

            mat.SetVector("_ColorGradingParams1", colorGradingParams1);
            mat.SetVector("_ColorGradingParams2", colorGradingParams2);
        }
        static void TrySetTextureTransform(
            Schema.TextureInfo textureInfo,
            UnityEngine.Material material,
            int propertyId,
            bool flipY = false
            )
        {
            Vector2 offset = Vector2.zero;
            Vector2 scale  = Vector2.one;

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

                float cos = 1;
                float sin = 0;

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

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

            material.SetTextureOffset(propertyId, offset);
            material.SetTextureScale(propertyId, scale);
        }
예제 #36
0
 public void BindVirtualCameraParams(Material mat, CameraParameters cameraParams, float focalDistance, float halfResWidth, bool isFirstRender)
 {
     mat.SetVector("_VirtualCameraParams1", new Vector4
     {
         x = 1f / (cameraParams.focalLength * 1000f),
         y = cameraParams.fNumber,
         z = cameraParams.shutterSpeed,
         w = (!isFirstRender) ? (1f - Mathf.Exp(-Time.deltaTime * cameraParams.adaptionSpeed)) : 1f
     });
     mat.SetVector("_VirtualCameraParams2", new Vector4
     {
         x = cameraParams.exposureCompensation + 1.8f,
         y = cameraParams.focalLength,
         z = focalDistance,
         w = ScionUtility.CoCToPixels(halfResWidth)
     });
     mat.SetVector("_VirtualCameraParams3", new Vector4
     {
         x = Mathf.Pow(2f, cameraParams.minMaxExposure.x),
         y = Mathf.Pow(2f, cameraParams.minMaxExposure.y)
     });
 }
예제 #37
0
	// SetPortraitProperties
	private void SetPortraitProperties(bool portrait, ref Material m)
	{
		if(portrait == true)
		{
			Vector2 tmp = Vector2.zero;
			tmp.x = _Center.y;
			tmp.y = _Center.x;
			m.SetVector("_Center",	tmp);
			tmp.x = _Scale.y;
			tmp.y = _Scale.x;
			m.SetVector("_Scale",	tmp);
			tmp.x = _ScaleIn.y;
			tmp.y = _ScaleIn.x;
			m.SetVector("_ScaleIn",	tmp);
		}
		else
		{
			m.SetVector("_Center",	_Center);
			m.SetVector("_Scale",	_Scale);
			m.SetVector("_ScaleIn",	_ScaleIn);
		}
	}
예제 #38
0
        public override void OnTween(float factor)
        {
            if (_material = material)
            {
                _temp = _material.GetVector(propertyID);

                if (mask.GetBit(0)) _temp.x = from.x + (to.x - from.x) * factor;
                if (mask.GetBit(1)) _temp.y = from.y + (to.y - from.y) * factor;
                if (mask.GetBit(2)) _temp.z = from.z + (to.z - from.z) * factor;
                if (mask.GetBit(3)) _temp.w = from.w + (to.w - from.w) * factor;

                _material.SetVector(propertyID, _temp);
            }
        }
예제 #39
0
        public ResourceObject Parse(ByteBuffer bb)
        {
            Schema.Material _material = Schema.Material.GetRootAsMaterial(bb);

            ResourceObjectMaterial result = new ResourceObjectMaterial(_material.Shader);

            UnityEngine.Material material = result.Unity3dObject as UnityEngine.Material;
            material.name = _material.Name;

            for (int i = 0; i < _material.PropertiesLength; i++)
            {
                Schema.ShaderProperty p = _material.GetProperties(i);
                switch (p.Type)
                {
                case ShaderPropertyType.Float:
                case ShaderPropertyType.Range:
                {
                    Schema.ShaderPropertyFloat f = p.GetValue <Schema.ShaderPropertyFloat>(fObj);
                    material.SetFloat(p.Names, f.Value);
                }
                break;

                case ShaderPropertyType.Color:
                {
                    Schema.ShaderPropertyColor c = p.GetValue <Schema.ShaderPropertyColor>(cObj);
                    material.SetColor(p.Names, new UnityEngine.Color(c.Color.R, c.Color.G, c.Color.B, c.Color.A));
                }
                break;

                case ShaderPropertyType.Vector:
                {
                    Schema.ShaderPropertyVector v = p.GetValue <Schema.ShaderPropertyVector>(vObj);
                    material.SetVector(p.Names, new Vector4(v.Vector.X, v.Vector.Y, v.Vector.Z, v.Vector.W));
                }
                break;

                case ShaderPropertyType.TexEnv:
                {
                    Schema.ShaderPropertyTexture t = p.GetValue <Schema.ShaderPropertyTexture>(tObj);
                    material.SetTextureOffset(p.Names, new Vector2(t.Offset.X, t.Offset.Y));
                    material.SetTextureScale(p.Names, new Vector2(t.Scale.X, t.Scale.Y));
                    result.AddTexture(t.Name, p.Names);
                }
                break;
                }
            }

            return(result);
        }
예제 #40
0
        public override DrawStackNode Allocate(DrawInfo info, SurfaceTexture tex, ref int stackID)
        {
            // Stack required.

            // Allocate a target stack now:
            int       targetStack = stackID;
            DrawStack stack       = tex.GetStack(targetStack, info);

            stackID++;

            float curAmplitude = 1f;
            float curFrequency = (float)Frequency.GetValue(0, 0);
            float lacunarity   = (float)Lacunarity.GetValue(0, 0);
            float persistence  = (float)Persistence.GetValue(0, 0);
            int   mOctaveCount = (int)OctaveCount.GetValue(0, 0);

            Material[] materials = new Material[mOctaveCount];

            // Stack up "OctaveCount" quads.
            for (int currentOctave = 0; currentOctave < mOctaveCount; currentOctave++)
            {
                // Update seed:
                long seed = (Seed + currentOctave) & 0xffffffff;

                // And a material.
                UnityEngine.Material material = GetMaterial(TypeID, SubMaterialID);

                // _Data (Seed, Frequency, Amplitude, Jitter):
                material.SetVector("_Data", new Vector4(seed, curFrequency, curAmplitude, 0f));

                // Add to set:
                materials[currentOctave] = material;

                curFrequency *= lacunarity;
                curAmplitude *= persistence;
            }

            // Create our node:
            BlockStackNode bsn = new BlockStackNode();

            DrawStore     = bsn;
            bsn.Mesh      = info.Mesh;
            bsn.Materials = materials;
            bsn.Stack     = stack;

            return(bsn);
        }
예제 #41
0
        public override DrawStackNode Allocate(DrawInfo info, SurfaceTexture tex, ref int stackID)
        {
            // RandomVectors required.
            if (RandomVectors == null)
            {
                RandomVectors = Resources.Load("Loonim-Random-Vectors") as Texture2D;
            }

            // Stack required.

            // Get a material:
            UnityEngine.Material material = GetMaterial(TypeID, SubMaterialID);

            // _Data:
            material.SetVector(
                "_Data",
                DataVector
                );

            // Allocate a target stack now:
            int       targetStack = stackID;
            DrawStack stack       = tex.GetStack(targetStack, info);

            stackID++;

            // Allocate sources:
            AllocateSources(material, info, tex, targetStack, 2);

            // Random vectors are always SRC2:
            material.SetTexture("_Src2", RandomVectors);

            // Create our node:
            MaterialStackNode matNode = DrawStore as MaterialStackNode;

            if (matNode == null)
            {
                matNode      = new MaterialStackNode();
                DrawStore    = matNode;
                matNode.Mesh = info.Mesh;
            }

            matNode.Material = material;
            matNode.Stack    = stack;

            return(matNode);
        }
예제 #42
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);
            }
        }
예제 #43
0
        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);
        }
예제 #44
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);
        }
        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;
                }
            }
        }
예제 #46
0
    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);
    }