Search Unity

Shader works on Android but it is black on iOS

Discussion in 'Shaders' started by IlisanVlad, Feb 25, 2020.

  1. IlisanVlad

    IlisanVlad

    Joined:
    Dec 3, 2017
    Posts:
    30
    Hi -

    I am using some shaders for painting. Everything works fine in the editor and on Android except for iOS.

    You can see the problem here recoreded on an iPhone 6


    The object looks ok until I press to start painting. The material turns instantly black and the paint doesnt stay on for more than a few frames.

    This is what it's supposed to look like


    Here are all the scripts used for painting:

    TexturePaint.cs

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.Rendering;
    5.  
    6. public class TexturePaint : MonoBehaviour
    7. {
    8.     bool canPaint = false;
    9.  
    10.     // ======================================================================================================================
    11.     // PARAMETERS -----------------------------------------------------------------------------------------------
    12.     public Texture baseTexture;                  // used to deterimne the dimensions of the runtime texture
    13.     public Material meshMaterial;                 // used to bind the runtime texture as the albedo of the mesh
    14.     public Mesh meshToDraw;
    15.     public GameObject meshGameobject;
    16.     public LevelCompletion levelCompletionScript;
    17.     public Shader UVShader;                     // the shader usedto draw in the texture of the mesh
    18.     public Shader ilsandMarkerShader;
    19.     public Shader fixIlsandEdgesShader;
    20.     public static Vector3 mouseWorldPosition;
    21.  
    22.     // --------------------------------
    23.  
    24.     public Camera mainCamera;
    25.     private RenderTexture markedIlsandes;
    26.     private CommandBuffer cb_markingIlsdands;
    27.  
    28.     // ---------------------------------
    29.     private PaintableTexture albedo;
    30.  
    31.     //Progression variables
    32.     Vector3 lastTouchPos;
    33.  
    34.     [HideInInspector]
    35.     public bool hasColorChanged = true; //This is true when painting with a newly changed color. Used for color percentages
    36.  
    37.     public void StartPainting()
    38.     {
    39.         canPaint = true;
    40.         hasColorChanged = true;
    41.         Shader.SetGlobalFloat("_BrushOpacity", 1);
    42.         Shader.SetGlobalFloat("_BrushHardness", GameManager.Instance.brushHardness);
    43.     }
    44.     public void StopPainting()
    45.     {
    46.         canPaint = false;
    47.     }
    48.  
    49.     private void Awake()
    50.     {
    51.         mainCamera.depthTextureMode = DepthTextureMode.Depth;
    52.     }
    53.     // ======================================================================================================================
    54.     // INITIALIZE -------------------------------------------------------------------
    55.  
    56.     void Start()
    57.     {
    58.         //  Shader.SetGlobalColor("_BrushColor", GameplayManager.Instance.defaultBrushColor); //Set the default color of the scene
    59.  
    60.         Vector4 mwp = new Vector4(100,100,100,100);
    61.         Shader.SetGlobalVector("_Mouse", mwp);
    62.  
    63.         // Texture and Mat initalization ---------------------------------------------
    64.         markedIlsandes = new RenderTexture(baseTexture.width, baseTexture.height, 0, RenderTextureFormat.R8);
    65.         albedo = new PaintableTexture(Color.white, baseTexture.width, baseTexture.height, "_MainTex", UVShader, meshToDraw, fixIlsandEdgesShader, markedIlsandes);
    66.  
    67.  
    68.         meshMaterial.SetTexture(albedo.id, albedo.runTimeTexture);
    69.  
    70.         // Command buffer inialzation ------------------------------------------------
    71.  
    72.         cb_markingIlsdands = new CommandBuffer();
    73.         cb_markingIlsdands.name = "markingIlsnads";
    74.  
    75.  
    76.         cb_markingIlsdands.SetRenderTarget(markedIlsandes);
    77.         Material mIlsandMarker = new Material(ilsandMarkerShader);
    78.         cb_markingIlsdands.DrawMesh(meshToDraw, Matrix4x4.identity, mIlsandMarker);
    79.         mainCamera.AddCommandBuffer(CameraEvent.AfterDepthTexture, cb_markingIlsdands);
    80.  
    81.  
    82.         albedo.SetActiveTexture(mainCamera);
    83.  
    84.         StartCoroutine(RemoveBuffer());
    85.     }
    86.     // ======================================================================================================================
    87.     // LOOP ---------------------------------------------------------------------------
    88.  
    89.     private void Update()
    90.     {
    91.         albedo.UpdateShaderParameters(meshGameobject.transform.localToWorldMatrix);
    92.  
    93.         // ---------------------------------------------------------------------------
    94.         // Setting up Mouse Parameters
    95.         if (Input.GetMouseButton(0) && canPaint)
    96.         {
    97.             RaycastHit hit;
    98.             Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
    99.             Vector4 mwp = Vector3.positiveInfinity;
    100.  
    101.             if (Physics.Raycast(ray, out hit))
    102.             {
    103.                 if (hit.collider.gameObject.tag == "PaintObject")
    104.                 {
    105.                     if (Input.mousePosition != lastTouchPos) GameplayManager.Instance.IncreaseProgression();
    106.                     mwp = hit.point;
    107.  
    108.                     if (hasColorChanged)
    109.                     {
    110.                         StartCoroutine(levelCompletionScript.GetNewColors(hit));
    111.                         hasColorChanged = false;
    112.                     }
    113.                 }
    114.             }
    115.  
    116.             mwp.w = Input.GetMouseButton(0) ? 1 : 0;
    117.  
    118.             mouseWorldPosition = mwp;
    119.             Shader.SetGlobalVector("_Mouse", mwp);
    120.  
    121.             lastTouchPos = Input.mousePosition;
    122.         }
    123.  
    124.     }
    125.     IEnumerator RemoveBuffer()
    126.     {
    127.         int i = 0;
    128.         while (i < 2)
    129.         {
    130.             i++;
    131.             yield return null;
    132.         }
    133.         mainCamera.RemoveCommandBuffer(CameraEvent.AfterDepthTexture, cb_markingIlsdands);
    134.     }
    135. }
    136.  
    137. [System.Serializable]
    138. public class PaintableTexture
    139. {
    140.     public string id;
    141.     public RenderTexture runTimeTexture;
    142.     public RenderTexture paintedTexture;
    143.  
    144.     public CommandBuffer cb;
    145.  
    146.     private Material mPaintInUV;
    147.     private Material mFixedEdges;
    148.     private RenderTexture fixedIlsands;
    149.  
    150.     public PaintableTexture(Color clearColor, int width, int height, string id,
    151.         Shader sPaintInUV, Mesh mToDraw, Shader fixIlsandEdgesShader, RenderTexture markedIlsandes)
    152.     {
    153.         this.id = id;
    154.  
    155.         runTimeTexture = new RenderTexture(width, height, 0)
    156.         {
    157.             anisoLevel = 0,
    158.             useMipMap = false,
    159.             filterMode = FilterMode.Bilinear
    160.         };
    161.  
    162.         paintedTexture = new RenderTexture(width, height, 0)
    163.         {
    164.             anisoLevel = 0,
    165.             useMipMap = false,
    166.             filterMode = FilterMode.Bilinear
    167.         };
    168.  
    169.  
    170.         fixedIlsands = new RenderTexture(paintedTexture.descriptor);
    171.  
    172.         Graphics.SetRenderTarget(runTimeTexture);
    173.         GL.Clear(false, true, clearColor);
    174.         Graphics.SetRenderTarget(paintedTexture);
    175.         GL.Clear(false, true, clearColor);
    176.  
    177.  
    178.         mPaintInUV = new Material(sPaintInUV);
    179.         if (!mPaintInUV.SetPass(0)) Debug.LogError("Invalid Shader Pass: ");
    180.         mPaintInUV.SetTexture("_MainTex", paintedTexture);
    181.  
    182.         mFixedEdges = new Material(fixIlsandEdgesShader);
    183.         mFixedEdges.SetTexture("_IlsandMap", markedIlsandes);
    184.         mFixedEdges.SetTexture("_MainTex", paintedTexture);
    185.  
    186.         // ----------------------------------------------
    187.  
    188.         cb = new CommandBuffer();
    189.         cb.name = "TexturePainting" + id;
    190.  
    191.  
    192.         cb.SetRenderTarget(runTimeTexture);
    193.         cb.DrawMesh(mToDraw, Matrix4x4.identity, mPaintInUV);
    194.  
    195.         cb.Blit(runTimeTexture, fixedIlsands, mFixedEdges);
    196.         cb.Blit(fixedIlsands, runTimeTexture);
    197.         cb.Blit(runTimeTexture, paintedTexture);
    198.  
    199.     }
    200.  
    201.     public void SetActiveTexture(Camera mainC)
    202.     {
    203.         mainC.AddCommandBuffer(CameraEvent.AfterDepthTexture, cb);
    204.     }
    205.  
    206.     public void SetInactiveTexture(Camera mainC)
    207.     {
    208.         mainC.RemoveCommandBuffer(CameraEvent.AfterDepthTexture, cb);
    209.     }
    210.  
    211.     public void UpdateShaderParameters(Matrix4x4 localToWorld)
    212.     {
    213.         mPaintInUV.SetMatrix("mesh_Object2World", localToWorld); // Mus be updated every time the mesh moves, and also at start
    214.     }
    215. }
    216.  

    TexturePaint.shader

    Code (CSharp):
    1. Shader "Unlit/TexturePaint"
    2. {
    3.    
    4.  
    5.     SubShader
    6.     {
    7.         Tags { "RenderType"="Opaque" }
    8.         LOD       100
    9.         ZTest Always
    10.         ZWrite Off
    11.         Cull   Off
    12.  
    13.         Pass
    14.         {
    15.             CGPROGRAM
    16.  
    17.             #pragma vertex   vert
    18.             #pragma fragment frag
    19.             #pragma exclude_renderers d3d9 d3d11 xbox360 ps3 flash
    20.  
    21.            
    22.             #include "UnityCG.cginc"
    23.  
    24.             struct appdata
    25.             {
    26.                 float4 vertex   : POSITION;
    27.                 float2 uv        : TEXCOORD0;
    28.             };
    29.  
    30.             struct v2f
    31.             {
    32.                 float4 vertex   : SV_POSITION;
    33.                 float3 worldPos : TEXCOORD0;
    34.                 float2 uv       : TEXCOORD1;
    35.             };
    36.  
    37.             float4    _Mouse;
    38.             float4x4  mesh_Object2World;
    39.             sampler2D _MainTex;
    40.             fixed4      _BrushColor;
    41.             float      _BrushOpacity;
    42.             float      _BrushHardness;
    43.             float      _BrushSize;
    44.  
    45.             v2f vert (appdata v)
    46.             {
    47.                 v2f o;
    48.  
    49.                 float2 uvRemapped   = v.uv.xy;
    50.                 #if UNITY_UV_STARTS_AT_TOP
    51.                        uvRemapped.y = 1. - uvRemapped.y;
    52.                 #endif
    53.                        uvRemapped   = uvRemapped *2 - 1;
    54.  
    55.                        o.vertex     = float4(uvRemapped.xy, 0, 1);
    56.                        o.worldPos   = mul(mesh_Object2World, v.vertex);
    57.                        o.uv         = v.uv;
    58.  
    59.                 return o;
    60.             }
    61.            
    62.             fixed4 frag (v2f i) : SV_Target
    63.             {
    64.                 float4 col  = tex2D(_MainTex, i.uv);
    65.                 float  size = _BrushSize;
    66.                 float  soft = _BrushHardness;
    67.                 float  f    = distance(_Mouse.xz, i.worldPos.xz);
    68.                        f    = 1. -smoothstep(size*soft, size, f);
    69.    
    70.                        col  = lerp(col, _BrushColor, f);
    71.                        col  = saturate(col);
    72.  
    73.                 return col;
    74.             }
    75.             ENDCG
    76.         }
    77.  
    78.     }
    79.     Fallback Off
    80. }
    81.  

    MarkIlsands.shader

    Code (CSharp):
    1. Shader "Unlit/MarkIlsands"
    2. {
    3.     SubShader
    4.     {
    5.         // =====================================================================================================================
    6.         // TAGS AND SETUP ------------------------------------------
    7.         Tags{ "RenderType" = "Opaque" }
    8.         LOD       100
    9.         ZTest Always
    10.         ZWrite Off
    11.         Cull   Off
    12.  
    13.         Pass
    14.     {
    15.         CGPROGRAM
    16.         // =====================================================================================================================
    17.         // DEFINE AND INCLUDE ----------------------------------
    18.         #pragma vertex   vert
    19.         #pragma fragment frag
    20.         #pragma exclude_renderers d3d9 d3d11 xbox360 ps3 flash
    21.  
    22.  
    23.         #include "UnityCG.cginc"
    24.  
    25.         // =====================================================================================================================
    26.         // DECLERANTIONS ----------------------------------
    27.         struct appdata
    28.     {
    29.         float4 vertex   : POSITION;
    30.         float2 uv        : TEXCOORD0;
    31.     };
    32.  
    33.     struct v2f
    34.     {
    35.         float4 vertex   : SV_POSITION;
    36.     };
    37.  
    38.  
    39.  
    40.     // =====================================================================================================================
    41.     // VERTEX FRAGMENT ----------------------------------
    42.  
    43.     v2f vert(appdata v)
    44.     {
    45.         v2f o;
    46.  
    47.         float2 uvRemapped   = v.uv.xy;
    48.         #if UNITY_UV_STARTS_AT_TOP
    49.                uvRemapped.y = 1. - uvRemapped.y;
    50.         #endif
    51.                uvRemapped   = uvRemapped * 2. - 1.;
    52.  
    53.                o.vertex        = float4(uvRemapped.xy, 0., 1.);
    54.  
    55.         return o;
    56.     }
    57.  
    58.     fixed4 frag(v2f i) : SV_Target
    59.     {
    60.         return float4(1.,0.,0.,1.);
    61.     }
    62.         ENDCG
    63.     }
    64.  
    65.     }
    66.     Fallback Off
    67. }
    68.  

    FixIlsandEdges.shader

    Code (CSharp):
    1. Shader "Unlit/FixIlsandEdges"
    2. {
    3.    
    4.     SubShader
    5.     {
    6.         // =====================================================================================================================
    7.         // TAGS AND SETUP ------------------------------------------
    8.         Tags { "RenderType"="Opaque" }
    9.         ZTest Always
    10.         LOD 100
    11.  
    12.         Pass
    13.         {
    14.  
    15.            
    16.         // =====================================================================================================================
    17.         // DEFINE AND INCLUDE ----------------------------------
    18.             CGPROGRAM
    19.             #pragma  vertex   vert
    20.             #pragma  fragment frag
    21.             #pragma exclude_renderers d3d9 d3d11 xbox360 ps3 flash
    22.            
    23.             #include "UnityCG.cginc"
    24.  
    25.             // =====================================================================================================================
    26.             // DECLERANTIONS ----------------------------------
    27.             struct appdata
    28.             {
    29.                 float4 vertex : POSITION;
    30.                 float2 uv      : TEXCOORD0;
    31.             };
    32.  
    33.             struct v2f
    34.             {
    35.                 float2 uv      : TEXCOORD0;
    36.                 float4 vertex : SV_POSITION;
    37.             };
    38.  
    39.                     sampler2D    _MainTex;
    40.             uniform    float4        _MainTex_TexelSize;
    41.                     sampler2D   _IlsandMap;
    42.            
    43.             // =====================================================================================================================
    44.             // VERTEX FRAGMENT ----------------------------------
    45.             v2f vert (appdata v)
    46.             {
    47.                 v2f o;
    48.                 o.vertex = UnityObjectToClipPos(v.vertex);
    49.                 o.uv     = v.uv;
    50.                 return o;
    51.             }
    52.            
    53.             fixed4 frag (v2f i) : SV_Target
    54.             {
    55.  
    56.             fixed4 col = tex2D(_MainTex, i.uv);
    57.             float map  = tex2D(_IlsandMap,i.uv);
    58.            
    59.             float3 average = col;
    60.  
    61.             if (map.x < 0.2) {                                    // only take an average if it is not in a uv ilsand
    62.                 int n = 0;
    63.                 average = float3(0., 0., 0.);
    64.  
    65.                 for (float x = -1.5; x <= 1.5; x++) {
    66.                     for (float y = -1.5; y <= 1.5; y++) {
    67.  
    68.                         float3 c =  tex2D(_MainTex, i.uv + _MainTex_TexelSize.xy*float2(x, y));
    69.                         float  m =  tex2D(_IlsandMap, i.uv + _MainTex_TexelSize.xy*float2(x, y));
    70.  
    71.                                n += step(0.1, m);
    72.                          average += c * step(0.1, m);
    73.  
    74.                     }
    75.                 }
    76.  
    77.                 average /= n;
    78.             }
    79.        
    80.             col.xyz = average;
    81.        
    82.                 return col;
    83.             }
    84.             ENDCG
    85.         }
    86.     }
    87.     Fallback Off
    88. }
    89.  

    - Unity Project https://www.dropbox.com/s/gtuij4qcm1qmcl8/TexturePaint-master.rar?dl=0

    - GitHub https://github.com/IRCSS/TexturePaint/blob/master/Assets/Scripts/TexturePaint.cs

    I made a few changes to my Unity Project to solve other issues you can see the problems I had before here
    https://forum.unity.com/threads/cus...g-the-platform-to-mobile.824139/#post-5501224

    Thank you.

    Update: After more reaserch I found out that the problem might be becasue of Render Textures with the depth set to 0. I have to try some things and find out if something works.

    Update 2: I tested this on an iPhone 8 and now has a different effect. The white edge is still there but I when I paint with a different color the object changes colors to that. e.g I press on the red color the object instantly changes to that red color and keeping the white edge.
     
    Last edited: Feb 27, 2020
    Nukeape likes this.