The material class.

Inheritance: UnityEngine.Object
コード例 #1
0
 public void SetCurrentToFrom()
 {
     if (_material = material)
     {
         _material.SetTextureScale(propertyName, from);
     }
 }
コード例 #2
0
	protected MaterialDesc[] ProcessSharedMaterials( Material[] mats )
	{
		MaterialDesc[] matsDesc = new MaterialDesc [ mats.Length ];
		for ( int i = 0; i < mats.Length; i++ )
		{
			matsDesc[ i ].material = mats[ i ];
			bool legacyCoverage = ( mats[ i ].GetTag( "RenderType", false ) == "TransparentCutout" );
		#if UNITY_4
			bool isCoverage = legacyCoverage;
			matsDesc[ i ].coverage = mats[ i ].HasProperty( "_MainTex" ) && isCoverage;
		#else
			bool isCoverage = legacyCoverage || mats[ i ].IsKeywordEnabled( "_ALPHATEST_ON" );
			matsDesc[ i ].propertyBlock = new MaterialPropertyBlock();
			matsDesc[ i ].coverage = mats[ i ].HasProperty( "_MainTex" ) && isCoverage;
		#endif
			matsDesc[ i ].cutoff = mats[ i ].HasProperty( "_Cutoff" );

			if ( isCoverage && !matsDesc[ i ].coverage && !m_materialWarnings.Contains( matsDesc[ i ].material ) )
			{
				Debug.LogWarning( "[AmplifyMotion] TransparentCutout material \"" + matsDesc[ i ].material.name + "\" {" + matsDesc[ i ].material.shader.name + "} not using _MainTex standard property." );
				m_materialWarnings.Add( matsDesc[ i ].material );
			}
		}
		return matsDesc;
	}
コード例 #3
0
 public void SetCurrentToTo()
 {
     if (_material = material)
     {
         _material.SetTextureScale(propertyName, to);
     }
 }
コード例 #4
0
 public void SetFromToCurrent()
 {
     if (_material = material)
     {
         from = _material.GetTextureScale(propertyName);
     }
 }
コード例 #5
0
        public void SetMaterial(Material mat)
        {
            Material = mat;

            for (int index = 0; index < Renderers.Length; index++)
                Renderers[index].sharedMaterial = Material;
        }
コード例 #6
0
        private void ImportTexturesFromXml(XDocument xml)
        {
            var texData = xml.Root.Elements("ImportTexture");
            foreach (var tex in texData)
            {
                string name = tex.Attribute("filename").Value;
                string data = tex.Value;

                // The data is gzip compressed base64 string. We need the raw bytes.
                //byte[] bytes = ImportUtils.GzipBase64ToBytes(data);
                byte[] bytes = ImportUtils.Base64ToBytes(data);

                // Save and import the texture asset
                {
                    string pathToSave = GetTextureAssetPath(name);
                    ImportUtils.ReadyToWrite(pathToSave);
                    File.WriteAllBytes(pathToSave, bytes);
                    AssetDatabase.ImportAsset(pathToSave, ImportAssetOptions.ForceSynchronousImport);
                }

                // Create a material if needed in prepartion for the texture being successfully imported
                {
                    string materialPath = GetMaterialAssetPath(name);
                    Material material = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
                    if (material == null)
                    {
                        // We need to create the material afterall
                        // Use our custom shader
                        material = new Material(Shader.Find("Tiled/TextureTintSnap"));
                        ImportUtils.ReadyToWrite(materialPath);
                        AssetDatabase.CreateAsset(material, materialPath);
                    }
                }
            }
        }
コード例 #7
0
ファイル: FourierGPU.cs プロジェクト: kharbechteinn/Scatterer
	public FourierGPU(int size)
	{	
		if(size > 256)
		{
			Debug.Log("FourierGPU::FourierGPU - fourier grid size must not be greater than 256, changing to 256");
			size = 256;
		}
		
		if(!Mathf.IsPowerOfTwo(size))
		{
			Debug.Log("FourierGPU::FourierGPU - fourier grid size must be pow2 number, changing to nearest pow2 number");
			size = Mathf.NextPowerOfTwo(size);
		}
		
//		Shader shader = Shader.Find("Math/Fourier");
		Shader shader = ShaderTool.GetShader2 ("CompiledFourier.shader");

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

		m_size = size; //must be pow2 num
		m_fsize = (float)m_size;
		m_passes = (int)(Mathf.Log(m_fsize)/Mathf.Log(2.0f));
		
		m_butterflyLookupTable = new Texture2D[m_passes];
		
		ComputeButterflyLookupTable();
		
		m_fourier.SetFloat("_Size", m_fsize);
	}
コード例 #8
0
	void Start()
	{

		m_depthBufferShader = ShaderTool.GetMatFromShader2 ("CompiledViewDepthBuffer.shader");
//		GetComponent<Camera>().depthTextureMode |= DepthTextureMode.DepthNormals;
		GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth;
	}
コード例 #9
0
ファイル: Minimap.cs プロジェクト: JJJohan/RTS
        public Minimap()
        {
            // Init minimap
            m_gameObject = new GameObject();
            m_icons = new List<MinimapIcon>();
            m_origBounds = new Rect(1920 - 224, 16, 209, 184);
            UpdateBounds();

            // Create the minimap render texture
            m_minimap = (Material)UnityEngine.Resources.Load("textures/minimapRT");

            // Create Camera
            m_camera = m_gameObject.AddComponent<Camera>();
            m_camera.isOrthoGraphic = true;
            m_camera.orthographicSize = 500f;
            m_camera.nearClipPlane = 10f;
            m_camera.farClipPlane = 1000f;
            m_camera.clearFlags = CameraClearFlags.Color;
            m_camera.backgroundColor = Color.black;
            m_camera.targetTexture = (RenderTexture)m_minimap.mainTexture;
            m_camera.rect = new Rect(0f, 0f, 1f, 1f);
            m_camera.cullingMask = 1 << LayerMask.NameToLayer("Terrain");
            m_gameObject.transform.position = new Vector3(0f, 100f, 0f);
            m_gameObject.transform.eulerAngles = new Vector3(90f, 0f, 0f);
            m_gameObject.layer = LayerMask.NameToLayer("Minimap");
            m_gameObject.name = "Minimap";
        }
コード例 #10
0
ファイル: OceanProperties.cs プロジェクト: Moxcr/armage
 public OceanProperties(string texture, Vector2 textureScale, string material, Vector3 scale)
 {
     this.texture = Resources.Load<Texture2D> (texture);
     this.textureScale = textureScale;
     this.material = Resources.Load<Material> (material);
     this.scale = scale;
 }
コード例 #11
0
        public static void Create(Vector3 position, Vector3 normal)
        {
            var effect = new GameObject("Particle Effect");
            effect.transform.position = position;
            effect.transform.rotation = Quaternion.LookRotation(normal);

            var particleSystem = effect.AddComponent<ParticleSystem>();
            particleSystem.startLifetime = 0.4f;
            particleSystem.startSpeed = 15;
            particleSystem.startSize = 0.13f;
            particleSystem.emissionRate = 100;
            particleSystem.loop = false;

            Material material = new Material(Shader.Find(" Diffuse"));
            material.color = Color.black;
            effect.GetComponent<ParticleSystemRenderer>().sharedMaterial = material;

            GameObject.Destroy(effect, 0.2f);

            /*for (int i = 0; i < 30; i++)
            {
                ParticleSystem.Particle p = new ParticleSystem.Particle();
                p.velocity = normal*5;
                //p.position = position;
                p.lifetime = 5;
                particleSystem.Emit(p);
            }
            particleSystem.Play();*/
        }
コード例 #12
0
ファイル: Bloom.cs プロジェクト: mittens/demos_unity
        private void OnDisable()
        {
            if (m_Material != null)
                DestroyImmediate(m_Material);

            m_Material = null;
        }
コード例 #13
0
        public static SMaterial FromMaterial(Material mat)
        {
            if (mat == null)
                return null;

            Shader shader = mat.shader;
            if (shader == null)
                return null;

            SMaterial result = new SMaterial();
            result.instanceID = mat.GetInstanceID();
            result.materialName = mat.name;
            result.shaderName = shader.name;

            ShaderProperties.Info info = ShaderPropertyHelper.GetShaderInfo(shader.name);

            if (info != null){
                ComposedByteStream rawData = new ComposedByteStream();

                int iMax = info.propertyNames.Length;
                for (int i = 0; i < iMax; i++)
                {
                    string propName = info.propertyNames[i];
                    switch (info.propertyTypes[i])
                    {
                        case ShaderProperties.PropType.Color:
                            Color color = mat.GetColor(propName);
                            rawData.AddStream(new float[] { color.r, color.g, color.b, color.a });
                            break;

                        case ShaderProperties.PropType.Range:
                        case ShaderProperties.PropType.Float:
                            rawData.AddStream(new float[] { mat.GetFloat(propName) });
                            break;

                        case ShaderProperties.PropType.TexEnv:
                            Texture texture = mat.GetTexture(propName);
                            Vector2 offset = mat.GetTextureOffset(propName);
                            Vector2 scale = mat.GetTextureScale(propName);

                            rawData.AddStream(new int[] { texture != null ? texture.GetInstanceID() : -1 });
                            rawData.AddStream(texture != null ? texture.name : "" );
                            rawData.AddStream(new float[] { offset.x, offset.y });
                            rawData.AddStream(new float[] { scale.x, scale.y });
                            break;

                        case ShaderProperties.PropType.Vector:
                            Vector4 vector = mat.GetVector(propName);
                            rawData.AddStream(new float[] { vector.x, vector.y, vector.z, vector.w });
                            break;
                    }
                }
                result.rawData = rawData.Compose();
                return result;
            } else {
                if (vBug.settings.general.debugMode)
                    Debug.LogError("No shader-info found @" + shader.name);
                return null;
            }
        }
コード例 #14
0
        static void CustomGraphicsBlit(RenderTexture source, RenderTexture dest, Material fxMaterial, int passNr)
        {
            RenderTexture.active = dest;

            fxMaterial.SetTexture ("_MainTex", source);

            GL.PushMatrix ();
            GL.LoadOrtho ();

            fxMaterial.SetPass (passNr);

            GL.Begin (GL.QUADS);

            GL.MultiTexCoord2 (0, 0.0f, 0.0f);
            GL.Vertex3 (0.0f, 0.0f, 3.0f); // BL

            GL.MultiTexCoord2 (0, 1.0f, 0.0f);
            GL.Vertex3 (1.0f, 0.0f, 2.0f); // BR

            GL.MultiTexCoord2 (0, 1.0f, 1.0f);
            GL.Vertex3 (1.0f, 1.0f, 1.0f); // TR

            GL.MultiTexCoord2 (0, 0.0f, 1.0f);
            GL.Vertex3 (0.0f, 1.0f, 0.0f); // TL

            GL.End ();
            GL.PopMatrix ();
        }
コード例 #15
0
		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);
			}
		}
コード例 #16
0
ファイル: CellColor.cs プロジェクト: VegK/Flood-It
        private void Awake()
        {
            _cellController = GetComponentInParent<CellController>();

            _firstMaterial = _cellController.FirstSide.GetComponent<MeshRenderer>().material;
            _secondMaterial = _cellController.SecondSide.GetComponent<MeshRenderer>().material;
        }
コード例 #17
0
ファイル: RimLight.cs プロジェクト: nicegary/Unity5Effects
        void OnRenderImage(RenderTexture src, RenderTexture dst)
        {
            if (m_material == null)
            {
                m_material = new Material(m_shader);
            }

            if (m_edge_highlighting)
            {
                m_material.EnableKeyword("ENABLE_EDGE_HIGHLIGHTING");
            }
            else
            {
                m_material.DisableKeyword("ENABLE_EDGE_HIGHLIGHTING");
            }

            if (m_mul_smoothness)
            {
                m_material.EnableKeyword("ENABLE_SMOOTHNESS_ATTENUAION");
            }
            else
            {
                m_material.DisableKeyword("ENABLE_SMOOTHNESS_ATTENUAION");
            }

            m_material.SetVector("_Color", GetLinearColor());
            m_material.SetVector("_Params1", new Vector4(m_fresnel_bias, m_fresnel_scale, m_fresnel_pow, m_intensity));
            m_material.SetVector("_Params2", new Vector4(m_edge_intensity, m_edge_threshold, m_edge_radius, 0.0f));
            Graphics.Blit(src, dst, m_material);
        }
コード例 #18
0
ファイル: qd_Mesh.cs プロジェクト: zjucsxxd/UnityRepository
        public static GameObject CreateDecal(Material mat, Rect uvCoords, float scale)
        {
            GameObject decal = new GameObject();
            decal.name = "Decal" + decal.GetInstanceID();

            decal.AddComponent<MeshFilter>().sharedMesh = DecalMesh("DecalMesh" + decal.GetInstanceID(), mat, uvCoords, scale);
            decal.AddComponent<MeshRenderer>().sharedMaterial = mat;

            #if UNITY_5
            decal.GetComponent<MeshRenderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
            #else
            decal.GetComponent<MeshRenderer>().castShadows = false;
            #endif

            qd_Decal decalComponent = decal.AddComponent<qd_Decal>();

            decalComponent.SetScale(scale);
            decalComponent.SetTexture( (Texture2D)mat.mainTexture );
            decalComponent.SetUVRect(uvCoords);

            #if DEBUG
            decal.AddComponent<qd_DecalDebug>();
            #endif

            return decal;
        }
コード例 #19
0
 public SpriteAnimator(Material material, int columnCount)
 {
     this.material = material;
     this.spriteSheetColumnCount = columnCount;
     this.Sequences = new List<SpriteAnimationSequence>();
     this.Settings = new SpriteAnimationSettings();
 }
コード例 #20
0
        public void Apply(CloudsMaterial material, float radius, Transform parent)
        {
            Remove();
            particleMaterial.MaxScale = size.y;
            particleMaterial.MaxTrans = maxTranslation;
            particleMaterial.NoiseScale =  new Vector3(noiseScale.x, noiseScale.y, noiseScale.z / radius);
            ParticleMaterial = new Material(ParticleCloudShader);
            particleMaterial.ApplyMaterialProperties(ParticleMaterial);
            material.ApplyMaterialProperties(ParticleMaterial);
            ParticleMaterial.EnableKeyword("SOFT_DEPTH_ON");

            volumeHolder = new GameObject();
            //Add the renderer here so othe rentities (shadows)
            //can easily access it.
            Renderer r = volumeHolder.AddComponent<MeshRenderer>();
            r.material = ParticleMaterial;
            ParticleMaterial.SetMatrix(ShaderProperties._ShadowBodies_PROPERTY, Matrix4x4.zero);
            ParticleMaterial.renderQueue = (int)Tools.Queue.Transparent + 2;

            r.enabled = false;
            volumeHolder.transform.parent = parent;
            volumeHolder.transform.localPosition = Vector3.zero;
            volumeHolder.transform.localScale = Vector3.one;
            volumeHolder.transform.localRotation = Quaternion.identity;
            volumeHolder.layer = (int)Tools.Layer.Local;
            volumeManager = new VolumeManager(radius, size, ParticleMaterial, volumeHolder.transform, area.x, (int)area.y);
            
        }
コード例 #21
0
 public override void OnRecord()
 {
     if (_material = material)
     {
         _original = _material.GetTextureScale(propertyName);
     }
 }
コード例 #22
0
 static void SetKeyword(Material m, string keyword, bool state)
 {
     if (state)
         m.EnableKeyword(keyword);
     else
         m.DisableKeyword(keyword);
 }
コード例 #23
0
        void OnEnable()
        {
            foreach(Transform child in transform)
            {
                //Search for child Loading Background to get the mesh renderer for the background texture
                if(child.name == "Loading Background")
                {
                    m_MeshRenderer = child.GetComponent<MeshRenderer>();
                }
                if(child.name == "Loading Percent")
                {
                    m_LoadingText = child.GetComponent<TextMesh>();
                }
            }

            if(m_MeshRenderer == null)
            {
                Debug.LogError("Missing a gameobject with the name \'Loading Background\' and a \'MeshRenderer\' component.");
                gameObject.SetActive(false);
                return;
            }
            if(m_LoadingText == null)
            {
                Debug.LogError("Missing a gameobject with the name \'Loading Text\' and a \'TextMesh\' component.");
                gameObject.SetActive(false);
                return;
            }
            Material material = new Material(m_MeshRenderer.sharedMaterial);
            material.SetTexture("_MainTex", m_TextureToDisplay);
            m_MeshRenderer.material = material;
        }
コード例 #24
0
ファイル: Building.cs プロジェクト: Kundara/project1
		// Use this for initialization
		void Start () {
			currentOutsideMaterial = new Material (dissolveMaterial.shader);
			currentOutsideMaterial.CopyPropertiesFromMaterial(dissolveMaterial);

			currentGlassMaterial = new Material (glassMaterial.shader);
			currentGlassMaterial.CopyPropertiesFromMaterial(glassMaterial);

			foreach (Transform t in outside.GetComponentsInChildren<Transform>()) {

				var renderer = t.gameObject.GetComponent<SpriteRenderer>();
				if (renderer != null) {
					
					if (t.CompareTag(Tags.Glass)){
						renderer.material = currentGlassMaterial;
					} else {
						renderer.material = currentOutsideMaterial;
					}


				}

		
			}

		}
コード例 #25
0
        protected Material CheckShaderAndCreateMaterial(Shader s, Material m2Create)
        {
            if (!s)
            {
                Debug.Log("Missing shader in " + this.ToString());
                enabled = false;
                return null;
            }

            if (s.isSupported && m2Create && m2Create.shader == s)
                return m2Create;

            if (!s.isSupported)
            {
                enabled = false;
                isSupported = false;
                Debug.Log("The shader " + s.ToString() + " on effect " + this.ToString() + " is not supported on this platform!");
                return null;
            }
            else
            {
                //Debug.Log("Creating material");
                m2Create = new Material(s);
                m2Create.hideFlags = HideFlags.DontSave;
                if (m2Create)
                {
                    return m2Create;
                }
                else
                    return null;
            }
        }
コード例 #26
0
 public override void OnRestore()
 {
     if (_material = material)
     {
         _material.SetTextureScale(propertyName, _original);
     }
 }
コード例 #27
0
 public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
 {
     if (material.HasProperty("_Emission"))
     {
         material.SetColor("_EmissionColor", material.GetColor("_Emission"));
     }
     base.AssignNewShaderToMaterial(material, oldShader, newShader);
     if ((oldShader == null) || !oldShader.name.Contains("Legacy Shaders/"))
     {
         SetupMaterialWithBlendMode(material, (BlendMode) ((int) material.GetFloat("_Mode")));
     }
     else
     {
         BlendMode opaque = BlendMode.Opaque;
         if (oldShader.name.Contains("/Transparent/Cutout/"))
         {
             opaque = BlendMode.Cutout;
         }
         else if (oldShader.name.Contains("/Transparent/"))
         {
             opaque = BlendMode.Fade;
         }
         material.SetFloat("_Mode", (float) opaque);
         Material[] mats = new Material[] { material };
         this.DetermineWorkflow(MaterialEditor.GetMaterialProperties(mats));
         MaterialChanged(material, this.m_WorkflowMode);
     }
 }
コード例 #28
0
ファイル: pb_Renderable.cs プロジェクト: itubeasts/I-eaT-U
		public static pb_Renderable CreateInstance(Mesh InMesh, Material InMaterial)
		{
			pb_Renderable ren = ScriptableObject.CreateInstance<pb_Renderable>();
			ren.mesh = InMesh;
			ren.materials = new Material[] { InMaterial };
			return ren;
		}
コード例 #29
0
ファイル: Shockwave.cs プロジェクト: Groutcho/EventHorizon
        IEnumerator Grow()
        {
            float f = 0;
            float t = 0;
            Vector3 originalScale = transform.localScale;
            Vector3 targetScale = originalScale * EndScale;
            Material originalMaterial = new Material(renderer.material);
            Color originalColor = originalMaterial.GetColor("_TintColor");
            Color targetColor = new Color(originalColor.r, originalColor.g, originalColor.b, 0F);
            renderer.material = originalMaterial;

            while (f <= duration)
            {
                t = f / duration;
                transform.localScale = Vector3.Lerp(originalScale, targetScale, t);

                originalMaterial.SetColor("_TintColor", Color.Lerp(originalColor, targetColor, t));

                f += Time.deltaTime;
                yield return new WaitForEndOfFrame();
            }

            if (mode == FXmode.DestroyAtEnd)
                Destroy(gameObject);

            else if (mode == FXmode.Loop)
                Play();
        }
コード例 #30
0
        protected override bool CheckResources()
        {
            CheckSupport(mode == ColorCorrectionMode.Advanced);

            ccMaterial = CheckShaderAndCreateMaterial(simpleColorCorrectionCurvesShader, ccMaterial);
            ccDepthMaterial = CheckShaderAndCreateMaterial(colorCorrectionCurvesShader, ccDepthMaterial);
            selectiveCcMaterial = CheckShaderAndCreateMaterial(colorCorrectionSelectiveShader, selectiveCcMaterial);

            if (!rgbChannelTex)
                rgbChannelTex = new Texture2D(256, 4, TextureFormat.ARGB32, false, true);
            if (!rgbDepthChannelTex)
                rgbDepthChannelTex = new Texture2D(256, 4, TextureFormat.ARGB32, false, true);
            if (!zCurveTex)
                zCurveTex = new Texture2D(256, 1, TextureFormat.ARGB32, false, true);

            rgbChannelTex.hideFlags = HideFlags.DontSave;
            rgbDepthChannelTex.hideFlags = HideFlags.DontSave;
            zCurveTex.hideFlags = HideFlags.DontSave;

            rgbChannelTex.wrapMode = TextureWrapMode.Clamp;
            rgbDepthChannelTex.wrapMode = TextureWrapMode.Clamp;
            zCurveTex.wrapMode = TextureWrapMode.Clamp;

            if (!isSupported)
                ReportAutoDisable();
            return isSupported;
        }
コード例 #31
0
        public static string GetMaterialPath(UnityEngine.Material material)
        {
            var    mat  = material;
            string path = UnityEditor.AssetDatabase.GetAssetPath(mat);

            if (path == "Resources/unity_builtin_extra")
            {
                path = "Library/" + mat.name + ".mat";
            }
            if (!path.Contains(".mat"))
            {
                path += "." + mat.name + ".mat";//.obj文件此时应该导出不同的材质文件,GetAssetPath获取的确实同一个
            }
            path = PathHelper.CheckFileName(path + ".json");
            return(path);
        }
コード例 #32
0
 static public int SetBuffer(IntPtr l)
 {
     try{
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         System.String        a1;
         checkType(l, 2, out a1);
         UnityEngine.ComputeBuffer a2;
         checkType(l, 3, out a2);
         self.SetBuffer(a1, a2);
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
コード例 #33
0
ファイル: BSPData2Unity3D.cs プロジェクト: fangguanya/BSP
 void LoadTextures()
 {
     if (textures == null)
     {
         int len = _textures.Length;
         textures     = new UnityEngine.Texture2D[len];
         allmaterials = new UnityEngine.Material[len];
         for (int i = 0; i < len; i++)
         {
             string[] parts = new string(_textures[i].name).Split('/');
             textures[i]                 = Resources.Load(parts[parts.Length - 1]) as Texture2D;
             allmaterials[i]             = new UnityEngine.Material(Shader.Find("Diffuse"));
             allmaterials[i].mainTexture = textures[i];
         }
     }
 }
コード例 #34
0
        //create changePokemon
        //create generateId
        /// <summary>
        /// generates a new Load RenderMesh value using the given values
        /// </summary>
        /// <param name="pokemonName"></param>
        /// <returns></returns>

        /*	public static RenderMesh LoadPokemonRenderMesh(string pokemonName)
         *      {
         *      ///	string dataPath = Application.dataPath + "/Resources/Pokemon/" + pokemonName + "/" + pokemonName + ".prefab";
         *      //	if (!File.Exists(dataPath))
         *      //	{
         *      //		Debug.LogError(dataPath);
         *      //	}
         *              GameObject go = Resources.Load("Pokemon/" + pokemonName + "/" + pokemonName, typeof(GameObject)) as GameObject;
         *              if (go == null) Debug.LogError("Failed to get the render mesh gameobject");
         *              else Debug.Log("Succesfully Loaded \""+pokemonName+"\"");
         *              //verify this works with physics
         *              RenderMesh renderer = new RenderMesh
         *              {
         *                      mesh = go.GetComponent<MeshFilter>().sharedMesh,
         *                      material = go.GetComponent<MeshRenderer>().sharedMaterial,
         *                      castShadows = UnityEngine.Rendering.ShadowCastingMode.On,
         *                      receiveShadows = true
         *              };
         *
         *              return renderer;
         *      }*/
        public static RenderMesh LoadEnviromentRenderMesh(EnviromentData enviromentData, string startPath)
        {
            startPath += enviromentData.entityName.ToString() + "/" + enviromentData.entityName.ToString();
            Debug.Log("adasdadasd" + startPath);
            GameObject go = Resources.Load("Enviroment/Models/" + startPath, typeof(GameObject)) as GameObject;

            UnityEngine.Material _mat     = Resources.Load("Enviroment/Models/" + startPath, typeof(UnityEngine.Material)) as UnityEngine.Material;
            UnityEngine.Mesh     _mesh    = go.GetComponent <MeshFilter>().sharedMesh;
            RenderMesh           renderer = new RenderMesh
            {
                mesh     = _mesh,
                material = _mat
            };

            return(renderer);
        }
コード例 #35
0
        private NormalTextureInfo ExportNormalTextureInfo(
            UnityEngine.Texture texture,
            TextureMapType textureMapType,
            UnityEngine.Material material)
        {
            var info = new NormalTextureInfo();

            info.Index = ExportTexture(texture, textureMapType);

            if (material.HasProperty("_BumpScale"))
            {
                info.Scale = material.GetFloat("_BumpScale");
            }

            return(info);
        }
コード例 #36
0
 private void DrawMaterialField()
 {
     if (_material == null)
     {
         _tmpRect.Set(2, 2, 152, 22);
         EditorGUI.DrawRect(_tmpRect, UnityEngine.Color.magenta);
     }
     _tmpRect.Set(3, 3, 150, 20);
     UnityEngine.Material newMaterial = (UnityEngine.Material)EditorGUI.ObjectField(_tmpRect, "", _material, typeof(UnityEngine.Material), false);
     if (_material != newMaterial)
     {
         _material  = newMaterial;
         _assetPath = AssetDatabase.GetAssetPath(_material);
         TriggerChangeEvent();
     }
 }
コード例 #37
0
 static public int Add_s(IntPtr l)
 {
     try{
         UnityEngine.Material a1;
         checkType(l, 1, out a1);
         System.Int32 a2;
         checkType(l, 2, out a2);
         UnityEngine.Material ret = UnityEngine.UI.StencilMaterial.Add(a1, a2);
         pushValue(l, ret);
         return(1);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
コード例 #38
0
        private OcclusionTextureInfo ExportOcclusionTextureInfo(
            UnityEngine.Texture texture,
            TextureMapType textureMapType,
            UnityEngine.Material material)
        {
            var info = new OcclusionTextureInfo();

            info.Index = ExportTexture(texture, textureMapType);

            if (material.HasProperty("_OcclusionStrength"))
            {
                info.Strength = material.GetFloat("_OcclusionStrength");
            }

            return(info);
        }
コード例 #39
0
    static bool Graphics_DrawMesh__Mesh__Vector3__Quaternion__Material__Int32(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 5)
        {
            UnityEngine.Mesh       arg0 = (UnityEngine.Mesh)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            UnityEngine.Vector3    arg1 = (UnityEngine.Vector3)JSApi.getVector3S((int)JSApi.GetType.Arg);
            UnityEngine.Quaternion arg2 = (UnityEngine.Quaternion)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            UnityEngine.Material   arg3 = (UnityEngine.Material)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            System.Int32           arg4 = (System.Int32)JSApi.getInt32((int)JSApi.GetType.Arg);
            UnityEngine.Graphics.DrawMesh(arg0, arg1, arg2, arg3, arg4);
        }

        return(true);
    }
コード例 #40
0
    static bool Graphics_DrawMesh__Mesh__Matrix4x4__Material__Int32__Camera(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 5)
        {
            UnityEngine.Mesh      arg0 = (UnityEngine.Mesh)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            UnityEngine.Matrix4x4 arg1 = (UnityEngine.Matrix4x4)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            UnityEngine.Material  arg2 = (UnityEngine.Material)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            System.Int32          arg3 = (System.Int32)JSApi.getInt32((int)JSApi.GetType.Arg);
            UnityEngine.Camera    arg4 = (UnityEngine.Camera)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            UnityEngine.Graphics.DrawMesh(arg0, arg1, arg2, arg3, arg4);
        }

        return(true);
    }
コード例 #41
0
ファイル: Material.cs プロジェクト: clarte53/armine
 private static void ToUnityMaterialProperties <T, U>(UnityEngine.Material unity_material, Dictionary <string, T> values, Action <UnityEngine.Material, string, T> setter)
 {
     if (values != null && setter != null && unity_material != null)
     {
         lock (values)
         {
             foreach (KeyValuePair <string, T> pair in values)
             {
                 if (unity_material.HasProperty(pair.Key))
                 {
                     setter(unity_material, pair.Key, pair.Value);
                 }
             }
         }
     }
 }
コード例 #42
0
        public int GetUnityMaterialIndex(UnityEngine.Material material)
        {
            int index = -1;

            if (material != null)
            {
                if (!unityMaterials.TryGetValue(material, out index))
                {
                    index = unityMaterials.Count;

                    unityMaterials.Add(material, index);
                }
            }

            return(index);
        }
コード例 #43
0
        public MaterialId GetMaterialId(UnityEngine.Material materialObj)
        {
            for (var i = 0; i < Materials.Count; i++)
            {
                if (Materials[i].ContentsWithoutVC == materialObj || Materials[i].ContentsWithVC == materialObj)
                {
                    return(new MaterialId
                    {
                        Id = i,
                        Root = this
                    });
                }
            }

            return(null);
        }
コード例 #44
0
        public MaterialId GetMaterialId(GLTFRoot root, UnityEngine.Material materialObj)
        {
            for (var i = 0; i < _materials.Count; i++)
            {
                if (_materials[i] == materialObj)
                {
                    return(new MaterialId
                    {
                        Id = i,
                        Root = root
                    });
                }
            }

            return(null);
        }
コード例 #45
0
 static public int SetTextureOffset(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.SetTextureOffset(a1, a2);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #46
0
ファイル: dfTextureSprite.cs プロジェクト: sknchan/LegacyRust
    protected override void OnRebuildRenderData()
    {
        base.OnRebuildRenderData();
        if (this.texture == null)
        {
            return;
        }
        this.ensureMaterial();
        if (this.material == null)
        {
            return;
        }
        if (this.renderMaterial == null)
        {
            UnityEngine.Material material = new UnityEngine.Material(this.material)
            {
                hideFlags = HideFlags.DontSave,
                name      = string.Concat(this.material.name, " (copy)")
            };
            this.renderMaterial = material;
        }
        this.renderMaterial.mainTexture = this.texture;
        this.renderData.Material        = this.renderMaterial;
        float   units   = base.PixelsToUnits();
        float   single  = 0f;
        float   single1 = 0f;
        float   single2 = this.size.x * units;
        float   single3 = -this.size.y * units;
        Vector3 num     = this.pivot.TransformToUpperLeft(this.size).RoundToInt() * units;

        this.renderData.Vertices.Add(new Vector3(single, single1, 0f) + num);
        this.renderData.Vertices.Add(new Vector3(single2, single1, 0f) + num);
        this.renderData.Vertices.Add(new Vector3(single2, single3, 0f) + num);
        this.renderData.Vertices.Add(new Vector3(single, single3, 0f) + num);
        this.renderData.Triangles.AddRange(dfTextureSprite.TRIANGLE_INDICES);
        this.rebuildUV(this.renderData);
        Color32 color32 = base.ApplyOpacity(this.color);

        this.renderData.Colors.Add(color32);
        this.renderData.Colors.Add(color32);
        this.renderData.Colors.Add(color32);
        this.renderData.Colors.Add(color32);
        if (this.fillAmount < 1f)
        {
            this.doFill(this.renderData);
        }
    }
コード例 #47
0
ファイル: 9-Perlin.cs プロジェクト: labiel1/DreamHouse_Gaminp
        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);
        }
コード例 #48
0
        private UnityEngine.Material CreateMaterialFromXml(XElement xml)
        {
            // Does this material support alpha color key?
            string htmlColor       = ImportUtils.GetAttributeAsString(xml, "alphaColorKey", "");
            bool   usesDepthShader = ImportUtils.GetAttributeAsBoolean(xml, "usesDepthShaders", false);

            // Determine which shader we sould be using
            string shaderName = "Tiled2Unity/";

            // Are we using depth shaders?
            if (usesDepthShader)
            {
                shaderName += "Depth";
            }
            else
            {
                shaderName += "Default";
            }

            // Are we using color key shaders?
            Color?keyColor = null;

            if (!String.IsNullOrEmpty(htmlColor))
            {
                shaderName += " Color Key";

                // Sometimes Tiled saves out color without the leading # but we expect it to be there
                if (!htmlColor.StartsWith("#"))
                {
                    htmlColor = "#" + htmlColor;
                }

                byte r = byte.Parse(htmlColor.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
                byte g = byte.Parse(htmlColor.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
                byte b = byte.Parse(htmlColor.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
                keyColor = new Color32(r, g, b, 255);
            }

            UnityEngine.Material material = new UnityEngine.Material(UnityEngine.Shader.Find(shaderName));

            if (keyColor.HasValue)
            {
                material.SetColor("_AlphaColorKey", keyColor.Value);
            }

            return(material);
        }
コード例 #49
0
        protected void RestShader(UnityEngine.Material targetMat)
        {
            if (targetMat == null)
            {
                return;
            }
            Shader tshader = Shader.Find(targetMat.shader.name);

            if (tshader != null)
            {
                targetMat.shader = tshader;
            }
            else
            {
                Debug.LogError("未能找到对应的shader.name = " + targetMat.shader.name);
            }
        }
コード例 #50
0
        private static void CreateMaterialAsset(UnityEngine.Material material, string assetName)
        {
            var prefabName = Path.GetFileNameWithoutExtension(assetName);
            var directorty = Path.GetDirectoryName(assetName);

            var noiseTexture = material.GetTexture("_NoiseTexture");

            if (noiseTexture != null && !AssetDatabase.Contains(noiseTexture))
            {
                AssetDatabase.CreateAsset(noiseTexture, Path.Combine(directorty, prefabName + "_noiseTexture.asset"));
            }

            if (!AssetDatabase.Contains(material))
            {
                AssetDatabase.CreateAsset(material, Path.Combine(directorty, prefabName + ".mat"));
            }
        }
コード例 #51
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());
            }
        }
コード例 #52
0
        public UnityEngine.Material ReturnColour(AtlasColours inColour, Constants.RossColour rossCol)
        {
            if (myMaterialWithColour[(int)inColour] == null)
            {
                myMaterialWithColour[(int)inColour] = new UnityEngine.Material(Shader.Find("Pi/OpaqueOverlay"));

                UnityEngine.Color tempC = new UnityEngine.Color();
                tempC.a = 0.8f;
                tempC.r = rossCol.cRed;
                tempC.g = rossCol.cGreen;
                tempC.b = rossCol.cBlue;

                myMaterialWithColour[(int)inColour].color = tempC;
            }

            return(myMaterialWithColour[(int)inColour]);
        }
コード例 #53
0
    private void LoadPrimitive(Primitive primitive, string name, Matrix4x4 matrix)
    {
        if (primitive.Mode != Primitive.ModeEnum.TRIANGLES)
        {
            throw new System.NotImplementedException("Unsupported primitive mode");
        }

        GameObject   obj      = new GameObject(name);
        MeshRenderer renderer = obj.AddComponent <MeshRenderer>();
        MeshFilter   filter   = obj.AddComponent <MeshFilter>();

        filter.mesh = new UnityEngine.Mesh();

        string posID = primitive.Attributes["POSITION"];

        Vector3[] positions = new AccessorReader(m_model, posID).ReadVector3Array();
        for (int i = 0; i < positions.Length; ++i)
        {
            positions[i] = matrix * new Vector4(positions[i].x, positions[i].y, positions[i].z, 1);
        }
        filter.mesh.vertices = positions;

        string indicesID = primitive.Indices;

        int[] indices = new AccessorReader(m_model, indicesID).ReadIntArray();
        filter.mesh.triangles = indices;

        if (primitive.Attributes.ContainsKey("TEXCOORD_0"))
        {
            string texCoordID = primitive.Attributes["TEXCOORD_0"];
            try
            {
                Vector2[] texCoord = new AccessorReader(m_model, texCoordID).ReadVector2Array();
                filter.mesh.uv = texCoord;
            }
            catch (System.TypeLoadException e) {; }
        }

        string materialID = primitive.Material;

        UnityEngine.Material material = LoadMaterial(m_model.Materials[materialID]);
        renderer.material = material;

        filter.mesh.RecalculateBounds();
        filter.mesh.RecalculateNormals();
    }
コード例 #54
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);
        }
コード例 #55
0
ファイル: MaterialGenerator.cs プロジェクト: Zhavii/glTFast
        protected static bool TrySetTexture(
            Schema.TextureInfo textureInfo,
            UnityEngine.Material material,
            int propertyId,
            ref Schema.Texture[] textures,
            ref Schema.Image[] schemaImages,
            ref Dictionary <int, Texture2D>[] imageVariants
            )
        {
            if (textureInfo != null && textureInfo.index >= 0)
            {
                int bcTextureIndex = textureInfo.index;
                if (textures != null && textures.Length > bcTextureIndex)
                {
                    var txt        = textures[bcTextureIndex];
                    var imageIndex = txt.GetImageIndex();

                    Texture2D img = null;
                    if (imageVariants != null &&
                        imageIndex >= 0 &&
                        imageVariants.Length > imageIndex &&
                        imageVariants[imageIndex] != null &&
                        imageVariants[imageIndex].TryGetValue(txt.sampler, out img)
                        )
                    {
                        if (textureInfo.texCoord != 0)
                        {
                            Debug.LogError(ERROR_MULTI_UVS);
                        }
                        material.SetTexture(propertyId, img);
                        var isKtx = txt.isKtx;
                        TrySetTextureTransform(textureInfo, material, propertyId, isKtx);
                        return(true);
                    }
                    else
                    {
                        Debug.LogErrorFormat("Image #{0} not found", imageIndex);
                    }
                }
                else
                {
                    Debug.LogErrorFormat("Texture #{0} not found", bcTextureIndex);
                }
            }
            return(false);
        }
コード例 #56
0
    static bool Material_Material2(JSVCall vc, int argc)
    {
        int _this = JSApi.getObject((int)JSApi.GetType.Arg);

        JSApi.attachFinalizerObject(_this);
        --argc;

        int len = argc;

        if (len == 1)
        {
            UnityEngine.Material arg0 = (UnityEngine.Material)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
            JSMgr.addJSCSRel(_this, new UnityEngine.Material(arg0));
        }

        return(true);
    }
コード例 #57
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));
            }
        }
コード例 #58
0
ファイル: Resources.cs プロジェクト: t-artikov/unity2urho
 public StandardMaterial(UnityEngine.Material source, UnityEngine.MeshRenderer instanceData) :
     base(source, instanceData)
 {
     diffuseColor   = source.color;
     uvOffset       = source.mainTextureOffset;
     uvScale        = source.mainTextureScale;
     diffuseTexture = ResourceCache.Instance.GetTexture(source.mainTexture);
     if (diffuseTexture == null)
     {
         diffuseTexture = ResourceCache.Instance.GetTexture(UnityEngine.Texture2D.whiteTexture);
     }
     normalTexture = ResourceCache.Instance.GetTexture(source.GetTexture("_BumpMap"));
     if (instanceData.lightmapIndex >= 0)
     {
         lightmapTexture = ResourceCache.Instance.GetTexture(LightmapSettings.lightmaps[instanceData.lightmapIndex].lightmapColor);
     }
 }
コード例 #59
0
 static public int Lerp(IntPtr l)
 {
     try {
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         UnityEngine.Material a1;
         checkType(l, 2, out a1);
         UnityEngine.Material a2;
         checkType(l, 3, out a2);
         System.Single a3;
         checkType(l, 4, out a3);
         self.Lerp(a1, a2, a3);
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #60
0
 static public int Lerp(IntPtr l)
 {
     try {
         UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
         UnityEngine.Material a1;
         checkType(l, 2, out a1);
         UnityEngine.Material a2;
         checkType(l, 3, out a2);
         System.Single a3;
         checkType(l, 4, out a3);
         self.Lerp(a1, a2, a3);
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }