- Joined
- Jan 2, 2020
- Messages
- 569
Invincibility shader
Example how to use it :
code_language.cerberus:
Import mojo2
Function Main()
New MyApp
End
Class MyApp Extends App
Global image2:Image
Global imagecanvas2:Canvas
Field sourceImage : Image
Field canvas : Canvas
Field effect : ShaderEffect
Field x : Int = 0
Method OnCreate()
sourceImage = Image.Load("256x256.png",0,0,0)
effect = New ShaderEffect
canvas = New Canvas
image2=New Image(256,256,0,0,0)
imagecanvas2=New Canvas(image2)
SetUpdateRate 0
End
Method OnRender()
canvas.Clear 0, 0.5, 1, 1
canvas.DrawRect 0,0, 64,64
If MouseDown(0)
effect.Render sourceImage,image2 ; canvas.DrawRect x,0, 256*1,256*1,image2,0,0,256,256
Else
canvas.DrawRect x,0, 256*1,256*1,sourceImage,0,0,256,256
Endif
x = x + 1 ; If x >= 512 Then x = x - 512
canvas.Flush
End
End
Class myShader Extends Shader
Method New()
Build(LoadString("shader.glsl"))
End
Method OnInitMaterial:Void(material:Material)
material.SetTexture "ColorTexture",Texture.White()
End
Function Instance:myShader()
If Not _instance _instance=New myShader
Return _instance
End
Private
Global _instance:myShader
End
Class ShaderEffect
Private
Global _canvas:Canvas
Field _material:Material
Method New()
If Not _canvas _canvas=New Canvas
_material=New Material( myShader.Instance() )
End
Method Render:Void(source:Image,target:Image)
_material.SetTexture "ColorTexture",source.Material.ColorTexture
_canvas.Clear 0, 0, 0, 0
_canvas.SetRenderTarget target
_canvas.SetViewport 0,0,target.Width,target.Height
_canvas.SetProjection2d 0,target.Width,0,target.Height
_canvas.DrawRect 0,0,target.Width,target.Height,_material
_canvas.Flush
End
End
Code:
// Uniforms
uniform sampler2D ColorTexture; // sometimes called Texture0
// Constants
#define PI 3.14
// Functions
float luma(vec3 color) {
return dot(color, vec3(0.299, 0.587, 0.114));
}
float luma(vec4 color) {
return dot(color.rgb, vec3(0.299, 0.587, 0.114));
}
float dither2x2(vec2 position, float brightness) {
int x = int(mod(position.x, 2.0));
int y = int(mod(position.y, 2.0));
int index = x + y * 2;
float limit = 0.0;
if (x < 8) {
if (index == 0) limit = 0.25;
if (index == 1) limit = 0.75;
if (index == 2) limit = 1.00;
if (index == 3) limit = 0.50;
}
return brightness < limit ? 0.0 : 1.0;
}
vec4 dither2x2(vec2 position, vec4 color) {
return vec4(color.rgb * dither2x2(position, luma(color)), 1.0);
}
// Main function
void shader(){
// -------------------------------------------------------------------------------------------------
// Get coordinate
vec2 uv=(b3d_ClipPosition.st/b3d_ClipPosition.w)*0.5+0.5; // 0.0 - 1.0
vec2 p = vec2(floor(uv.x*256.0), floor(uv.y*256.0)); // 0 - 255
// Read pixel
vec4 color=texture2D(ColorTexture,uv).rgba;
// Write pixel
if (color.a != 0.0)
b3d_FragColor = dither2x2(p, color.rgba) ; // Pixel shadow invisibility effect
else
b3d_FragColor = color ;
// -------------------------------------------------------------------------------------------------
}
Example how to use it :