Search Unity

SE Natural Bloom Dirty Lens

Discussion in 'Assets and Asset Store' started by sonicether, Apr 29, 2014.

  1. gian-reto-alig

    gian-reto-alig

    Joined:
    Apr 30, 2013
    Posts:
    756
    Hi

    I bought this asset and tried to use it in my game prototype. But everytime I add it to any of my cams, I get this message: "The camere is either not HDR enabled...."... but all of my cameras are!

    Now, I have 2 game cameras (two player splitscreen) that then get routed through a third camera (NGUI Camera)... I have mutliple effects on my game cameras, but even setting your effect up as the first effect in the stack on the game cameras does not help.

    Adding it to the NGUI Cameras, where I had the standart unity bloom effect until now (only Image Effect there), switching the unity bloom effect off and ignoring the warning message, I don't get any bloom, but instead the image is now upside down!

    Any Idea what could be the problem? Could it be because I use deferred lighting?


    Thanks for any help


    Gian-Reto
     
  2. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    Try selecting Game view and then Scene view again. I had the same problem and switching views fixed it.
     
  3. djweinbaum

    djweinbaum

    Joined:
    Nov 3, 2013
    Posts:
    533
    The skybox texture is LDR, and indeed the highlights are a bit clipped, however I'm able to boost the intensity with the skyshop sky settings. I think I've found the my problem. The delta that you need between brightnesses to actually see bloom is insane. The only thing that I have found that actually has enough brightness to cause bloom is the packaged emission shaders. I think the following examples better encapsulate my problem:

    $ES-Washing.jpg

    To get my sky to bloom even a tiny bit I need to boost the crap out of my sky and also boost the crap out of the bloom intensity slider. For whatever reason boosting the bloom intensity washes out the scene indiscriminately. I don't understand why it should do that. You can see that even when I cover the light hole my scene is still "blooming". That hole is substantially brighter than the rocks. Why is it not blooming substantially more? Why is my scene blooming when every pixel of it is dark? Even a skybox multiplier of 10 in skyshop is not enough to get the lens dust going. In order to keep my bloom intensity low, but still get my sky to bloom, I'd need a sky that was at least 30 times brighter than everything else.

    I want to further illustrate my point with the following example:

    $bloom_value_madness.jpg

    Your emission shader blooms wonderfully! However, TWO unity directional lights each maxed out at 8.0 (this is the highest unity will let you go) are shining through a hole I carved, and that sun spot (its on the stairs, don't mind the bright veggies, they get messed up with suns that bright) is not even close to enough brightness to bloom like your emission shader with only the slightest amount of boost. Am I making any sense? Am I crazy?

    If people have gotten this bloom to work well in their scenes, I'd love to see screenshots as a reference of what this effect is supposed to look like. Sonic Ether, I'd like to propose more sliders for control over the brightness delta required to see substantial bloom and dust. I don't know if the math would allow it, and certainly if I'm the odd one out here, by all means, it wouldn't be prudent to waste time on my specific issues, but more sliders for better control would help me out greatly. I do really dig the effect when I can manage to actually get it blooming. You've done a great job!
     
    Last edited: May 4, 2014
  4. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    Some more eye candy I created using this awesome package. Don't mind the incorrect CAT III approach lighting. I didn't finish that yet.

    Note that there are some center and edge lights missing. This is caused by the lights being too small at a distance. This also causes shimmering. Perhaps they could be scaled up but that would make them more bright as well. If Sonic Ether knows a solution for this, that would be glad to hear it.

    Two different approach lighting intensities at day:
    $runway day low.png
    $runway day high.png

    Same approach lighting intensity in fog, from far and closer to the threshold.
    $runway fog far.png
    $runway fog near.png

    Two different approach lighting intensities at night:

    $runway night high.png
     
    Last edited: May 4, 2014
  5. RB_lashman

    RB_lashman

    Joined:
    Aug 15, 2013
    Posts:
    92
    ooooh!! :) the last screenshot looks like something from TRON :) nice!!
     
    Last edited: May 4, 2014
  6. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    Yes, pretty isn't it? And it looks very similar to real life if they crank up the intensity, which they don't like to do by the way. Because of the electricity bill I guess.

    Not sure if my PC uses more juice if I crack up the bloom though :cool:

    Next step: directional lights. Perhaps with a Look Up Texture to set the intensity.
     
    Last edited: May 4, 2014
  7. RB_lashman

    RB_lashman

    Joined:
    Aug 15, 2013
    Posts:
    92
    nope, it doesn't care :p it's an image effect - it's always applied to the entire image :)
     
  8. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    Sonic Ether, can you build this into the shader?

    http://en.wikipedia.org/wiki/Inverse-square_law
    The intensity (or illuminance or irradiance) of light or other linear waves radiating from a point source (energy per unit of area perpendicular to the source) is inversely proportional to the square of the distance from the source; so an object (of the same size) twice as far away, receives only one-quarter the energy (in the same time period).
    $500px-Inverse_square_law.svg.png

    And how about a directional light? Should that logic live inside the shader or is it better that we build a solution for that individually?
     
    Last edited: May 5, 2014
  9. WGermany

    WGermany

    Joined:
    Jun 27, 2013
    Posts:
    78
    I actually have done this with point lights, so I guess it is possible. (And I hope he reads my post from before).
     
    Last edited: May 5, 2014
  10. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    Would it be possible to stick the dirty lens textures on a window of a cockpit, car, etc instead of the screen itself? This would solve the VR issue as well.
     
    JayG81 likes this.
  11. DrewMedina

    DrewMedina

    Joined:
    Apr 1, 2013
    Posts:
    418
    I did that, but it doesnt react the same way your demo does... No hotspots...
    Would it need to be a shader or can you suggest a shader?
    Im using a standard transparent (away from it right now).. They are great textures though
     
  12. greenmonster

    greenmonster

    Joined:
    Jan 18, 2013
    Posts:
    26
    Hi,

    I purchased this asset shortly after it was made available, and while there was a little bit of a misunderstanding that HDR needed to be involved, I still think that this is an asset worth keeping as a tool in my toolbox after having played with it in an empty project.

    Like others here, I'm experimenting with its use in VR, and am quite pleased with its potential so far. The dirty lens offset not being correct is OK for now -- not the end of the world as no one should really be focusing on something as close to the eyes as goggle/helmet glass etc.

    However, the main issue I've run into now is that something intensely bright (like the Sun, or other bright alien star) will "pop" into view rather suddenly if the resulting bloom is large enough. I'm not sure I can argue that this is physically incorrect, but combined with the way each eye has its own offset frustum, this popping will occur for each eye at different times as the user swivels his head around. Here's a video to demonstrate:



    Aside from turning down the intensity of the Sun's "Emission Gain" (it's using the included Emissive/Textured shader), I'm not sure if this is something that could be worked around. Do you know of a way I could soften the onset of big and bright bloom, that could help mask the problem?

    Not the end of the world if this isn't a solvable problem, but I can see times where I'd like something big and bright in a scene. The bigger it is, the more noticeable the popping going from eye to eye.

    Thanks again for this!
     
  13. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
  14. gian-reto-alig

    gian-reto-alig

    Joined:
    Apr 30, 2013
    Posts:
    756
    Hi Sonic Ether

    After some activation / deactivation of the image effect, the warning went away.

    Still, the effect does not work as intended: no bloom, it only turns the whole image upside down (besides the OnGUI stuff).

    Any idea what I can do here?

    Regards

    Gian-Reto
     
  15. greenmonster

    greenmonster

    Joined:
    Jan 18, 2013
    Posts:
    26
    Is it possible you have MSAA turned on in the Quality Settings? I see upside down image also if I try to use MSAA with HDR and Forward rendering.
     
  16. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,775
    You could possibly hack around this problem by hardcoding an "alpha-only" light source that, in LateUpdate or both eyes' OnWillRenderCamera, sets its vector to the leftmost visible point on the camera's view frustum, and "ramps" its brightness based on the nearness of the sun light to the edge of the frustum. Not a pretty or easy hack, but doable. And, I do agree that the "popping" is a huge distraction from the realism of that scene.
     
  17. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    I think that the bloom fade in/out caused by camera movement should not be present at all in VR. The bloom should always be visible and not change intensity if the light source is partially obscured by the camera.

    Think about it, when was the last time you saw headlights of a car bloom into existence when the light entered the view frustum of your eyes? This effect only happens in real life when a light source is obscured by another object, but the FOV of your eyes have no effect on it, or at least not noticeably.

    Perhaps rendering the scene with a bigger FOV and then cropping the result will fix this issue. It would be better if there is a VR version of the shader though.
     
    Last edited: May 5, 2014
  18. greenmonster

    greenmonster

    Joined:
    Jan 18, 2013
    Posts:
    26
    Wow, creative solution there. I like it. :) Thank you tons!
     
  19. sonicether

    sonicether

    Joined:
    Jan 12, 2013
    Posts:
    265
    Adding a slider that decreases the delta required to see substantial bloom would break the physical accuracy of this effect. Real life doesn't scatter light differently based on how bright it is. All light scatters the same. Implementing a "threshold" or a slider like you have described would break conservation of energy and break the physical accuracy of this effect. I have put an emphasis on physical accuracy when developing this shader, and I believe that with the right workflow the benefits are quite awesome. I actually think that outdoor sunny image you've got there looks quite nice bloom-wise!

    Again, I can't stress enough the importance of HDR, especially with your skybox. Clipping basically makes effects reliant on large brightness differences effectively useless. Your eyes will thank you for using an HDR skybox.

    One thing you can try to get brighter lights, which is what I do with my projects, is try decreasing the overall brightness of all lights/lighting in your game. This increases headroom for brighter lights. It's unfortunate that a true HDR workflow takes extra work in Unity, but there's not too much I can do about that. Let's hope that Unity 5 ends up making life easier for those who want their scenes to be truly HDR, which really is an absolute necessity for a high-quality impressive look in a game.


    This is a great idea! Perhaps I can extend the effect to dirty windows in 3D space. I've already got a concept for how that may work. This will be something worth experimenting with.


    Ultimately I can't really do testing or development for VR because I do not have the hardware with which to test/develop. All I can really say about the matter is this. If light hasn't entered a lens at all, it can't have an opportunity to scatter within it. This applies to both cameras and the human eye, though it is less noticeable with the human eye for many reasons, one of which is likely for a similar reason that our brains "filter out" the transitional state while moving our eyes to look at something else. However, that is a completely separate matter than how distracting the "popping" may be during a VR experience.

    I was actually just testing this "IRL" with my phone's quite bright LED. If the light is entering from the right, my right eye can see "bloom" before the left eye, because my nose is obstructing the light from entering my left eye. Of course, the opposite can be said when light enters from the left.

    However, in order for me to observe the problem and develop a solution, I would need the hardware for it. I simply don't have access to VR. For this reason, development is exceedingly difficult for something I cannot directly test. Iteration is many orders of magnitude slower than it needs to be for effective development. Perhaps in the future, if I can spare the cash, I'll pick up an OR and see what I can do.
     
    Last edited: May 6, 2014
  20. greenmonster

    greenmonster

    Joined:
    Jan 18, 2013
    Posts:
    26
    I really appreciate that you took the time to look into it a bit. I'm working around the popping for now by simply not having such an intense bright light source as that will give the light source some room to appear in both eyes by the time the user notices it.

    And I definitely recommend getting an OR. :) If you're a developer, it's basically a whole new world.
     
  21. RB_lashman

    RB_lashman

    Joined:
    Aug 15, 2013
    Posts:
    92
    oh, we definitely want to get our hands on OR ... but those things don't grow on trees, you know ;)
     
  22. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    How about the light attenuation issue I posted on page 3?
     
  23. Binary42

    Binary42

    Joined:
    Aug 15, 2013
    Posts:
    207
    I have a quick question so i can make a purchase decision: Are these Shaders source or compiled?
    Sorry if this was answered before.
     
  24. sonicether

    sonicether

    Joined:
    Jan 12, 2013
    Posts:
    265
    I am planning another asset that covers light attenuation and HDR workflow with lights in Unity. It is somewhat irrelevant to this effect.

    They are source.
     
  25. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    One thing I noticed is that if the color is shifted all the way to the right, the white highlight disappears:
    $red.png

    Of the color is shifted a bit to the left (I think as little as 1 value will do), the white highlight does appear.
    $white.png

    Is this intentional?
     
  26. jaijai76

    jaijai76

    Joined:
    Aug 5, 2013
    Posts:
    21
    Don't know if any body here is familiar to unistorm but i would like the unistorm sun to work well with this effect and am not sure how to go about it. do i just add my own material to it and configure it to change color a bit with the unistorm lighting?
     
  27. sonicether

    sonicether

    Joined:
    Jan 12, 2013
    Posts:
    265
    It is not explicitly intended, but a natural result of what's going on and the way that RGB color is computed in computer graphics. In your first image, there's a tiny bit of green and blue in the material color. Due to color clipping, eventually if things get bright enough, those tiny amounts of green and blue light "catch up" to the amount of red (because red is clipped at 255), and that's why the white highlight appears. Any 100% pure color is not going to have a highlight that causes hue shifting like that. It is just how light works.

    When going for a pure red, I actually like to go with something like R = 255, G = 5, B = 0. A tiny bit of green will allow the brightest part of the highlight to shift towards yellow.

    So if you'd like to see hue shifting, make sure to avoid 100% pure colors.
     
  28. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    Thanks for the tip. Playing around with that makes for some interesting effects.

    Edit:
    How can I make the Softparticle shader always render on top of everything (without using camera layers)? ZTest Always doesn't do anything.
     
    Last edited: May 7, 2014
  29. PureSpider

    PureSpider

    Joined:
    Oct 25, 2013
    Posts:
    3
    I'd really love a "demo" version of this asset (which can have "SONIC ETHER" in huge letters all over the screen or so), just to see how the effect fits in my specific game before buying.
     
  30. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    Some suggestions:

    Animated raindrops on a windshield would be a really nice effect.
    Some more light textures (like separticle.png) with different highlight sizes would be useful.
     
  31. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    Here is web player which uses the bloom shader form Sonic Ether.

    $approach lights color tweak.png

    Controls:

    AWSD = move horizontally.
    QE = move vertically.
    Mouse look = click on screen, click again or ESC to stop mouse look.
    Scroll wheel = increase / decrease move speed multiplier.

    Theory:

    Scale vs Distance: If lights are far away, they can be smaller then one screen pixel. This causes the lights to shimmer or not show up at all. If this setting is enabled, the further away the light is, the larger the scale. This gets rid of the simmer and light disappearance issue. Also, in real life light sources which are further away appear larger then nearby objects of the same size.

    Emission Gain vs Distance: Lights which are further away should be less bright due to the inverse square law. This is currently not implemented in the bloom shader, so this setting fixes that.

    Global Bloom: increase/decrease the bloom of all lights, regardless of distance.

    Tone Mapping: the exposure time of the camera.

    Lens Dirt amount: post processing special effect which simulates light refractions caused by dirt/scratches on the lens.

    Fog, Time of Day, Field of View: self explanatory.

    Web player link:
    https://googledrive.com/host/0Bwk4bDWv3jAcTF80TWRPeDliMU0/Web Player.html
     
    Last edited: May 10, 2014
  32. NeatWolf

    NeatWolf

    Joined:
    Sep 27, 2013
    Posts:
    924
    I'm working on a historical reconstruction and I'm under NDA so I can't still show you the pics, but I have to say:
    it's a must have, the improvement is dramatic.

    As I also expressed as a wish by email, lens streaks or being able to change the shape of the distribution (Eg:circular to triangle or exagon) would be great.

    Also, it works *wonderfully* in conjunction with other lens-based assets, by using the same dirt texture :p

    I can't wait for more assets from SonicEther to show up ^^
     
  33. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    Is anyone else experiencing a black screen with high quality and resolution settings when using the SE bloom shader and the Oculus Rift? I have seen this problem pop up already on 3 different PC's.
     
  34. paraself

    paraself

    Joined:
    Jun 30, 2012
    Posts:
    139
    Tested on Ipad 4, very basic scene with circle bouncing within screen. no more than 10 fps, so I guess it's not that mobile friendly.
    $IMG_0007.jpg
     
  35. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    I noticed that real world lights brightness is not the only thing which attenuates over distance. The color attenuates over distance as well. For example, white lights turn to yellow further away and then to amber when even further away.

    If you could address this in the new package you reported working on, that would be awesome.
     
  36. jaijai76

    jaijai76

    Joined:
    Aug 5, 2013
    Posts:
    21
    I was wondering if anybody can tell me how to make a good sun with this. Iv had attempts but they don't turn out quite as well as i wanted, it would be good if i could get a sun as good as the sun djweinbaum achieved on page 2

    This is irrelevant but is this sonicether the same one who made the shader mod on minecraft?

    By the way how did Elecman manage to make all those options for the bloom?
     
    Last edited: May 18, 2014
  37. RB_lashman

    RB_lashman

    Joined:
    Aug 15, 2013
    Posts:
    92
    yeah - one and the same :)
     
  38. NeatWolf

    NeatWolf

    Joined:
    Sep 27, 2013
    Posts:
    924
    Here's the before/after of a scene (from an asset on sale today), by using SE Natural Bloom and other well known packages.
    I'm totally in love with your bloom Sonicether, please continue to surprise us! :D

    Before:
    $SSRR02 OFF.jpg

    After some tweaks and also with SE Natural Bloom:
    $SSRR02.jpg
     
    Last edited: May 16, 2014
  39. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    Does anyone else get a black screen when: the bloom shader is used with the following settings?:

    -Windows standalone exe
    -Anti Aliasing enabled

    SE, can you confirm this is an issue?
     
    Last edited: May 17, 2014
  40. KRGraphics

    KRGraphics

    Joined:
    Jan 5, 2010
    Posts:
    4,466
    Dude, that looks INSANELY cool... definitely gonna purchase this. And I would love to see more Post FX from you, my favourite being aberration :)
     
  41. djweinbaum

    djweinbaum

    Joined:
    Nov 3, 2013
    Posts:
    533
    Are you certain what you're seeing isn't the light scattering from the fog volume asset?
     
  42. Binary42

    Binary42

    Joined:
    Aug 15, 2013
    Posts:
    207
    Last edited: May 22, 2014
  43. DrewMedina

    DrewMedina

    Joined:
    Apr 1, 2013
    Posts:
    418
    Are you still planning to give an offset for using the dirt in VR? I hope so!
    Thanks
     
  44. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
  45. HanSol0

    HanSol0

    Joined:
    Aug 16, 2012
    Posts:
    3
    The results in my space game are really great, except that it flips the image upside-down when you're using a camera that has a clear flag of Depth Only. Any known workarounds to this, or is it a known bug?
     
  46. Binary42

    Binary42

    Joined:
    Aug 15, 2013
    Posts:
    207
    I had this problem when my cams used different rendering paths, check that AA is disabled in the Quality settings too.
     
  47. HanSol0

    HanSol0

    Joined:
    Aug 16, 2012
    Posts:
    3
    Thanks for the reply, Binary42. All my cams are set to "Use Player Settings", which is inheriting the Forward rendering path. AA is disabled in all quality settings. Any time I put the SENBDL script on a camera with the Depth Only clear flag, it flips the rendered image vertically for that camera and all cameras rendering the depth below it. Setting the render paths explicitly don't seem to fix it either.
     
  48. Binary42

    Binary42

    Joined:
    Aug 15, 2013
    Posts:
    207

    Well, at least i can confirm that problem. ;) Also SENBDL stops renderig. However, Clear Flags seem to work with Deffered Lighting correctly, but since DL requiers shader model 3.0 i'll queue up for a solution.
     
  49. Elecman

    Elecman

    Joined:
    May 5, 2011
    Posts:
    1,371
    If you are using the SE/Particles/Additive shader (or any bloom shader for that matter) and want to play around with different light textures, you might find this script helpful.

    It creates a flare texture in the editor in Scene or Play mode. It can save the texture to a png or upload it directly to the material so you can test the result at runtime with fast iterations.

    Be sure not to set the Emission Gain too high, otherwise the nice colored highlight effect will get over saturated.

    $inspector.jpg

    Usage:
    -Place FlareCreatorEditor.cs in the Editor folder.
    -Place FlareCreator.cs on the GameObject or prefab where the SE material resides.
    -Adjust the variables on the Inspector and then press Apply. Note that textures larger than 512 might take a while to generate.
    -Click Save in case you want to dump the texture into the Assets folder root.

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using UnityEditor;
    5.  
    6. [CustomEditor(typeof(FlareCreator))]
    7. public class FlareCreatorEditor : Editor {
    8.  
    9.     public override void OnInspectorGUI(){
    10.  
    11.         FlareCreator t = (FlareCreator)target;
    12.  
    13.         t.useInputTexture = EditorGUILayout.Toggle("Use Texture as Input", t.useInputTexture);
    14.  
    15.         if(t.useInputTexture){
    16.  
    17.             t.originalTexture = (Texture2D)EditorGUILayout.ObjectField("Input Texture", t.originalTexture, typeof(Texture), false);
    18.         }
    19.  
    20.         if(t.modifiedTexture != null){
    21.  
    22.             t.modifiedTexture = (Texture2D)EditorGUILayout.ObjectField("Output Texture", t.modifiedTexture, typeof(Texture), false);
    23.         }
    24.  
    25.         if(!t.useInputTexture){
    26.  
    27.             t.textureSize = EditorGUILayout.IntField("Texture Size", t.textureSize);
    28.             t.circleColor = EditorGUILayout.ColorField("Circle Color", t.circleColor);
    29.             t.circleRadius = EditorGUILayout.IntField("Circle Radius", t.circleRadius);
    30.         }
    31.  
    32.         t.blurSize = EditorGUILayout.IntField("Blur Size", t.blurSize);
    33.         t.iterations = EditorGUILayout.IntField("Iterations", t.iterations);
    34.  
    35.         if(GUILayout.Button("Apply")){
    36.  
    37.             t.Apply();
    38.         }
    39.  
    40.         if(GUILayout.Button("Save")){
    41.  
    42.             t.Save();
    43.         }
    44.  
    45.         if (GUI.changed){
    46.  
    47.             EditorUtility.SetDirty(t);
    48.         }
    49.     }
    50. }
    51.  

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. using System.IO;
    5. using UnityEditor;
    6.  
    7. public class FlareCreator : MonoBehaviour {
    8.  
    9.     public Texture2D originalTexture;
    10.     public bool useInputTexture = true;
    11.     public int textureSize = 128;
    12.     public int circleRadius = 20;
    13.     public int blurSize = 9;
    14.     public int iterations = 5;
    15.     public Color circleColor = Color.white;
    16.  
    17.     [System.NonSerialized]
    18.     public Texture2D modifiedTexture;
    19.  
    20.     private float progress = 0f;
    21.     private float maxProgress = 0;
    22.  
    23.     private float avgR = 0;
    24.     private float avgG = 0;
    25.     private float avgB = 0;
    26.     private float blurPixelCount = 0;
    27.  
    28.     public void Apply(){
    29.  
    30.         if(useInputTexture){
    31.  
    32.             modifiedTexture = Blur(originalTexture, blurSize, iterations);
    33.         }
    34.  
    35.         else{
    36.  
    37.             modifiedTexture = CreateCircleTexture(circleRadius, circleColor);
    38.             modifiedTexture = Blur(modifiedTexture, blurSize, iterations);
    39.         }
    40.  
    41.          if(Application.isPlaying){
    42.  
    43.              renderer.material.SetTexture("_MainTex", modifiedTexture);
    44.          }
    45.  
    46.          else{
    47.  
    48.             renderer.sharedMaterial.SetTexture("_MainTex", modifiedTexture);
    49.          }
    50.     }
    51.  
    52.     Texture2D Blur(Texture2D image, int radius, int iterations){
    53.  
    54.         Texture2D tex = image;
    55.  
    56.         progress = 0f;
    57.  
    58.         maxProgress = (image.width + image.height) * iterations;
    59.  
    60.         for (var i = 0; i < iterations; i++) {
    61.  
    62.             tex = BlurImage(tex, radius, true);
    63.             tex = BlurImage(tex, radius, false);
    64.         }
    65.  
    66.         EditorUtility.ClearProgressBar();
    67.  
    68.         return tex;
    69.     }
    70.  
    71.     public void Save(){
    72.  
    73.         if(modifiedTexture != null){
    74.  
    75.             byte[] bytes = modifiedTexture.EncodeToPNG();
    76.             File.WriteAllBytes(Application.dataPath + "/SavedFlare.png", bytes);
    77.  
    78.             Debug.Log("Texture saved at: Assets/SavedFlare.png");
    79.         }
    80.  
    81.         else{
    82.  
    83.             Debug.Log("No texture selected or created");
    84.         }
    85.     }
    86.  
    87.     public Texture2D CreateCircleTexture(int r, Color col){
    88.  
    89.         Texture2D tex = new Texture2D(textureSize, textureSize);
    90.  
    91.         //set background to black
    92.         Color32[] backgroundColors = new Color32[textureSize * textureSize];
    93.  
    94.         for(int i = 0; i < backgroundColors.Length; i++){
    95.  
    96.             backgroundColors[i] = Color.black;
    97.         }
    98.  
    99.         tex.SetPixels32(backgroundColors);
    100.  
    101.         //get middle of texture
    102.         int cx = Mathf.CeilToInt((float)tex.width / 2f);
    103.         int cy = Mathf.CeilToInt((float)tex.height / 2f);
    104.  
    105.         int x, y, px, nx, py, ny, d;
    106.         Color32[] tempArray = tex.GetPixels32();
    107.  
    108.         for (x = 0; x <= r; x++){
    109.  
    110.             d = (int)Mathf.Ceil(Mathf.Sqrt(r * r - x * x));
    111.  
    112.             for (y = 0; y <= d; y++){
    113.  
    114.                 px = cx + x;
    115.                 nx = cx - x;
    116.                 py = cy + y;
    117.                 ny = cy - y;
    118.  
    119.                 tempArray[py*textureSize + px] = col;
    120.                 tempArray[py*textureSize + nx] = col;
    121.                 tempArray[ny*textureSize + px] = col;
    122.                 tempArray[ny*textureSize + nx] = col;
    123.             }
    124.         }
    125.  
    126.         tex.SetPixels32(tempArray);
    127.         tex.Apply ();
    128.  
    129.         return tex;
    130.     }
    131.  
    132.     Texture2D BlurImage(Texture2D image, int blurSize, bool horizontal){
    133.  
    134.         Texture2D blurred = new Texture2D(image.width, image.height);
    135.         int _W = image.width;
    136.         int _H = image.height;
    137.         int xx, yy, x, y;
    138.  
    139.         if (horizontal) {
    140.  
    141.             for (yy = 0; yy < _H; yy++) {
    142.  
    143.                 for (xx = 0; xx < _W; xx++) {
    144.  
    145.                     ResetPixel();
    146.  
    147.                     //Right side of pixel
    148.                     for (x = xx; (x < xx + blurSize  x < _W); x++) {
    149.  
    150.                         AddPixel(image.GetPixel(x, yy));
    151.                     }
    152.  
    153.                     //Left side of pixel
    154.                     for (x = xx; (x > xx - blurSize  x > 0); x--) {
    155.  
    156.                         AddPixel(image.GetPixel(x, yy));
    157.                     }
    158.  
    159.                     CalcPixel();
    160.  
    161.                     for (x = xx; x < xx + blurSize  x < _W; x++) {
    162.  
    163.                         blurred.SetPixel(x, yy, new Color(avgR, avgG, avgB, 1.0f));
    164.                     }
    165.                 }
    166.  
    167.                 progress++;
    168.                 ShowProgressBar();
    169.             }
    170.         }
    171.  
    172.         else {
    173.  
    174.             for (xx = 0; xx < _W; xx++) {
    175.  
    176.                 for (yy = 0; yy < _H; yy++) {
    177.  
    178.                     ResetPixel();
    179.  
    180.                     //Over pixel
    181.                     for (y = yy; (y < yy + blurSize  y < _H); y++) {
    182.  
    183.                         AddPixel(image.GetPixel(xx, y));
    184.                     }
    185.  
    186.                     //Under pixel
    187.                     for (y = yy; (y > yy - blurSize  y > 0); y--) {
    188.  
    189.                         AddPixel(image.GetPixel(xx, y));
    190.                     }
    191.  
    192.                     CalcPixel();
    193.  
    194.                     for (y = yy; y < yy + blurSize  y < _H; y++) {
    195.  
    196.                         blurred.SetPixel(xx, y, new Color(avgR, avgG, avgB, 1.0f));
    197.                     }                  
    198.                 }
    199.  
    200.                 progress++;
    201.                 ShowProgressBar();
    202.             }
    203.         }
    204.  
    205.         blurred.Apply();
    206.         return blurred;
    207.     }
    208.  
    209.     void AddPixel(Color pixel) {
    210.  
    211.         avgR += pixel.r;
    212.         avgG += pixel.g;
    213.         avgB += pixel.b;
    214.         blurPixelCount++;
    215.     }
    216.  
    217.     void ResetPixel() {
    218.  
    219.         avgR = 0.0f;
    220.         avgG = 0.0f;
    221.         avgB = 0.0f;
    222.         blurPixelCount = 0;
    223.     }
    224.  
    225.     void CalcPixel() {
    226.  
    227.         avgR = avgR / blurPixelCount;
    228.         avgG = avgG / blurPixelCount;
    229.         avgB = avgB / blurPixelCount;
    230.     }
    231.  
    232.     void ShowProgressBar(){
    233.  
    234.         float p = progress / maxProgress;
    235.         EditorUtility.DisplayProgressBar("Creating Texture...", Mathf.RoundToInt(p * 100f)+ " %", p);
    236.     }
    237. }
    238.  
    Credits go to the folks at the thread here:
    http://forum.unity3d.com/threads/185694-Contribution-Texture2D-blur-in-c
     
    Last edited: May 23, 2014
  50. sonicether

    sonicether

    Joined:
    Jan 12, 2013
    Posts:
    265
    Hi guys, sorry I've been away, I've been so busy juggling other projects!

    Looks like there are some bugs to fix, the worst of them being the vertically-flipped image issue. I think I have an idea of how to solve this. I'll work on this ASAP and let you guys know how that's going. When that's fixed I'll move on to slightly more minor bugs.

    Thank you guys for sharing and contributing to the discussion here. :)