SetTextureScale() public méthode

Sets the placement scale of texture propertyName.

public SetTextureScale ( string propertyName, Vector2 scale ) : void
propertyName string
scale Vector2
Résultat void
    public void SetNewMaterial()
    {
        Renderer _renderer = GetComponent<Renderer>();
        Material newMat = new Material(Shader.Find("Diffuse"));
        //Material newMat = new Material(renderer.sharedMaterial);

        bool baseMaterialHaveNormalMap = _renderer.sharedMaterial.GetTexture("_BumpMap");
        bool baseMaterialHaveCubeMap = _renderer.sharedMaterial.GetTexture("_Cube");

        newMat.SetTexture("_MainTex", _renderer.sharedMaterial.GetTexture("_MainTex"));
        newMat.SetTextureOffset("_MainTex", offset);
        newMat.SetTextureScale("_MainTex", scale);

        if (baseMaterialHaveNormalMap)
        {
            newMat.SetTexture("_BumpMap", _renderer.sharedMaterial.GetTexture("_BumpMap"));
            newMat.SetTextureOffset("_BumpMap", offset);
            newMat.SetTextureScale("_BumpMap", scale);
        }
        if (baseMaterialHaveCubeMap)
        {
            newMat.SetTexture("_Cube", _renderer.sharedMaterial.GetTexture("_Cube"));
            newMat.SetTextureScale("_Cube", scale);
            newMat.SetTextureOffset("_Cube", offset);
        }

        newMat.color = materialColor;

        _renderer.sharedMaterial = newMat;
    }
        private Material CreateMeshMaterial(Mesh mesh)
        {
            Texture2D diffuseTex    = textureManager.GetTexture(mesh.BaseDiffuse);
            Texture2D packedSpecTex = textureManager.GetTexture(mesh.SpecMap);
            Texture2D normalTex     = textureManager.GetTexture(mesh.BumpMap);

            Material material = new Material(source);

            if (diffuseTex != null)
            {
                material.SetTexture("_MainTex", diffuseTex);
                material.SetTextureScale("_MainTex", new Vector2(1, -1));
            }
            if (packedSpecTex != null)
            {
                material.SetTexture("_PackedSpecular", packedSpecTex);
                material.SetTextureScale("_PackedSpecular", new Vector2(1, -1));
            }
            if (normalTex != null)
            {
                material.SetTexture("_BumpMap", normalTex);
                material.SetTextureScale("_BumpMap", new Vector2(1, -1));
            }

            return(material);
        }
Exemple #3
0
	public void Initialize(float nativeResolutionX, float nativeResolutionY, float ratio_scrWidth_To_bgWidth){
		transform.localScale = new Vector3(nativeResolutionX, nativeResolutionY, 1);
		transform.localPosition = new Vector3(nativeResolutionX / 2, nativeResolutionY / 2, 0);
		
		m_material = gameObject.renderer.material;
		m_material.SetTextureScale("_MainTex", new Vector2(0.5f, 1));
		m_material.SetTextureScale("_MainTex", new Vector2(ratio_scrWidth_To_bgWidth, 1));
	}
        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);
        }
        private void ConfigMaterial(MmdMaterial mmdMaterial, MmdUnityConfig config, UnityEngine.Material material, Texture mainTexture)
        {
            material.SetColor("_Color", mmdMaterial.DiffuseColor);
            material.SetFloat("_Opacity", mmdMaterial.DiffuseColor.a);
            material.SetColor("_AmbColor", mmdMaterial.AmbientColor);
            material.SetColor("_SpecularColor", mmdMaterial.SpecularColor);
            material.SetFloat("_Shininess", mmdMaterial.Shiness);
            material.SetFloat("_OutlineWidth", mmdMaterial.EdgeSize);
            material.SetColor("_OutlineColor", mmdMaterial.EdgeColor);
            if (mainTexture != null)
            {
                material.mainTexture      = mainTexture;
                material.mainTextureScale = new Vector2(1, 1);
            }


            if (mmdMaterial.SubTextureType != MmdMaterial.SubTextureTypeEnum.MatSubTexOff)
            {
                var additionalTexture =
                    mmdMaterial.SubTexture == null ? null : _textureLoader.LoadTexture(mmdMaterial.SubTexture);
                if (additionalTexture != null)
                {
                    additionalTexture.wrapMode = TextureWrapMode.Clamp;
                    switch (mmdMaterial.SubTextureType)
                    {
                    case MmdMaterial.SubTextureTypeEnum.MatSubTexSpa:
                        material.SetTexture("_SphereAddTex", additionalTexture);
                        material.SetTextureScale("_SphereAddTex", new Vector2(1, 1));
                        break;

                    case MmdMaterial.SubTextureTypeEnum.MatSubTexSph:
                        material.SetTexture("_SphereMulTex", additionalTexture);
                        material.SetTextureScale("_SphereMulTex", new Vector2(1, 1));
                        break;
                    }
                }
            }

            RefreshShaderKeywords(mmdMaterial, config, material);

            var toonTexture = _textureLoader.LoadTexture(mmdMaterial.Toon);

            if (toonTexture != null)
            {
                toonTexture.wrapMode = TextureWrapMode.Clamp;
                material.SetTexture("_ToonTex", toonTexture);
                material.SetTextureScale("_ToonTex", new Vector2(1, 1));
            }
        }
    void Awake()
    {
        _skyboxMaterial = RenderSettings.skybox;

        _skyboxMaterial.SetTextureScale("_BackTex", new Vector2(camera.pixelWidth / camera.pixelHeight, 1));
        SetOffset();
    }
 public override void OnRestore()
 {
     if (_material = material)
     {
         _material.SetTextureScale(propertyName, _original);
     }
 }
 public void SetCurrentToFrom()
 {
     if (_material = material)
     {
         _material.SetTextureScale(propertyName, from);
     }
 }
 public override void Restore()
 {
     if (null == m_Material)
     {
         return;
     }
     // end if
     if (!string.IsNullOrEmpty(m_property))
     {
         m_Material.SetTextureScale(m_property, m_beginTiling);
     }
     else if (-1 != m_propertyID)
     {
         m_Material.SetTextureScale(m_propertyID, m_beginTiling);
     } // end if
 }
    public void UpdateTile()
    {
        //Replace "GetNeighboursRaycast2D" with the method you want to use to find tile neirghbours
        GetNeighboursRaycast2D();

        SelectTile();

        if (!Application.isPlaying) {
            try {
                renderer.sharedMaterial.SetTextureScale("_BumpMap", new Vector2(1f/8f,1f/6f));
                renderer.sharedMaterial.SetTextureOffset("_BumpMap", new Vector2(1f/8f*sx,1f/6f*sy));
            } catch {}
        } else {
            try {
                var tempMaterial = new Material(renderer.sharedMaterial);
                tempMaterial.mainTexture=renderer.sharedMaterial.mainTexture;
                try {
                tempMaterial.SetTextureScale("_BumpMap", new Vector2(1f/8f,1f/6f));
                tempMaterial.SetTextureOffset("_BumpMap", new Vector2(1f/8f*sx,1f/6f*sy));
                } catch {}
                tempMaterial.shader=renderer.sharedMaterial.shader;
                renderer.sharedMaterial = tempMaterial;
            } catch {}
        }
    }
 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]));
         }
     }
 }
 public void SetCurrentToTo()
 {
     if (_material = material)
     {
         _material.SetTextureScale(propertyName, to);
     }
 }
Exemple #13
0
        public override void OnStart(PartModule.StartState state)
        {
            base.OnStart(state);
            print(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);

            _skinnedMeshRenderer = part.GetComponentInChildren<SkinnedMeshRenderer>();
            _trackSurface = _skinnedMeshRenderer.gameObject;
            _moduleWheel = part.GetComponentInChildren<KFModuleWheel>();

            if (HighLogic.LoadedSceneIsFlight && !Equals(vessel.vesselType, VesselType.Debris))
            {
                trackMaterial = _trackSurface.renderer.material;
                Vector2 trackTiling = trackMaterial.mainTextureScale;
                trackTiling = new Vector2(trackTiling.x * _moduleWheel.directionCorrector, trackTiling.y);
                trackMaterial.SetTextureScale("_MainTex", trackTiling);
                trackMaterial.SetTextureScale("_BumpMap", trackTiling);
            }
        }
		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);
		}
Exemple #15
0
    void Awake()
    {
        _material = GetComponent<Renderer>().material;

        _texture = _material.GetTexture(TexturePropertyName);
        _matSize = System.Math.Min(_texture.width, _texture.height);

        _material.SetTextureScale(TexturePropertyName, new Vector2(1f / ((float)XCells), 1f / ((float)YCells)));

        SetSpriteIndex(0);
    }
        public Material GetMaterial(CnkLOD chunkData)
        {
            Texture2D[] diffuseTextures = new Texture2D[chunkData.Textures.Count];
            Texture2D[] specTextures    = new Texture2D[chunkData.Textures.Count];

            for (int i = 0; i < chunkData.Textures.Count; i++)
            {
                CnkLOD.Texture texture = chunkData.Textures[i];

                Dds diffuse = texture.ColorNXMap;
                Dds spec    = texture.SpecNyMap;

                Texture2D diffuseTex = new Texture2D(diffuse.Width, diffuse.Height, diffuse.TextureFormat, false);
                Texture2D specTex    = new Texture2D(spec.Width, spec.Height, spec.TextureFormat, false);

                diffuseTex.LoadRawTextureData(diffuse.TextureData.Data);
                specTex.LoadRawTextureData(spec.TextureData.Data);

                diffuseTextures[i] = diffuseTex;
                specTextures[i]    = specTex;
            }

            Texture2D materialDiffuse = new Texture2D(1024, 1024);

            materialDiffuse.PackTextures(diffuseTextures, 0, 2048, true);
            materialDiffuse.name = chunkData.Name + " Diffuse";

            Texture2D materialSpec = new Texture2D(1024, 1024);

            materialSpec.PackTextures(specTextures, 0, 2048, true);
            materialSpec.name = chunkData.Name + " Specular";

            Material material = new Material(source);

            material.SetTexture("_MainTex", materialDiffuse);
            material.SetTextureScale("_MainTex", new Vector2(1, -1));
            material.SetTexture("_PackedSpecular", materialSpec);
            material.SetTextureScale("_PackedSpecular", new Vector2(1, -1));

            return(material);
        }
        public override void OnTween(float factor)
        {
            if (_material = material)
            {
                _temp = _material.GetTextureScale(propertyName);

                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;

                _material.SetTextureScale(propertyName, _temp);
            }
        }
        // int zTest, int stencilRef
        //
        public void Initialize(Material sharedOpaqueMaterial, Shader transparentShader)
        {
            data = new List<Data>();

            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(sRenderType, true, sOpaque);
                    if (tag == sTransparent || tag == sTransparentCutout)
                    {
                        Material replacementMat = new Material(transparentShader);
                        //replacementMat.SetInt(ShaderPropertyID._ZTest, zTest);
                        //replacementMat.SetInt(ShaderPropertyID._StencilRef, stencilRef);

                        // To render both sides of the Sprite
                        if (r is SpriteRenderer) { replacementMat.SetInt(ShaderPropertyID._Cull, cullOff); }

                        if (sourceMat.HasProperty(ShaderPropertyID._MainTex))
                        {
                            replacementMat.SetTexture(ShaderPropertyID._MainTex, sourceMat.mainTexture);
                            replacementMat.SetTextureOffset(sMainTex, sourceMat.mainTextureOffset);
                            replacementMat.SetTextureScale(sMainTex, 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);
                }
            }
        }
Exemple #19
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();
			}
        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);
        }
 static int SetTextureScale(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 3);
         UnityEngine.Material obj = (UnityEngine.Material)ToLua.CheckObject(L, 1, typeof(UnityEngine.Material));
         string arg0 = ToLua.CheckString(L, 2);
         UnityEngine.Vector2 arg1 = ToLua.ToVector2(L, 3);
         obj.SetTextureScale(arg0, arg1);
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
 static public int SetTextureScale(IntPtr l)
 {
     try {
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         System.String        a1;
         checkType(l, 2, out a1);
         UnityEngine.Vector2 a2;
         checkType(l, 3, out a2);
         self.SetTextureScale(a1, a2);
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Exemple #23
0
 static public int SetTextureScale(IntPtr l)
 {
     try {
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         System.String        a1;
         checkType(l, 2, out a1);
         UnityEngine.Vector2 a2;
         checkType(l, 3, out a2);
         self.SetTextureScale(a1, a2);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Exemple #24
0
        protected virtual void ApplyTextureTransform(GLTF.Schema.TextureInfo def, UnityEngine.Material mat, string texName)
        {
            GLTF.Schema.Extension extension;
            if (_root.ExtensionsUsed != null &&
                _root.ExtensionsUsed.Contains(ExtTextureTransformExtensionFactory.EXTENSION_NAME) &&
                def.Extensions != null &&
                def.Extensions.TryGetValue(ExtTextureTransformExtensionFactory.EXTENSION_NAME, out extension))
            {
                ExtTextureTransformExtension ext = (ExtTextureTransformExtension)extension;

                Vector2 temp = ext.Offset.ToUnityVector2();
                temp = new Vector2(temp.x, -temp.y);
                mat.SetTextureOffset(texName, temp);

                mat.SetTextureScale(texName, ext.Scale.ToUnityVector2());
            }
        }
Exemple #25
0
        private void ApplyTexture(UnityEngine.Material mat, string propertyName, string textureFile)
        {
            var tex = LoadTexture(textureFile, out var texType);

            if (tex == null)
            {
                return;
            }

            mat.SetTexture(propertyName, tex);

            // Unity is stupid and flips DXT textures upside down (or more likely fails to flip them right side up). so we need to do it ourselves...
            if (texType == TextureHelper.TextureType.DXT)
            {
                mat.SetTextureScale(propertyName, new Vector2(1f, -1f));
            }
        }
Exemple #26
0
        public void Start()
        {
            var prop = internalProp;

            Cpu = part.GetComponent<kOSProcessor>().cpu;

            var size = 0.1f;
            var m = new Mesh();
            m.name = "Scripted_Plane_New_Mesh";
            m.vertices = new Vector3[] { new Vector3(size, -size, 0.01f), new Vector3(size, size, 0.01f), new Vector3(-size, size, 0.01f), new Vector3(-size, -size, 0.01f) };
            m.uv = new Vector2[] { new Vector2(0, 0.4f), new Vector2(0, 1), new Vector2(0.79f, 1), new Vector2(0.79f, 0.4f) };
            m.triangles = new int[] { 0, 1, 2, 0, 2, 3 };
            m.RecalculateNormals();

            MeshFilter mf = prop.FindModelComponents<MeshFilter>()[0];
            prop.FindModelComponents<MeshFilter>()[1].mesh = null;
            mf.mesh = m;

            screenGo = mf.gameObject;

            BoxCollider b = screenGo.GetComponent<BoxCollider>() ?? screenGo.AddComponent<BoxCollider>();
            ClickHandler handler = screenGo.GetComponent<ClickHandler>() ?? screenGo.AddComponent<ClickHandler>();
            handler.OnClick = OnMouseDown;

            foreach (MeshRenderer renderer in prop.FindModelComponents<MeshRenderer>())
            {
                Material mat = new Material(Shader.Find(" Diffuse"));
                mat.SetTexture("_MainTex", InternalDisplayTexture);
                mat.SetTextureScale("_MainTex", new Vector2(1, 1));

                renderer.material = mat;
            }

            foreach (PartModule module in part.Modules)
            {
                if (module is kOSProcessor)
                {
                    var k = (kOSProcessor)module;

                    k.InternalDisplayTexture = InternalDisplayTexture;
                }
            }
        }
Exemple #27
0
 public static void ApplyValueLerp(AMMaterialTrack.ValueType valueType, string prop, int propId, Material mat, AMMaterialKey fromKey, AMMaterialKey toKey, float t)
 {
     switch(valueType) {
         case AMMaterialTrack.ValueType.Float:
         case AMMaterialTrack.ValueType.Range:
             mat.SetFloat(propId, Mathf.Lerp(fromKey.val, toKey.val, t));
             break;
         case AMMaterialTrack.ValueType.Vector:
             mat.SetVector(propId, Vector4.Lerp(fromKey.vector, toKey.vector, t));
             break;
         case AMMaterialTrack.ValueType.Color:
             mat.SetColor(propId, Color.Lerp(fromKey.color, toKey.color, t));
             break;
         case AMMaterialTrack.ValueType.TexOfs:
             mat.SetTextureOffset(prop, Vector2.Lerp(fromKey.texOfs, toKey.texOfs, t));
             break;
         case AMMaterialTrack.ValueType.TexScale:
             mat.SetTextureScale(prop, Vector2.Lerp(fromKey.texScale, toKey.texScale, t));
             break;
     }
 }
    private void InitDefaultVariables()
    {
        currentRenderer = GetComponent<Renderer>();
        if (currentRenderer==null)
            throw new Exception("UvTextureAnimator can't get renderer");
        if (!currentRenderer.enabled)
            currentRenderer.enabled = true;
        allCount = 0;
        animationStoped = false;
        animationLifeTime = TilesX * TilesY / AnimationFPS;
        count = TilesY * TilesX;
        index = TilesX - 1;
        var offset = Vector3.zero;
        StartFrameOffset = StartFrameOffset - (StartFrameOffset / count) * count;
        var size = new Vector2(1f / TilesX, 1f / TilesY);

        if (currentRenderer!=null) {
            instanceMaterial = currentRenderer.material;
            instanceMaterial.SetTextureScale("_MainTex", size);
            instanceMaterial.SetTextureOffset("_MainTex", offset);
        }
    }
Exemple #29
0
    void OnPostRender()
    {
        if (takeScreen){
            int height = Screen.height;
            int width = Screen.width;
            texture = new Texture2D(width, height);
            texture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
            texture.Apply();

            material = new Material (Shader.Find("Self-Illumin/Diffuse"));
            material.SetTextureScale("Tiling", new Vector2(100,0));
            material.mainTexture = texture;

            takeScreen = false;
            try{
                TImer time = GameObject.FindGameObjectWithTag("Timer").GetComponent<TImer>();
            }
            catch (NullReferenceException){
                Debug.Log ("ughhhh");
            }
            callback();
        }
    }
Exemple #30
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);
        }
	public static void ConfigureNewMaterialToMatchOld(Material newMat, Material original){
		if (original == null){
			Debug.LogWarning("Original material is null, could not copy properties to " + newMat + ". Setting shader to " + newMat.shader);
			return;
		}
		newMat.shader = original.shader;					
		newMat.CopyPropertiesFromMaterial(original);
		ShaderTextureProperty[] texPropertyNames = MB3_TextureCombiner.shaderTexPropertyNames;
		for (int j = 0; j < texPropertyNames.Length; j++){
			Vector2 scale = Vector2.one;
			Vector2 offset = Vector2.zero;
			if (newMat.HasProperty(texPropertyNames[j].name)){
				newMat.SetTextureOffset(texPropertyNames[j].name,offset);
				newMat.SetTextureScale(texPropertyNames[j].name,scale);
			}
		}
	}
		Rect[] __CreateAtlasesMBTexturePacker(ProgressUpdateDelegate progressInfo, int numAtlases, List<MB_TexSet> distinctMaterialTextures, List<string> texPropertyNames, Material resultMaterial, Texture2D[] atlases, MB2_EditorMethodsInterface textureEditorMethods, int _padding){
			Rect[] uvRects;
			if (distinctMaterialTextures.Count == 1){
				if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Only one image per atlas. Will re-use original texture");
				uvRects = new Rect[1];
				uvRects[0] = new Rect(0f,0f,1f,1f);
				for (int i = 0; i < numAtlases; i++){
					MeshBakerMaterialTexture dmt = distinctMaterialTextures[0].ts[i];
					atlases[i] = dmt.t;
					resultMaterial.SetTexture(texPropertyNames[i],atlases[i]);
					resultMaterial.SetTextureScale(texPropertyNames[i],dmt.scale);
					resultMaterial.SetTextureOffset(texPropertyNames[i],dmt.offset);
				}
			} else {
				List<Vector2> imageSizes = new List<Vector2>();
				for (int i = 0; i < distinctMaterialTextures.Count; i++){
					imageSizes.Add(new Vector2(distinctMaterialTextures[i].idealWidth, distinctMaterialTextures[i].idealHeight));	
				}
				MB2_TexturePacker tp = new MB2_TexturePacker();
				int atlasSizeX = 1;
				int atlasSizeY = 1;
				
				//todo add sanity warnings for huge atlasesr
				int atlasMaxDimension = 4096;
				
				if (textureEditorMethods != null) atlasMaxDimension = textureEditorMethods.GetMaximumAtlasDimension();
				
				uvRects = tp.GetRects(imageSizes,atlasMaxDimension,_padding,out atlasSizeX, out atlasSizeY);
				if (LOG_LEVEL >= MB2_LogLevel.info) Debug.Log("Generated atlas will be " + atlasSizeX + "x" + atlasSizeY + " (Max atlas size for platform: " + atlasMaxDimension + ")");
				for (int i = 0; i < numAtlases; i++){
					GC.Collect();
					if (progressInfo != null) progressInfo("Creating Atlas '" + texPropertyNames[i] + "'", .01f);
					Color[] atlasPixels = new Color[atlasSizeX * atlasSizeY];//atlas.GetPixels();
					for (int j = 0; j < atlasPixels.Length; j++) atlasPixels[j] = Color.clear;
					for (int j = 0; j < distinctMaterialTextures.Count; j++){
						if (LOG_LEVEL >= MB2_LogLevel.trace) MB2_Log.Trace("Adding texture {0} to atlas {1}", distinctMaterialTextures[j].ts[i].t == null ? "null" : distinctMaterialTextures[j].ts[i].t.ToString(),texPropertyNames[i]);
						Rect r = uvRects[j];
						Texture2D t = distinctMaterialTextures[j].ts[i].t;
						int x = Mathf.RoundToInt(r.x * atlasSizeX);
						int y = Mathf.RoundToInt(r.y * atlasSizeY);
						int ww = Mathf.RoundToInt(r.width * atlasSizeX);
						int hh = Mathf.RoundToInt(r.height * atlasSizeY);
						if (ww == 0 || hh == 0) Debug.LogError("Image in atlas has no height or width");
						if (textureEditorMethods != null) textureEditorMethods.SetReadWriteFlag(t, true, true);
						if (progressInfo != null) progressInfo("Copying to atlas: '" + distinctMaterialTextures[j].ts[i].t + "'", .02f);
						CopyScaledAndTiledToAtlas(distinctMaterialTextures[j].ts[i],x,y,ww,hh,fixOutOfBoundsUVs,maxTilingBakeSize,atlasPixels,atlasSizeX,progressInfo);
					}
					if (progressInfo != null) progressInfo("Applying changes to atlas: '" + texPropertyNames[i] + "'", .03f);
					Texture2D atlas = new Texture2D(atlasSizeX, atlasSizeY,TextureFormat.ARGB32, true);
					atlas.SetPixels(atlasPixels);
					atlas.Apply();
					if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Saving atlas " + texPropertyNames[i] + " w=" + atlas.width + " h=" + atlas.height);
					atlases[i] = atlas;
					if (progressInfo != null) progressInfo("Saving atlas: '" + texPropertyNames[i] + "'", .04f);
					if (saveAtlasesAsAssets && textureEditorMethods != null){
						textureEditorMethods.SaveAtlasToAssetDatabase(atlases[i], texPropertyNames[i], i, resultMaterial);
					} else {
						resultMaterial.SetTexture(texPropertyNames[i], atlases[i]);
					}
					resultMaterial.SetTextureOffset(texPropertyNames[i], Vector2.zero);
					resultMaterial.SetTextureScale(texPropertyNames[i],Vector2.one);
					_destroyTemporaryTextures(); // need to save atlases before doing this				
				}
			}
			return uvRects;
		}
		Rect[] __CreateAtlasesUnityTexturePacker(ProgressUpdateDelegate progressInfo, int numAtlases, List<MB_TexSet> distinctMaterialTextures, List<string> texPropertyNames, Material resultMaterial, Texture2D[] atlases, MB2_EditorMethodsInterface textureEditorMethods, int _padding){
			Rect[] uvRects;
			if (distinctMaterialTextures.Count == 1){
				if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Only one image per atlas. Will re-use original texture");
				uvRects = new Rect[1];
				uvRects[0] = new Rect(0f,0f,1f,1f);
				for (int i = 0; i < numAtlases; i++){
					MeshBakerMaterialTexture dmt = distinctMaterialTextures[0].ts[i];
					atlases[i] = dmt.t;
					resultMaterial.SetTexture(texPropertyNames[i],atlases[i]);
					resultMaterial.SetTextureScale(texPropertyNames[i],dmt.scale);
					resultMaterial.SetTextureOffset(texPropertyNames[i],dmt.offset);
				}
			} else {
				long estArea = 0;
				int atlasSizeX = 1;
				int atlasSizeY = 1;
				uvRects = null;
				for (int i = 0; i < numAtlases; i++){ //i is an atlas "MainTex", "BumpMap" etc...
					if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.LogWarning("Beginning loop " + i + " num temporary textures " + _temporaryTextures.Count);
					for(int j = 0; j < distinctMaterialTextures.Count; j++){ //j is a distinct set of textures one for each of "MainTex", "BumpMap" etc...
						MB_TexSet txs = distinctMaterialTextures[j];
						
						int tWidth = txs.idealWidth;
						int tHeight = txs.idealHeight;
		
						Texture2D tx = txs.ts[i].t;
						if (tx == null) tx = txs.ts[i].t = _createTemporaryTexture(tWidth,tHeight,TextureFormat.ARGB32, true);
		
						if (progressInfo != null)
							progressInfo("Adjusting for scale and offset " + tx, .01f);	
						if (textureEditorMethods != null) textureEditorMethods.SetReadWriteFlag(tx, true, true); 
						tx = getAdjustedForScaleAndOffset2(txs.ts[i]);				
						
						//create a resized copy if necessary
						if (tx.width != tWidth || tx.height != tHeight) {
							if (progressInfo != null) progressInfo("Resizing texture '" + tx + "'", .01f);
							if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.LogWarning("Copying and resizing texture " + texPropertyNames[i] + " from " + tx.width + "x" + tx.height + " to " + tWidth + "x" + tHeight);
							if (textureEditorMethods != null) textureEditorMethods.SetReadWriteFlag((Texture2D) tx, true, true);
							tx = _resizeTexture((Texture2D) tx,tWidth,tHeight);
						}
						txs.ts[i].t = tx;
					}
		
					Texture2D[] texToPack = new Texture2D[distinctMaterialTextures.Count];
					for (int j = 0; j < distinctMaterialTextures.Count;j++){
						Texture2D tx = distinctMaterialTextures[j].ts[i].t;
						estArea += tx.width * tx.height;
						texToPack[j] = tx;
					}
					
					if (textureEditorMethods != null) textureEditorMethods.CheckBuildSettings(estArea);
			
					if (Math.Sqrt(estArea) > 3500f){
						if (LOG_LEVEL >= MB2_LogLevel.warn) Debug.LogWarning("The maximum possible atlas size is 4096. Textures may be shrunk");
					}
					atlases[i] = new Texture2D(1,1,TextureFormat.ARGB32,true);
					if (progressInfo != null)
						progressInfo("Packing texture atlas " + texPropertyNames[i], .25f);	
					if (i == 0){
						if (progressInfo != null)
							progressInfo("Estimated min size of atlases: " + Math.Sqrt(estArea).ToString("F0"), .1f);			
						if (LOG_LEVEL >= MB2_LogLevel.info) Debug.Log("Estimated atlas minimum size:" + Math.Sqrt(estArea).ToString("F0"));
						
						_addWatermark(texToPack);			
						
						if (distinctMaterialTextures.Count == 1){ //don't want to force power of 2 so tiling will still work
							uvRects = new Rect[1] {new Rect(0f,0f,1f,1f)};
							atlases[i] = _copyTexturesIntoAtlas(texToPack,_padding,uvRects,texToPack[0].width,texToPack[0].height);
						} else {
							int maxAtlasSize = 4096;
							uvRects = atlases[i].PackTextures(texToPack,_padding,maxAtlasSize,false);
						}
						
						if (LOG_LEVEL >= MB2_LogLevel.info) Debug.Log("After pack textures atlas size " + atlases[i].width + " " + atlases[i].height);
						atlasSizeX = atlases[i].width;
						atlasSizeY = atlases[i].height;	
						atlases[i].Apply();
					} else {
						if (progressInfo != null)
							progressInfo("Copying Textures Into: " + texPropertyNames[i], .1f);					
						atlases[i] = _copyTexturesIntoAtlas(texToPack,_padding,uvRects, atlasSizeX, atlasSizeY);
					}
					
					if (saveAtlasesAsAssets && textureEditorMethods != null){
						textureEditorMethods.SaveAtlasToAssetDatabase(atlases[i], texPropertyNames[i], i, resultMaterial);
					} else {
						resultMaterial.SetTexture(texPropertyNames[i], atlases[i]);
					}
					resultMaterial.SetTextureOffset(texPropertyNames[i], Vector2.zero);
					resultMaterial.SetTextureScale(texPropertyNames[i],Vector2.one);
					
					_destroyTemporaryTextures(); // need to save atlases before doing this
					GC.Collect();
				}
			}
			return uvRects;
		}	
Exemple #34
0
 public void ApplyValue(AMMaterialTrack.ValueType valueType, string prop, int propId, Material mat)
 {
     switch(valueType) {
         case AMMaterialTrack.ValueType.Float:
         case AMMaterialTrack.ValueType.Range:
             mat.SetFloat(propId, val);
             break;
         case AMMaterialTrack.ValueType.Vector:
             mat.SetVector(propId, vector);
             break;
         case AMMaterialTrack.ValueType.Color:
             mat.SetColor(propId, color);
             break;
         case AMMaterialTrack.ValueType.TexEnv:
             mat.SetTexture(propId, texture);
             break;
         case AMMaterialTrack.ValueType.TexOfs:
             mat.SetTextureOffset(prop, texOfs);
             break;
         case AMMaterialTrack.ValueType.TexScale:
             mat.SetTextureScale(prop, texScale);
             break;
     }
 }
			// Constructor
			public HighlightingRendererCache(Renderer rend, Material[] mats, Material sharedOpaqueMaterial, int renderQueue, float zTest, float stencilRef)
			{
				rendererCached = rend;
				goCached = rend.gameObject;
				sourceMaterials = mats;
				replacementMaterials = new Material[mats.Length];
				transparentMaterialIndexes = new List<int>();
				
				for (int i = 0; i < mats.Length; i++)
				{
					Material sourceMat = mats[i];
					if (sourceMat == null) { continue; }
					
					string tag = sourceMat.GetTag("RenderType", true, "Opaque");
					if (tag == "Transparent" || tag == "TransparentCutout")
					{
						Material replacementMat = new Material(transparentShader);
						replacementMat.renderQueue = renderQueue;
						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);
						
						replacementMaterials[i] = replacementMat;
						transparentMaterialIndexes.Add(i);
					}
					else
					{
						replacementMaterials[i] = sharedOpaqueMaterial;
					}
				}
			}
 /// <summary>
 /// Restores the material values
 /// </summary>
 /// <param name="m">Material</param>
 /// <param name="values">Set of values</param>
 public void SetValues(Material m, IEnumerable<StoredValue> values)
 {
     foreach (var v in values) {
         switch (v.property.type) {
             case MaterialProperty.PropertyType.Color:
                 m.SetColor(v.property.name, (Color)v.value[0]);
                 Debug.Log(v.property.name);
                 break;
             case MaterialProperty.PropertyType.Float:
                 m.SetFloat(v.property.name, (float)v.value[0]);
                 break;
             case MaterialProperty.PropertyType.Range:
                 m.SetFloat(v.property.name, (float)v.value[0]);
                 break;
             case MaterialProperty.PropertyType.TexEnv:
                 m.SetTexture(v.property.name, (Texture)v.value[0]);
                 m.SetTextureOffset(v.property.name, (Vector2)v.value[1]);
                 m.SetTextureScale(v.property.name, (Vector2)v.value[2]);
                 break;
             case MaterialProperty.PropertyType.Vector:
                 m.SetVector(v.property.name, (Vector4)v.value[0]);
                 break;
             default:
                 Debug.LogError("Unsupported type: " + v.property.type.ToString());
                 break;
         }
     }
 }
Exemple #37
0
 public static void SetMainTextureScaleOffset(this Material _this, Vector4 st)
 {
     _this.SetTextureScale(PropId_MainTexture, new Vector2(st.x, st.y));
     _this.SetTextureOffset(PropId_MainTexture, new Vector2(st.z, st.w));
 }
		// Constructor
		public HighlightingRendererCache(Renderer rend, Material[] mats, Material sharedOpaqueMaterial, bool writeDepth)
		{
			rendererCached = rend;
			goCached = rend.gameObject;
			sourceMaterials = mats;
			replacementMaterials = new Material[mats.Length];
			transparentMaterialIndexes = new List<int>();
			
			for (int i = 0; i < mats.Length; i++)
			{
				Material sourceMat = mats[i];
				if (sourceMat == null)
				{
					continue;
				}
				string tag = sourceMat.GetTag("RenderType", true);
				if (tag == "Transparent" || tag == "TransparentCutout")
				{
					Material replacementMat = new Material(writeDepth ? transparentZShader : transparentShader);
					if (sourceMat.HasProperty("_MainTex"))
					{
						replacementMat.SetTexture("_MainTex", sourceMat.mainTexture);
						replacementMat.SetTextureOffset("_MainTex", sourceMat.mainTextureOffset);
						replacementMat.SetTextureScale("_MainTex", sourceMat.mainTextureScale);
					}
					
					replacementMat.SetFloat("_Cutoff", sourceMat.HasProperty("_Cutoff") ? sourceMat.GetFloat("_Cutoff") : transparentCutoff);
					
					replacementMaterials[i] = replacementMat;
					transparentMaterialIndexes.Add(i);
				}
				else
				{
					replacementMaterials[i] = sharedOpaqueMaterial;
				}
			}
		}
Exemple #39
0
        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)
                {
                    logger?.Error(LogCode.UVMulti);
                }

                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
            }

            if (material.HasProperty(mainTexPropId))
            {
                material.SetTextureOffset(mainTexPropId, textureST.zw);
                material.SetTextureScale(mainTexPropId, textureST.xy);
            }
            material.SetTextureOffset(propertyId, textureST.zw);
            material.SetTextureScale(propertyId, textureST.xy);
            material.SetVector(mainTexScaleTransform, textureST);
        }
        Rect[] __CreateAtlasesMBTexturePackerFast(ProgressUpdateDelegate progressInfo, int numAtlases, List<MB_TexSet> distinctMaterialTextures, List<ShaderTextureProperty> texPropertyNames, bool[] allTexturesAreNullAndSameColor, Material resultMaterial, Texture2D[] atlases, MB2_EditorMethodsInterface textureEditorMethods, int _padding)
        {
            Rect[] uvRects;
            if (distinctMaterialTextures.Count == 1){
                if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Only one image per atlas. Will re-use original texture");
                uvRects = new Rect[1];
                uvRects[0] = new Rect(0f,0f,1f,1f);
                for (int i = 0; i < numAtlases; i++){
                    MeshBakerMaterialTexture dmt = distinctMaterialTextures[0].ts[i];
                    atlases[i] = dmt.t;
                    resultMaterial.SetTexture(texPropertyNames[i].name,atlases[i]);
                    resultMaterial.SetTextureScale(texPropertyNames[i].name,dmt.scale);
                    resultMaterial.SetTextureOffset(texPropertyNames[i].name,dmt.offset);
                }
            } else {
                List<Vector2> imageSizes = new List<Vector2>();
                for (int i = 0; i < distinctMaterialTextures.Count; i++){
                    imageSizes.Add(new Vector2(distinctMaterialTextures[i].idealWidth, distinctMaterialTextures[i].idealHeight));
                }
                MB2_TexturePacker tp = new MB2_TexturePacker();
                tp.doPowerOfTwoTextures = _meshBakerTexturePackerForcePowerOfTwo;
                int atlasSizeX = 1;
                int atlasSizeY = 1;

                //todo add sanity warnings for huge atlasesr
                int atlasMaxDimension = _maxAtlasSize;

                //if (textureEditorMethods != null) atlasMaxDimension = textureEditorMethods.GetMaximumAtlasDimension();

                uvRects = tp.GetRects(imageSizes,atlasMaxDimension,_padding,out atlasSizeX, out atlasSizeY);
                if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Generated atlas will be " + atlasSizeX + "x" + atlasSizeY + " (Max atlas size for platform: " + atlasMaxDimension + ")");

                //create a game object
                GameObject renderAtlasesGO = new GameObject("MBrenderAtlasesGO");
                MB3_AtlasPackerRenderTexture atlasRenderTexture = renderAtlasesGO.AddComponent<MB3_AtlasPackerRenderTexture>();
                for (int i = 0; i < numAtlases; i++){
                    Texture2D atlas = null;
                    if (allTexturesAreNullAndSameColor[i]){
                        atlas = null;
                        if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Not creating atlas for " + texPropertyNames[i].name + " because textures are null and default value parameters are the same.");
                    } else {
                        GC.Collect();
                        if (progressInfo != null) progressInfo("Creating Atlas '" + texPropertyNames[i].name + "'", .01f);
                        // ===========
                        // configure it
                        atlasRenderTexture.width = atlasSizeX;
                        atlasRenderTexture.height = atlasSizeY;
                        atlasRenderTexture.padding = _padding;
                        atlasRenderTexture.rects = uvRects;
                        atlasRenderTexture.textureSets = distinctMaterialTextures;
                        atlasRenderTexture.indexOfTexSetToRender = 0;
                        // call render on it
                        atlas = atlasRenderTexture.OnRenderAtlas();
                        // destroy it
                        // =============
                        if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Saving atlas " + texPropertyNames[i].name + " w=" + atlas.width + " h=" + atlas.height);
                    }
                    atlases[i] = atlas;
                    if (progressInfo != null) progressInfo("Saving atlas: '" + texPropertyNames[i].name + "'", .04f);
                    if (_saveAtlasesAsAssets && textureEditorMethods != null){
                        textureEditorMethods.SaveAtlasToAssetDatabase(atlases[i], texPropertyNames[i], i, resultMaterial);
                    } else {
                        resultMaterial.SetTexture(texPropertyNames[i].name, atlases[i]);
                    }
                    resultMaterial.SetTextureOffset(texPropertyNames[i].name, Vector2.zero);
                    resultMaterial.SetTextureScale(texPropertyNames[i].name,Vector2.one);
                    _destroyTemporaryTextures(); // need to save atlases before doing this
                }
            }
            return uvRects;
        }
Exemple #41
0
        /// <summary>
        /// マテリアルをUnity用に変換する
        /// </summary>
        /// <returns>Unity用マテリアル</returns>
        /// <param name='material'>PMX用マテリアル</param>
        Material ConvertMaterial(PMXFormat.Material material)
        {
            //先にテクスチャ情報を検索
            Texture2D main_texture = null;
            if (material.usually_texture_index < format_.texture_list.texture_file.Length) {
                string texture_file_name = format_.texture_list.texture_file[material.usually_texture_index];
                string path = format_.meta_header.folder + "/" + texture_file_name;
                main_texture = (Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));
            }

            //マテリアルに設定
            Material result = new Material(Shader.Find(GetMmdShaderPath(material, main_texture)));

            // シェーダに依って値が有ったり無かったりするが、設定してもエラーに為らない様なので全部設定
            result.SetColor("_Color", material.diffuse_color);
            result.SetColor("_AmbColor", material.ambient_color);
            result.SetFloat("_Opacity", material.diffuse_color.a);
            result.SetColor("_SpecularColor", material.specular_color);
            result.SetFloat("_Shininess", material.specularity);
            // エッジ
            result.SetFloat("_OutlineWidth", material.edge_size);
            result.SetColor("_OutlineColor", material.edge_color);

            // スフィアテクスチャ
            if (material.sphere_texture_index < format_.texture_list.texture_file.Length) {
                string sphere_texture_file_name = format_.texture_list.texture_file[material.sphere_texture_index];
                string path = format_.meta_header.folder + "/" + sphere_texture_file_name;
                Texture2D sphere_texture = (Texture2D)UnityEditor.AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D));

                switch (material.sphere_mode) {
                case PMXFormat.Material.SphereMode.AddSphere: // 加算
                    result.SetTexture("_SphereAddTex", sphere_texture);
                    result.SetTextureScale("_SphereAddTex", new Vector2(1, -1));
                    break;
                case PMXFormat.Material.SphereMode.MulSphere: // 乗算
                    result.SetTexture("_SphereMulTex", sphere_texture);
                    result.SetTextureScale("_SphereMulTex", new Vector2(1, -1));
                    break;
                case PMXFormat.Material.SphereMode.SubTexture: // サブテクスチャ
                    //サブテクスチャ用シェーダーが無いので設定しない
                    break;
                default:
                    //empty.
                    break;

                }
            }

            // トゥーンテクスチャ
            {
                string toon_texture_name = null;
                if (0 < material.common_toon) {
                    //共通トゥーン
                    toon_texture_name = "toon" + material.common_toon.ToString("00") + ".bmp";
                } else if (material.toon_texture_index < format_.texture_list.texture_file.Length) {
                    //自前トゥーン
                    toon_texture_name = format_.texture_list.texture_file[material.toon_texture_index];
                }
                if (!string.IsNullOrEmpty(toon_texture_name)) {
                    string resource_path = UnityEditor.AssetDatabase.GetAssetPath(Shader.Find("MMD/HalfLambertOutline"));
                    Texture2D toon_texture = (Texture2D)UnityEditor.AssetDatabase.LoadAssetAtPath(resource_path, typeof(Texture2D));
                    result.SetTexture("_ToonTex", toon_texture);
                    result.SetTextureScale("_ToonTex", new Vector2(1, -1));
                }
            }

            // テクスチャが空でなければ登録
            if (null != main_texture) {
                result.mainTexture = main_texture;
                result.mainTextureScale = new Vector2(1, -1);
            }

            return result;
        }
        Rect[] __CreateAtlasesMBTexturePacker(ProgressUpdateDelegate progressInfo, int numAtlases, List<MB_TexSet> distinctMaterialTextures, List<ShaderTextureProperty> texPropertyNames, bool[] allTexturesAreNullAndSameColor, Material resultMaterial, Texture2D[] atlases, MB2_EditorMethodsInterface textureEditorMethods, int _padding)
        {
            Rect[] uvRects;
            if (distinctMaterialTextures.Count == 1){
                if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Only one image per atlas. Will re-use original texture");
                uvRects = new Rect[1];
                uvRects[0] = new Rect(0f,0f,1f,1f);
                for (int i = 0; i < numAtlases; i++){
                    MeshBakerMaterialTexture dmt = distinctMaterialTextures[0].ts[i];
                    atlases[i] = dmt.t;
                    resultMaterial.SetTexture(texPropertyNames[i].name,atlases[i]);
                    resultMaterial.SetTextureScale(texPropertyNames[i].name,dmt.scale);
                    resultMaterial.SetTextureOffset(texPropertyNames[i].name,dmt.offset);
                }
            } else {
                List<Vector2> imageSizes = new List<Vector2>();
                for (int i = 0; i < distinctMaterialTextures.Count; i++){
                    imageSizes.Add(new Vector2(distinctMaterialTextures[i].idealWidth, distinctMaterialTextures[i].idealHeight));
                }
                MB2_TexturePacker tp = new MB2_TexturePacker();
                tp.doPowerOfTwoTextures = _meshBakerTexturePackerForcePowerOfTwo;
                int atlasSizeX = 1;
                int atlasSizeY = 1;

                //todo add sanity warnings for huge atlasesr
                int atlasMaxDimension = _maxAtlasSize;

                //if (textureEditorMethods != null) atlasMaxDimension = textureEditorMethods.GetMaximumAtlasDimension();

                uvRects = tp.GetRects(imageSizes,atlasMaxDimension,_padding,out atlasSizeX, out atlasSizeY);
                if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Generated atlas will be " + atlasSizeX + "x" + atlasSizeY + " (Max atlas size for platform: " + atlasMaxDimension + ")");
                for (int i = 0; i < numAtlases; i++){
                    Texture2D atlas = null;
                    if (allTexturesAreNullAndSameColor[i]){
                        atlas = null;
                        if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Not creating atlas for " + texPropertyNames[i].name + " because textures are null and default value parameters are the same.");
                    } else {
                        GC.Collect();
                        if (progressInfo != null) progressInfo("Creating Atlas '" + texPropertyNames[i].name + "'", .01f);
                        //use a jagged array because it is much more efficient in memory
                        Color[][] atlasPixels = new Color[atlasSizeY][];
                        for (int j = 0; j < atlasPixels.Length; j++){
                            atlasPixels[j] = new Color[atlasSizeX];
                        }
                        bool isNormalMap = false;
                        if (texPropertyNames[i].isNormalMap) isNormalMap = true;
            //						for (int j = 0; j < atlasPixels.Length; j++) {
            //							for (int k = 0; k < atlasSizeX; k++){
            //								atlasPixels[j][k] = GetColorIfNoTexture(
            //								if (isNormalMap){
            //									atlasPixels[j][k] = new Color(.5f,.5f,1f); //neutral bluish for normal maps
            //								} else {
            //									atlasPixels[j][k] = Color.clear;
            //								}
            //							}
            //						}
                        for (int j = 0; j < distinctMaterialTextures.Count; j++){
                            if (LOG_LEVEL >= MB2_LogLevel.trace) MB2_Log.Trace("Adding texture {0} to atlas {1}", distinctMaterialTextures[j].ts[i].t == null ? "null" : distinctMaterialTextures[j].ts[i].t.ToString(),texPropertyNames[i]);
                            Rect r = uvRects[j];
                            Texture2D t = distinctMaterialTextures[j].ts[i].t;
                            int x = Mathf.RoundToInt(r.x * atlasSizeX);
                            int y = Mathf.RoundToInt(r.y * atlasSizeY);
                            int ww = Mathf.RoundToInt(r.width * atlasSizeX);
                            int hh = Mathf.RoundToInt(r.height * atlasSizeY);
                            if (ww == 0 || hh == 0) Debug.LogError("Image in atlas has no height or width");
                            if (textureEditorMethods != null) textureEditorMethods.SetReadWriteFlag(t, true, true);
                            if (progressInfo != null) progressInfo("Copying to atlas: '" + distinctMaterialTextures[j].ts[i].t + "'", .02f);
                            CopyScaledAndTiledToAtlas(distinctMaterialTextures[j].ts[i],x,y,ww,hh,_fixOutOfBoundsUVs,_maxTilingBakeSize,atlasPixels,atlasSizeX,isNormalMap,progressInfo);
                        }
                        if (progressInfo != null) progressInfo("Applying changes to atlas: '" + texPropertyNames[i].name + "'", .03f);
                        atlas = new Texture2D(atlasSizeX, atlasSizeY,TextureFormat.ARGB32, true);
                        for (int j = 0; j < atlasPixels.Length; j++){
                            atlas.SetPixels(0,j,atlasSizeX,1,atlasPixels[j]);
                        }
                        atlas.Apply();
                        if (LOG_LEVEL >= MB2_LogLevel.debug) Debug.Log("Saving atlas " + texPropertyNames[i].name + " w=" + atlas.width + " h=" + atlas.height);
                    }
                    atlases[i] = atlas;
                    if (progressInfo != null) progressInfo("Saving atlas: '" + texPropertyNames[i].name + "'", .04f);
                    if (_saveAtlasesAsAssets && textureEditorMethods != null){
                        textureEditorMethods.SaveAtlasToAssetDatabase(atlases[i], texPropertyNames[i], i, resultMaterial);
                    } else {
                        resultMaterial.SetTexture(texPropertyNames[i].name, atlases[i]);
                    }
                    resultMaterial.SetTextureOffset(texPropertyNames[i].name, Vector2.zero);
                    resultMaterial.SetTextureScale(texPropertyNames[i].name,Vector2.one);
                    _destroyTemporaryTextures(); // need to save atlases before doing this
                }
            }
            return uvRects;
        }
        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 CreatePrefab()
		{
			if (prefabAtmosphere == null)
			{
				prefabAtmosphere = new GameObject ("RefractiveAtmosphere");
				prefabAtmosphere.SetActive (false);
				var mf = prefabAtmosphere.AddComponent<MeshFilter> ();
				var mr = prefabAtmosphere.AddComponent<MeshRenderer> ();
				mr.castShadows = false;
				mr.receiveShadows = false;

				var material = new Material (Shaders.RefractiveAtmosphere);
				var _normals = new Texture2D (4, 4, TextureFormat.ARGB32, false);
				_normals.LoadImage (Textures.RefractiveAtmosphereNormals);
				material.SetTexture ("_BumpMap", _normals);
				material.SetTextureScale ("_BumpMap", new Vector2 (4f, 4f));
				material.SetVector ("_BumpMapOffset", new Vector4 (0, 0, 1, 0));

				mr.sharedMaterial = material;

				var sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
				var sphereMesh = sphere.GetComponent<MeshFilter> ().mesh;
				DestroyImmediate (sphere);
				mf.sharedMesh = sphereMesh;

				var behaviour = prefabAtmosphere.AddComponent<RefractiveAtmosphere> ();

				prefabAtmosphere.transform.localScale = Vector3.one * 1250f;

				DontDestroyOnLoad (prefabAtmosphere);
			}
		}
Exemple #45
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;
		}
Exemple #46
0
 private void _SetMatTex(Material mat, string matPropName, Texture tex, Vector2 tiling, Vector2 offset)
     // 设置材质指定属性的纹理
 {
     //if (!string.IsNullOrEmpty(texturePath))
     //{
     //    Texture tex;
     //if (CachedTextures.TryGetValue(texturePath, out tex))
     {
         mat.SetTexture(matPropName, tex);
         mat.SetTextureScale(matPropName, tiling);
         mat.SetTextureOffset(matPropName, offset);
     }
     //else
     //    Logger.LogError("找不到纹理: {0}", texturePath);
     //}
 }