How to add transparency with a shader in SceneKit?

后端 未结 3 1327
不思量自难忘°
不思量自难忘° 2021-01-13 16:31

I would like to have a transparency effect from an image, for now I just test with a torus, but the shader does not seem to work with alpha. From what I understood from this

相关标签:
3条回答
  • 2021-01-13 17:02

    I was struggling with this problem too. Finally I found out that to make '#pragma transparent' work, I had to add it to another shader other than the one executing my transparency code.

    For example, I added transparency code to the surface shader, and added '#pragma transparent' to the geometry shader. The Apple API document also added '#pragma transparent' to the geometry shader, don't know if they were intended to do so.

    NSString *geometryScript = @""
    "#pragma transparent";
    
    NSString *surfaceScript = @""
    //"#pragma transparent" // You must not put it together with the transparency code
    "float a = 0.1;"
    "_surface.diffuse = vec4(_surface.diffuse.rgb * a, a);";
    
    // This works for the transparency code in surface shader too.
    //NSString *fragmentScript = @""
    //"#pragma transparent";
    
    yourMaterial.shaderModifiers = @{SCNShaderModifierEntryPointGeometry:geometryScript,
    SCNShaderModifierEntryPointSurface:surfaceScript};
    

    This code works in iOS 11.2, Xcode 9.2.

    This rule applies to SCNShaderModifierEntryPointFragment shader as well. Likewise, if you want to change transparency there, you can add '#pragma transparent' to the geometry shader or the surface shader. I haven't tested SCNShaderModifierEntryPointLightingModel shader.

    If you don't add any '#pragma transparent' to a shader, a black background may be blended with the transparent pixels.

    0 讨论(0)
  • 2021-01-13 17:10

    SceneKit uses premultiplied alpha (r, g and b fields should be multiplied by the desired a) :

    vec4(0.0, 0.2, 0.0, 0.2); // `vec4(0.0, 1.0, 0.0, 1.0) * alpha` with alpha = 0.2
    
    0 讨论(0)
  • 2021-01-13 17:12

    Adding transparency can be quite easily done in the SCNShadable Surface or Fragment entry point

    The SCNShaderModifierEntryPointSurface entry point version

    #pragma transparent
    #pragma body
    
    _surface.diffuse.a = 0.5;
    

    The SCNShaderModifierEntryPointFragment entry point version

    #pragma transparent
    #pragma body
    
    _output.color.a = 0.5;
    
    0 讨论(0)
提交回复
热议问题