aboutsummaryrefslogtreecommitdiff
path: root/src/main/resources/shaders/newton.glsl
blob: e53b1535e65f0e134b9a446b91e282204b051dee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#version 430
layout(local_size_x = 1, local_size_y = 1) in;

#include <utils>

#define MAX_ITERATIONS 200

const float antialiasing = 0.28;
uniform float seconds = 0;
layout(rgba8) uniform writeonly image2D output_image;

float fabs(float a) {
  return a > 0. ? a : -a;
}

float cosh(float val) {
  float tmp = exp(val);
  float cosH = (tmp + 1.0 / tmp) / 2.0;
  return cosH;
}

float sinh(float val) {
  float tmp = exp(val);
  float sinH = (tmp - 1.0 / tmp) / 2.0;
  return sinH;
}

vec2 cmul(vec2 a, vec2 b) {
  return vec2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x);
}

vec2 cdiv(vec2 a, vec2 b) {
  float denominator = b.x * b.x + b.y * b.y;
  if (denominator == 0.) return a;
  return cmul(a, vec2(b.x, -b.y)) / denominator;
}

vec2 cpow(vec2 z, int n) {
  vec2 res = z;
  for (int i = 0; i < 20; i++) {
    if (i >= n - 1) break;
    res = cmul(z, res);
  }
  return res;
}

vec2 cexp(vec2 z) {
  return exp(z.x) * vec2(cos(z.y), sin(z.y));
}

vec2 get_step(vec2 z) {
  vec2 value = cpow(z, 5) + 2.0 * cpow(z, 3) - vec2(1., 0.);
  vec2 derivative = 5.0 * cpow(z, 4) + 3.0 * cpow(z, 2);
  return cdiv(value, derivative);
}

vec3 image(vec2 uv) {
  vec2 prevZ;
  vec2 z = uv * 3.0;

  float t = seconds / 20;
  vec2 factor = vec2(mod(t + 0.1, 2), 0);

  int iterations = 0;
  for (int i = 0; i < MAX_ITERATIONS; i++) {
    prevZ = z;
    z = prevZ - cmul(factor, get_step(prevZ));

    iterations++;
    if (fabs(z.x - prevZ.x) < 0.001) break;
  }

  float val = float(iterations) * 10.0 / float(MAX_ITERATIONS);
  float r = 0.1;
  float g = min(val * 0.2, 0.7);
  float b = min(val * 0.8, 0.7);
  return srgb(r, g, b);
}

vec3 antialiased_image(vec2 uv) {
  vec2 resolution = vec2(imageSize(output_image).xy);
  float s = antialiasing / max(resolution.x, resolution.y);
  vec3 sum = vec3(0);
  int count = 0;
  for (int i = -2; i < 2; i++)
    for (int j = -2; j < 2; j++, count++)
      sum += image(uv + vec2(i, j) * s);
  return sum / count;
}

void main() {
  vec2 resolution = vec2(imageSize(output_image).xy);
  float aspect_ratio = resolution.y / resolution.x;
  vec2 uv = (gl_GlobalInvocationID.xy - resolution * 0.5) * vec2(1.0, aspect_ratio) / resolution;

  // vec3 color = image(uv);
  vec3 color = antialiased_image(uv);
  imageStore(output_image, ivec2(gl_GlobalInvocationID.xy), vec4(color, 1));
}