• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
2
Question by OC_Raiz · Aug 28, 2016 at 12:13 PM · c#shader

Unity (Shader) / Writing and reading Computebuffer in a Shader

I'm trying to write into a Computebuffer in the fragment shader, but it doesn't work.

First I'm creating a new Computebuffer and writing into a Computebuffer inside my C# code (a red screen)

After it's been written, I'm reading that buffer from a shader (works)

Next I'm using another shader to fill the buffer with some gradient. This should work - but it doesn't work.

When I'm reading the buffer again - I'm still seeing the red screen.

Does anyone here have an idea why? And how I can get to write things into the Computebuffer while I'm in the Fragment Shader?

My Code: (bufferScript.cs) (bind to Main Camera to test)

 using UnityEngine;
 using System.Collections;
 using System.IO;
 
 [ExecuteInEditMode]
 public class bufferScript : MonoBehaviour
 {
     public bool writeBufferOn;
     public bool readBufferOn;    
     public ComputeBuffer myBuffer;
     public Material writeBufferMat;
     public Material readBufferMat;
 
     void Update()
     {
         if (readBufferMat == null)
         {
             readBufferMat = Resources.Load<Material>("readBufferMat") as Material;
         }
         if (readBufferMat.shader == null)
         {
             readBufferMat.shader = Resources.Load<Shader>("readBufferShader") as Shader;
         }
         if (writeBufferMat == null)
         {
             writeBufferMat = Resources.Load<Material>("writeBufferMat") as Material;
         }
         if (writeBufferMat.shader == null)
         {
             writeBufferMat.shader = Resources.Load<Shader>("writeBufferShader") as Shader;
         }
         if (myBuffer == null)
         {            
             // initial fill buffer with red pixels
             myBuffer = new ComputeBuffer(Camera.main.pixelWidth * Camera.main.pixelHeight, 3*sizeof(float), ComputeBufferType.Default);
             float[] v = new float[Camera.main.pixelWidth * Camera.main.pixelHeight * 3];
             for (int c = 0; c < Camera.main.pixelWidth * Camera.main.pixelHeight * 3; c+=3)
             {
                 v[c+0] = 1.0f;
                 v[c+1] = 0.0f;
                 v[c+2] = 0.0f;
             }
             myBuffer.SetData(v);
         }
     }   
 
 
     void OnRenderImage(RenderTexture source, RenderTexture destination)
     {        
         if (writeBufferOn == true)
         {
             Graphics.ClearRandomWriteTargets();
             writeBufferMat.SetPass(0);
             writeBufferMat.SetInt("_width", Camera.main.pixelWidth);
             writeBufferMat.SetInt("_height", Camera.main.pixelHeight);
             writeBufferMat.SetBuffer("_myBuffer", myBuffer);
             Graphics.SetRandomWriteTarget(1, myBuffer);
             Graphics.Blit(source, destination, writeBufferMat);
             Graphics.ClearRandomWriteTargets();
 
             // expecting red/blue to be 0 and green with gradient from 0 to 1 across screen width
             float[] v = new float[Camera.main.pixelWidth * Camera.main.pixelHeight * 3];
             myBuffer.GetData(v);
             if (v[3 * 0 + 0] != 0.0f)
             {
                 print("Still red, write to compute buffer failed!");
             }
         }
         if (readBufferOn == true)
         {
             Graphics.ClearRandomWriteTargets();
             readBufferMat.SetPass(0);
             readBufferMat.SetInt("_width", Camera.main.pixelWidth);
             readBufferMat.SetInt("_height", Camera.main.pixelHeight);
             readBufferMat.SetBuffer("_myBuffer", myBuffer);
             Graphics.Blit(source, destination, readBufferMat);
         }
     }
 
     //garbage collector extra 
     void OnDisable()
     {
         if (myBuffer != null)
             myBuffer.Dispose();
         myBuffer = null;
     }
 }



My Shader (readBufferShader)

 Shader "custom/readBufferShader" 
 {
     SubShader
     {
 
         Pass
         {
             CGPROGRAM
             #include "UnityCG.cginc"
             #pragma target 5.0
             #pragma vertex vert
             #pragma fragment frag           
 
             struct v2f
             {
                 float4 pos : SV_POSITION;
                 float4 uv : TEXCOORD0;
                 float4 scrPos : TEXCOORD1;
             };
 
             //Vertex Shader
             v2f vert(appdata_base v)
             {
                 v2f o;
                 o.pos = mul(UNITY_MATRIX_MVP, v.vertex);
                 o.scrPos = ComputeScreenPos(o.pos);
                 o.uv = float4(v.texcoord.xy, v.texcoord.z, 1);
                 return o;
             }
 
             //Fragment Shader
             int _width;
             int _height;
             StructuredBuffer<float3> _myBuffer : register(u1);
 
             half4 frag(v2f i) : COLOR
             {
                 int x = int(i.scrPos.x * _width);
                 int y = int(i.scrPos.y * _height);
                 float3 value = _myBuffer[(y * _width) + x]; // reading the buffer works
                 return half4(value, 1);             
             }
 
             ENDCG
         }
     }   
 }

My other Shader (writeBufferShader)

 Shader "custom/writeBufferShader" 
 {
     SubShader
     {
 
         Pass
         {
             CGPROGRAM
             #include "UnityCG.cginc"            
             #pragma target 5.0
             #pragma vertex vert
             #pragma fragment frag           
 
             struct v2f
             {
                 float4 pos : SV_POSITION;
                 float4 uv : TEXCOORD0;
                 float4 scrPos : TEXCOORD1;
             };
 
             //Vertex Shader
             v2f vert(appdata_base v)
             {
                 v2f o;
                 o.pos = mul(UNITY_MATRIX_MVP, v.vertex);                
                 o.scrPos = ComputeScreenPos(o.pos);
                 o.uv = float4(v.texcoord.xy, v.texcoord.z, 1);
                 return o;
             }
 
             //Fragment Shader
             int _width;
             int _height;
             RWStructuredBuffer<float3> _myBuffer : register(u1);
 
             half4 frag(v2f i) : COLOR
             {   
                 int x = int(i.scrPos.x * _width);
                 int y = int(i.scrPos.y * _height);
                 _myBuffer[(y * _width) + x] = float3(0, i.scrPos.x, 0); // buffer should be written here, but nothing happens!
                 return half4(1,1,1,1);
             }
 
             ENDCG
         }   
     }
 }



Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image oc70984 · Aug 29, 2016 at 08:30 AM 0
Share

is there any solution to this problem?

avatar image sam-perisentient · Oct 26, 2017 at 06:53 PM 0
Share

For others who find this page, more info on this topic is here: https://forum.unity.com/threads/how-to-write-to-an-unordered-access-compute-buffer-from-a-pixel-shader.403783/

0 Replies

· Add your reply
  • Sort: 

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

8 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Triggering timed dissolve in shader graph via a C# coroutine 2 Answers

No shadows when building with WebGL? 1 Answer

Using PBR shader and dynamically switching values 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges