/src/away3d/filters/tasks/Filter3DBlurTask.as
ActionScript | 119 lines | 92 code | 26 blank | 1 comment | 15 complexity | 1f3aff15f5adef98d0f21605600a9a4d MD5 | raw file
1package away3d.filters.tasks 2{ 3 import away3d.cameras.Camera3D; 4 import away3d.core.managers.Stage3DProxy; 5 6 import flash.display3D.Context3DProgramType; 7 8 import flash.display3D.textures.Texture; 9 10 public class Filter3DBlurTask extends Filter3DTaskBase 11 { 12 private static const MAX_BLUR : int = 6; 13 private var _blurX : uint; 14 private var _blurY : uint; 15 private var _data : Vector.<Number>; 16 private var _stepX : Number = 1; 17 private var _stepY : Number = 1; 18 private var _numSamples : uint; 19 20 public function Filter3DBlurTask(blurX : uint = 3, blurY : uint = 3) 21 { 22 super(); 23 _blurX = blurX; 24 _blurY = blurY; 25 _data = Vector.<Number>([0, 0, 0, 1, 0, 0, 0, 0]); 26 } 27 28 public function get blurX() : uint 29 { 30 return _blurX; 31 } 32 33 public function set blurX(value : uint) : void 34 { 35 _blurX = value; 36 37 if (_blurX > MAX_BLUR) _stepX = _blurX/MAX_BLUR; 38 else _stepX = 1; 39 40 invalidateProgram3D(); 41 updateBlurData(); 42 } 43 44 public function get blurY() : uint 45 { 46 return _blurY; 47 } 48 49 public function set blurY(value : uint) : void 50 { 51 _blurY = value; 52 53 invalidateProgram3D(); 54 updateBlurData(); 55 } 56 57 override protected function getFragmentCode() : String 58 { 59 var code : String; 60 61 _numSamples = 0; 62 63 code = "mov ft0, v0 \n" + 64 "sub ft0.y, v0.y, fc0.y\n"; 65 66 for (var y : Number = 0; y <= _blurY; y += _stepY) { 67 if (y > 0) code += "sub ft0.x, v0.x, fc0.x\n"; 68 for (var x : Number = 0; x <= _blurX; x += _stepX) { 69 ++_numSamples; 70 if (x == 0 && y == 0) 71 code += "tex ft1, ft0, fs0 <2d,nearest,clamp>\n"; 72 else 73 code += "tex ft2, ft0, fs0 <2d,nearest,clamp>\n" + 74 "add ft1, ft1, ft2 \n"; 75 76 if (x < _blurX) 77 code += "add ft0.x, ft0.x, fc1.x \n"; 78 } 79 if (y < _blurY) code += "add ft0.y, ft0.y, fc1.y \n"; 80 } 81 82 code += "mul oc, ft1, fc0.z"; 83 84 _data[2] = 1/_numSamples; 85 86 return code; 87 } 88 89 override public function activate(stage3DProxy : Stage3DProxy, camera3D : Camera3D, depthTexture : Texture) : void 90 { 91 stage3DProxy.context3D.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, _data, 2); 92 } 93 94 override protected function updateTextures(stage : Stage3DProxy) : void 95 { 96 super.updateTextures(stage); 97 98 updateBlurData(); 99 } 100 101 private function updateBlurData() : void 102 { 103 // todo: must be normalized using view size ratio 104 var invW : Number = 1/_textureWidth; 105 var invH : Number = 1/_textureHeight; 106 107 if (_blurX > MAX_BLUR) _stepX = _blurX/MAX_BLUR; 108 else _stepX = 1; 109 110 if (_blurY > MAX_BLUR) _stepY = _blurY/MAX_BLUR; 111 else _stepY = 1; 112 113 _data[0] = _blurX*.5*invW; 114 _data[1] = _blurY*.5*invH; 115 _data[4] = _stepX*invW; 116 _data[5] = _stepY*invH; 117 } 118 } 119}