Changing the Perspective of CG with Shaders

Hello. I'm Hirayama from the Technology Department.
Today I want to talk about a technique I've been wanting to use in a product for about ten years now and still haven't managed to: changing the perspective of CG with a shader.
The code is on GitHub as a sample project. I think it works, but it has not been used in production. Please think of it purely as a sample.
Just run it first
Things will probably click faster if you try the WebGL build before reading.
- Try turning the toggle labeled
Projectionon and off. Off is the state without this article's processing. - Moving the slider changes the field of view.
- Turning on the toggle labeled
SampleGamestarts a crappy little game. It's like "a game you've seen somewhere, rolled into a cylinder and played while looking up at it from below." Compare how it feels while switchingProjectionon and off. You can move the viewpoint by dragging.
What is this doing?
Here's what it does.

In a scene with lots of cubes lined up, drawing it normally gives you the left image, but adding this article's processing gives you the right one.
The left image has these characteristics:
- Things stretch more the further they are from the center of the screen
- What was originally a straight line is also a straight line in the result
The right image has these characteristics:
- Things don't stretch much even away from the center
- What were straight lines have become curves. They bend more toward the edges.
So why did I want to do this?
Motivation
Camera settings include something called the "field of view". The bigger it is, the wider the area shown on screen; the smaller you make it, the narrower the area, shown magnified. In Unity you can set it in an Inspector like this.

Field Of View at the very bottom is the one: the "angle of view" (though when I had Google translate the Japanese term, it came out as "field of vision"). The unit is "degrees"; if it's 180, everything from straight up to straight down fits on one screen. If it's 90, it's from 45 degrees up to 45 degrees down. How much shows horizontally depends on the screen's aspect ratio.
However, for various reasons, this value can't be made very big. In a game where the camera moves around turning and looking up, I think even 60 is probably pushing it. That's because of the property I mentioned earlier: "things stretch more the further they are from the center of the screen".
As a test, I set it to 120 and recorded a video.

They're all 1x1x1 cubes, but they stretch as they move toward the edges, which feels quite off. Boxes are one thing, but if they were people the picture would be pretty dire. If it were a game with characters modeled on real people, it might upset those people and the game might never be released.
On top of that, the edges being stretched means the center gets only a small area, so you're actually wasting the screen's resolution. The wider the area you try to show, the less clearly you can see the part you most want to see.
What happens with real cameras?
What about real cameras? The Wikipedia page on field of view explains it clearly, I think.
What's generally called "wide angle" is a vertical field of view of about 50 degrees. When you take a photo with an ordinary camera, you only see 50 degrees. So even in games and CG, if you stay in about the same range as real cameras, there isn't much of a problem. In sports games, for instance, there are probably cases where you actively match real cameras to create the "watching it on TV" feel.
But the human field of view is much wider. Horizontally it's about 120 degrees. You can also find claims that the angle we see sharply is only about 2 degrees, but by moving our eyeballs at high speed and having the brain fill in the gaps, we "feel" as though we see almost the whole thing sharply. When you look at a monitor from 60 cm away, 2 degrees is a mere 2 cm on the monitor (tan(1 degree) × 2 × 60 = 2.09). Can you stare hard at one character on the monitor and read the character five places over from it? I can't. We really only see about 2 cm.
So with head-mounted displays for VR and the like, you might be able to detect the movement of the human eye and change the picture so you don't have to do wasteful drawing, but on an ordinary monitor you have no choice but to show the whole thing. So I find myself wishing I could just show 120 degrees as a matter of course.
Some people will also simply want a look that's different from everyday CG. A little bending around the edges gives a strange sense of power. I think it could be interesting if used well in compositions looking up at something huge. Have a look at the screenshot at the top. If this can be done as a post-process, you can add the effect with hardly any changes to the game's rendering, so you could even add it after the fact to a game you've already made.
Map projections
The classic example of representing 3D space as a 2D picture is a map. It represents the curved surface of the earth on a plane, so it's similar. Think of the "Mercator projection" and the like.
The projection of ordinary 3D CG
In map terms, CG's projection corresponds to the gnomonic projection. You may not hear of it much. No wonder: it's far too awkward to use as an ordinary map.
The way to draw it is simple: draw a line from the center of the earth through each point, and plot it where that line hits a plane placed outside the earth. As we've already seen, it has the following characteristics.
- The larger the angle from the line of sight, the more things stretch out long and thin
- Projecting 180 degrees or more is impossible
- Things that look like straight lines from the center are straight lines on the plane too
Because of characteristics 1 and 2, you can't draw the whole earth on one sheet of paper. You can't even draw a hemisphere, so you'd probably end up dividing it into about six sheets (like the faces of a die). In CG, a cube map is exactly that. Mathematically speaking, for an angle θ the distance from the center on screen is tan(θ), so θ can never be 90 degrees, because it would become infinite.
Point 3 is phrased for maps; for CG you could simply say "straight lines stay straight". Today's game CG is mostly made with a technique called "rasterization", which represents the picture as a set of triangles. Just by doing the simple calculation of "dividing a polygon vertex's xy by its z distance from the viewpoint", you get 2D coordinates on screen, and if you connect the three vertices brought onto the screen with straight lines and fill the inside, you can draw the picture. For the time being, if you want to redraw the entire picture 30 or 60 times a second on a machine like a smartphone, this technique is the only option. GPUs are designed to do this calculation frighteningly fast, and making a game without benefiting from that is rather painful.
Real cameras, too, are built to capture straight lines as straight lines as far as possible, and also use a gnomonic-style projection. When you photograph a street of tall buildings, you probably wouldn't want the buildings at the edges of the photo to come out bent. But as mentioned, the field of view is narrow, so the problem of things getting bigger toward the edges isn't that noticeable.
Fisheye-lens-style projection
There's such a thing as a fisheye lens. With a gnomonic-style projection, however hard you try you can't capture a range of 180 degrees or more, and the wider you capture, the more serious the problem of the edges stretching, so fisheye lenses use a different projection.
In most cases, it's the "equidistant projection". If something at an angle of 5 degrees from the central axis is 5 mm from the center in the image, something at 10 degrees from the central axis appears 10 mm from the center. Something at an angle of 180 degrees, that is, the other side of the earth (in 3D, directly behind), can also be drawn at a distance of 180 mm, so lengths don't get longer away from the center. Mathematically speaking, the distance from the center is proportional to θ, not to tan(θ) as in the gnomonic projection.
In terms of map projections, this corresponds to the azimuthal equidistant projection.
Its characteristics are:
- 360 degrees can be projected onto a single plane
- Things stretch in the circumferential direction toward the edges (the gnomonic projection stretches them radially)
- Straight lines become curves. The further from the center, the more they bend.
For maps, even though you can draw the earth on one sheet, it's practically useless. The flag of the United Nations is drawn in this projection centered on the North Pole, and Australia looks quite squashed north to south. It isn't actually squashed north to south; it's stretched east to west. In CG you'd probably project 180 degrees (a hemisphere) at most, so it won't distort this much, but it's still pretty harsh. The ground captured by a fisheye lens is a good example.
There are, however, uses where distortion doesn't matter. Environment maps used for lighting calculations are an example: if you use one to represent the light coming from the surroundings, every direction fits into one texture. Humans don't look at it directly, so the distortion isn't a problem. But it's awkward to handle (22% of the texture can't be used, the resolution varies too much by direction, and the UV generation calculation is heavy), so I think the normal thing is to use a cube map if you can.
This implementation
This technique converts ordinary CG drawn in a gnomonic-style projection into an azimuthal-equidistant-style picture with a post-process.
Shader
For each pixel after the conversion, we calculate which pixel of the original picture to fetch.
struct appdata
{
float4 vertex : POSITION;
};
struct v2f
{
float4 vertex : SV_POSITION;
float2 position : TEXCOORD0;
};
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
float aspect = _ScreenParams.x / _ScreenParams.y;
o.position = v.vertex; // contains [0, 1]
o.position -= 0.5; // convert to -1/2, 1/2
o.position.x *= aspect; // multiply x by the aspect ratio [-aspect/2, aspect/2], [-1/2, 1/2]
o.position *= 2.0; // [-aspect, aspect],[-1,1]
return o;
}
sampler2D _MainTex;
float _TanSrcHalfFovY;
float _DstHalfFovY;
fixed4 frag (v2f i) : SV_Target
{
float2 p = i.position;
float dstR = sqrt((p.x * p.x) + (p.y * p.y));
float theta = dstR * _DstHalfFovY;
float srcR = (dstR == 0.0) ? 0.0 : (tan(theta) / (_TanSrcHalfFovY * dstR));
p *= srcR;
p.x *= _ScreenParams.y / _ScreenParams.x;
p *= 0.5;
p += 0.5;
return tex2D(_MainTex, p);
}
What comes into the vertex shader is vertex data (appdata.vertex) with x and y each from 0 to 1. We shift it so the center of the screen is 0, multiply x by the aspect ratio, and double the whole thing so that y ranges from -1 to 1. This much is done per vertex.
What differs between the original image and the converted image is a pixel's distance from the center of the screen.
In the gnomonic-like original image, when the angle from the line-of-sight axis is θ, the distance on the image is proportional to tan(θ). In the azimuthal-equidistant-like converted image, it's simply proportional to θ. The Taylor expansion of tanθ is
tan(θ) = θ + (1/3)θ^3 + (2/15)θ^5 + (17/315)θ^7 ...
so it's larger than θ, and the gap grows as θ grows. This corresponds to things stretching toward the edges in the gnomonic projection, and to cancel it, we multiply by tan(θ)/θ to get the distance in the original image. If we computed it with the Taylor expansion, we'd simply lower the degree by one and compute
tan(θ)/θ = 1 + (1/3)θ^2 + (2/15)θ^4 + (17/315)θ^6 ...
with no branch needed, but here we straightforwardly do the division tan(θ)/θ, so a branch is needed to avoid dividing when θ is 0. Perhaps out of old habit, I'm using ?:, but an if would probably be the same speed. After that we multiply by some scaling factor to get the final UV.
I haven't done much fine-grained optimization, but finding out what would actually help is a hassle too, so I've left it as is for now. For example, _ScreenParams.y / _ScreenParams.y, that is, the aspect ratio, could be calculated in advance and set with Material.SetFloat. In the old days that would clearly have been faster, but whether it still is, I can't tell without looking into it. It could even depend on the driver or the device. Making the code harder to read for no effect would be sad, so I'm holding off for now.
Implementing it as a post-process
If the gameObject with the Camera has a MonoBehaviour that implements OnRenderImage, it's used as a post-process. OnRenderImage is called after that camera has finished drawing. Here, a class with the long name AzimuthalEquidistantProjector handles this.
It holds the shader introduced above and a material that uses it, and draws with Graphis.Blit().
Speeding it up
What I introduced above has a speed problem. That's because it does a fair amount of computation, mixing division, tan and sqrt, for every pixel of the converted image. At 1280x720, that's over 900,000 times. So let's speed it up a bit.
That said, I won't be optimizing the shader itself. If there are, say, 20 instructions now, getting it down to 18 is only a 10% speed-up at best, and in reality cutting the instruction count by 10% probably won't make it 10% faster. So instead I'll think about drastically cutting the number of times the calculation runs.
Moving the calculation to the vertex shader
Shaders are normally used for lighting calculations, and there's a standard trick for speeding up lighting calculations: move calculations that are fine per vertex into the vertex shader. The fragment shader runs once per pixel, but in most cases there aren't that many vertices. Each triangle should cover at least several pixels, and if not, you have too many vertices. If on average one triangle covers 10 pixels, turning fragment shader calculations into vertex shader calculations cuts the amount of computation to a tenth. So let's go with that this time too.
Doing it with Graphics.Blit() is easy, but then you can't add vertices. Here I generate a Mesh myself to increase the vertices. For example, if you divide the screen into 2x2, four quads, the vertex count is 3x3, or 9. There are 8 triangles. The vertex shader runs 9 times, which is one hundred-thousandth of running the fragment shader 1280x720 times. But with too few vertices the quality naturally drops, so you need a certain number. In this implementation I made it adjustable in the Inspector. The default is 48, which generates 49x49 = 2401 vertices. Compared with 900,000, that's nothing at all.
If you were implementing this seriously, it'd be better to have a mechanism that adjusts this automatically according to the actual resolution and pixel density. 640x480 and 2436x1125 should need different numbers of divisions, and I suspect 1920x1080 at 40 inches and 1920x1080 at 5 inches would need different numbers of divisions too.
struct v2f
{
float4 vertex : SV_POSITION;
float2 uv : TEXCOORD0;
};
float _TanSrcHalfFovY;
float _DstHalfFovY;
v2f vert (appdata v)
{
float aspect = _ScreenParams.x / _ScreenParams.y;
float2 p = v.vertex; // [-1, 1]
p.x *= aspect; // [-aspect, aspect], [-1, 1]
float dstR = sqrt((p.x * p.x) + (p.y * p.y));
float theta = dstR * _DstHalfFovY;
#if UNITY_UV_STARTS_AT_TOP
p.y = -p.y;
#endif
float r = (dstR == 0.0) ? 0.0 : (tan(theta) / (_TanSrcHalfFovY * dstR));
p *= r;
p.x /= aspect;
p *= 0.5;
p += 0.5;
v2f o;
o.vertex = v.vertex;
o.uv = p;
return o;
}
sampler2D _MainTex;
fixed4 frag (v2f i) : SV_Target
{
return tex2D(_MainTex, i.uv);
}
This is the version that calculates in the vertex shader. The fragment shader now only does tex2D. The vertex shader's calculation is mostly the same as before, but appdata.vertex holds -1 to 1 instead of 0 to 1. That way you get a full-screen rectangle without UnityObjectToClipPos().
One thing to watch out for is the part that says #if UNITY_UV_STARTS_AT_TOP. UV coordinate systems differ between DirectX/Metal and OpenGL. In the former the top edge is 0 and the bottom edge is 1; in the latter the top edge is 1 and the bottom edge is 0. In the former, y needs to be flipped. The code that calculated in the fragment shader did nothing about this because Graphics.Blit() takes care of it nicely. This time we generate the Mesh ourselves, so we have no choice but to do it in the shader.
Performance
On my own Kyocera S2, this processing took an extra 11.8 ms. In a 30 fps scene where the bottleneck is on the CPU side and the GPU has room to spare, it's not unusable. Most devices are more than twice as fast as this one, so I think there are many situations where it could be used even in a 60 fps game.
Honestly, though, my impression is that it's still slow. If I want it fast enough to use at 60 fps even on the S2, I'd like it twice as fast. But I have no concrete plans to use it, and there are issues to solve before it can be used, such as the problems described next, so I'll stop here for now.
Future improvements
Unfortunately, this technique has quite a few drawbacks. There are things you have to think about if you want to put it in something you sell.
Wasted drawing area
The original rendering wastes part of its drawing area, and that needs to be cut down. In fact, we aren't using the whole area of the original texture.

This was drawn with a vertical field of view of 135 degrees for the original rendering, and also 135 degrees after conversion. The red and green areas show places that are within the drawing range but have no data in the original image (you can turn this on and off from the Inspector with a debug feature. It makes things heavier).
At the top and bottom edges in the middle of the screen it fits exactly, but everywhere else there's nowhere near enough data. In other words, if you originally draw at 135 degrees, you have to lower the field of view after conversion. In fact, this lowering of the field of view can be calculated automatically, and if you leave it to the automatic setting it becomes 77 degrees. At 77 degrees, the drawing range is the inside of the black rectangle below.

What's outside it is drawn but never used. Pure waste. So one possible speed-up is to not paint the parts outside this rectangle in the first place when doing the original drawing.
A good approach would be to calculate where this rectangle falls in the original image, and fill the Z-buffer in the areas outside it with suitable polygons. You could also consider using the stencil, but then the stencil can't be used for anything else, so the Z-buffer keeps things more general-purpose.
I don't know whether writing only to the Z-buffer is possible in Unity, but if it isn't, a shader that just paints red or something would do. If you write "the nearest possible value" into the Z-buffer in advance, the subsequent drawing fails the Z test and the fragment shader won't run. That should reduce the drawing load somewhat. In this example, it looks like about 20% could be shaved off.
The cost of shrinking at the edges, and degradation from enlarging the center

This is what the original image looks like when drawn at 135 degrees. The edges are stretched considerably. Since they become small after conversion, these areas are being shrunk.
But shrinking is expensive. Painting one pixel needs data from several pixels, and if you shrink too much, memory access jumps around and performance drops even further.
Even so, fixing this is somewhat difficult. Mipmaps might help, but making them takes time too, and while mipmaps are good for shrinking uniformly overall, they don't suit shrinking in only one direction. Using anisotropic filtering would make it look nice, but naturally it gets heavier.
And since the center gets only a small area in the original image, the conversion enlarges it, and that's where degradation becomes a problem.
Ideas for improvement
I've never actually tried it, but I feel that drawing twice might be an option. Draw the center of the screen and the edges of the screen separately, and combine them into one. For example, draw the central part (half the width and height) at 512x512 and the remaining edges at 512x512, then combine the two draws for the final result. That way the edges are drawn at half the resolution, so the shrinking load goes down. If you raise the resolution of the center somewhat, you can also cancel out the degradation from enlarging it.
However, the vertex shader would run twice, DrawCalls would increase, and this conversion would get more complicated, so I won't know what happens to the speed until I try. Also, it would no longer be just a post-process, so the scope of changes gets bigger.
I also feel there might be another option: using a different projection. If you just want to widen the horizontal field of view, a cylindrical projection such as the Mercator projection or the equirectangular projection might work.
Or there may be the option of drawing with MSAA (MultiSampleAntiAlias) enabled to deal with at least the jaggies at polygon edges. That needs few code changes, and on hardware that keeps render targets in dedicated memory, MSAA can sometimes be applied quite cheaply, so it may be worth considering. Below is a comparison from trying it out. I raised the field of view to 150 degrees to make it easier to see. It depends on the load, but I think it's effective.


MSAA can be set in the Camera's Inspector. Note that it can also be disabled on the PlayerSettings side.

In any case, if you're going to use this technique with a field of view over 120 degrees, it won't be good enough to sell unless you do something about the degradation in the center, so you'll end up taking some measure. If you put it in a product as it is now, you'd either keep the field of view within a range where the degradation isn't noticeable, or use it within a field-of-view animation (that is, a zoom) to shorten the time the degradation is noticeable. Turning on the sample's ZoomEffect toggle lets you see the field-of-view animation.

Closing
Following my bloom effect article, this is my second article on "adding flavor afterward with post-processing."
In the sense that just adding a component to the camera changes the picture, post-processing is a cost-effective technique. You can add it to something you've already made, or enable it only in particular scenes.
But if you're going to build a game properly on that premise, you have to clear the speed and quality issues, and the overall design also has to fit around it, so it stops being that easy. For bloom, you need to think seriously about representing HDR; in this article's case, you need a technique that can do something about the enlargement of the center.
As another flavor you can add with post-processing, depth-of-field blur (what's commonly called out-of-focus blur) is also well known, and I recommend it. It's in the PostProcessingStack. However, it can't be made as light as bloom or a projection change, and once you start doing it seriously, it demands knowledge and a feel for real cameras, so it may be a bit advanced. If there's demand, I'm thinking I might prepare a light implementation and write an article about it together with the basics of how to use it.
References
- Tokoi Laboratory: Flattening fisheye lens images
- The source is a fisheye image, and the conversion and purpose are different, but it's a closely related topic, so I think it will deepen your understanding.
Addendum
I made a product that uses this. (android iOS).
Titan Shoot