5. Camera with Configurable View Volume¶
This renderer modifies the Camera class to give us more control over the
renderer's virtual camera.
In the previous renderers, the camera is fixed at the origin, looking down the negative z-axis and has a fixed view volume (either a fixed projective view volume or a fixed orthographic view volume). This is not very convenient. In order to render a complex scene, we have to position each object relative to the (fixed) camera. It would be better to have the camera act like a real movie camera, where objects are positioned in a scene and then the camera is positioned in whatever location seems best. In fact, we should be able to move the camera around the scene, independently of moving the objects in the scene. In addition, a real movie camera can zoom in and out to view less or more of the objects in the scene.
In this renderer we give the Camera class the ability to set the camera's
view volume. This gives us two abilities that we did not have before. It lets
us set the aspect ratio of the camera's view rectangle. And it lets us "zoom"
the camera in and out of a scene.
In the next renderer we will allow the camera to translate in space and in a later renderer we will allow the camera to rotate in space and point in any direction.
5.1 Renderer source code¶
The Java source code for this renderer is publicly available as a zip file.
Here is a link to the renderer's source code.
Download and unzip the source code to any convenient location in your computer's file system. The renderer does not have any dependencies other than the Java 11 (or later) JDK. Once you have downloaded and unzipped the distribution, you are ready to compile the renderer and run the renderer's (interactive) example programs.
In the previous renderer the first pipeline stage was Model2Camera. This
renderer splits that stage into two stages, Model2View and View2Camera.
This renderer has one new file in the renderer.pipeline package.
- "View2Camera.java"
The previous "Model2Camera.java" pipeline stage is renamed.
- "Model2View.java"
The file "Camera.java" in the renderer.scene package is modified to store
the camera's view volume parameters.
The files "Pipeline.java" and "Pipeline2.java" are modified to put the new
View2Camera stage into the rendering pipeline after the Model2View stage.
The client programs are modified to make use of the camera's configurable volume.
5.2 Pipeline¶
The pipeline has the following seven stages.
v_0 ... v_n A Model's list of Vertex objects
\ /
\ /
|
| model coordinates (of v_0 ... v_n)
|
+-------+
| |
| P1 | Model-to-view transformation (of the vertices)
| |
+-------+
|
| view coordinates (of v_0 ... v_n) relative to an arbitrary view volume
|
+-------+
| |
| P2 | View-to-camera (normalization) transformation (of the vertices)
| |
+-------+
|
| camera coordinates (of v_0 ... v_n) relative to the standard view volume
|
+---+
/ \
| P3 | Near Plane Clipping (of each primitive)
\ /
+---+
|
| camera coordinates (of the near-clipped v_0 ... v_n)
|
+-------+
| |
| P4 | Projection transformation (of the vertices)
| |
+-------+
|
| image plane coordinates (of v_0 ... v_n)
|
+---+
/ \
| P5 | Clipping (of each primitive)
\ /
+---+
|
| image plane coordinates (of the clipped vertices)
|
+-------+
| |
| P6 | Viewport transformation (of the clipped vertices)
| |
+-------+
|
| pixel-plane coordinates (of the clipped vertices)
|
+---+
/ \
| P7 | Rasterization, clipping & anti-aliasing (of each Primitive)
\ /
+---+
|
| shaded pixels (for each clipped, anti-aliased Primitive)
|
\|/
FrameBuffer.ViewPort
For basic information about the rendering pipeline, see Section 1.9 The Renderer Pipeline.
For the previous pipeline, see Section 4.2.
Exercise: Rewrite "Pipeline.java" so that the normalization pipeline
stage, View2Camera, comes after the Projection pipeline stage.
5.3 View volumes¶
Recall that the renderer has two view volume shapes. One shape for perspective projection and one shape for orthographic projection.

In the previous renderers these view volumes were fixed. This renderer allows us to change the shape of each view volume.
The perspective view volume is determined by four slanting planes. The
orthographic view volume is determined by four planes parallel to the
coordinate planes. All of these planes are determined by the rectangle where
the view volume intersects the image-plane, z = -1. We called that rectangle
the "view rectangle". In this renderer we change the shape of a view volume by
changing the edges of the view rectangle.
In this renderer the view volume for a Camera object is determined by four
parameters.
left- Left edge of the view rectangle in the image-plane.right- Right edge of the view rectangle in the image-plane.bottom- Bottom edge of the view rectangle in the image-plane.top- Top edge of the view rectangle in the image-plane.
These four parameters represent the four edges of a view rectangle in the
image-plane. The left and right parameters are coordinates on the x-axis.
The top and bottom parameters are coordinates on the y-axis. These four
edges are the intersection of the view volume with the image-plane.
For the perspective projection, the view volume is an infinitely long frustum
that is formed from the pyramid with its apex at the origin and its base in
the plane z = -1 with edges x = left, x = right, y = bottom, and
y = top.
For the orthographic projection, the view volume is an infinitely long
parallelepiped that is formed from the rectangle in the z = -1 plane with
edges x = left, x = right, y = bottom, and y = top.
Here are some online demo programs that let you play with the shape of a camera's view volume. Notice how making the view volume narrow is the same thing as "zooming in" on an object contained in the view volume.
- https://webgl2fundamentals.org/webgl/frustum-diagram.html
- https://webgl2fundamentals.org/webgl/webgl-visualize-camera-with-frustum.html
- https://webgl2fundamentals.org/webgl/webgl-visualize-camera-with-orthographic.html
- https://cs.wellesley.edu/~cs307/threejs/demos-s21-r95/Camera/camera-api.shtml
- https://cs.wellesley.edu/~cs307/threejs/demos-s21-r95/Camera/frustum.shtml
- https://www.songho.ca/opengl/gl_transform.html#example2
The Camera class has static factory methods for constructing Camera objects
of the appropriate type and shape.
If you look in the code for the Camera class you will see that it has only
one constructor and that constructor is private. A private constructor can
only be called by code within the class file. Any external code that wants to
construct a Camera object cannot call the Camera constructor. Code external
to the Camera class must call one of the static factory methods in the
Camera class. A static factory method is an object-oriented design pattern.
Static factory methods are more versatile than traditional constructors. They
solve many problems that often come up when using constructors. Most modern
Java designs emphasize static factory methods over constructors.
5.3.1 Normalized view volume¶
In the previous renderers the camera used fixed view volumes, one for perspective projection and another for orthographic projection.
The fixed perspective view volume was the infinitely long pyramid formed from
the pyramid with its apex at the origin and its base in the plane z = -1 with
edges x = -1, x = +1, y = -1, and y = +1.
The fixed orthographic view volume was the infinitely long parallelepiped formed
from the square in the plane z = -1 with edges x = -1, x = +1, y = -1,
and y = +1.
In other words, the two fixed view volumes both had parameter values
top = right = 1 and bottom = left = -1.
These two fixed view volumes are important. We call them the normalized view volumes or, sometimes, the "standard view volumes".
The normalized view volumes are important because the View2camera pipeline
stage transforms a camera's arbitrary view volume into a standard view volume.
Then, all the following pipeline stages do their work in the normalized view
volume, just as they did in the previous renderers. This design means that
adding a configurable view volume stage to the pipeline does not have any
effect on later pipeline stages.
5.4 Aspect ratio¶
You probably have noticed that many of the screens that you look at have slightly different "shapes". Some are more square (old TVs and old CRT monitors) and some are more rectangular. Some of the rectangular screens are looked at with their long edge horizontal (movie screens and laptop screens) and some are looked at with their long edge vertical (tablets and smart phones). This shape of a screen is called the screen's "aspect ratio".
The aspect ratio of a rectangle is defined as the ratio of its horizontal
length to its vertical length (or, width/height). We define the aspect ratio
of a screen to be the ratio of its horizontal length to its vertical length,
both measured in pixels.
We will define the aspect ratio of a view volume to be the aspect ratio
of its view rectangle (in the camera's view-plane, z = -1).
For both perspective and orthographic projection, the aspect ratio of the view volume's view rectangle is
Notice that:
- A square screen has aspect ration = 1.
- A rectangular screen with its long edge horizontal has aspect ratio > 1.
- A rectangular screen with its long edge vertical has aspect ratio < 1.
An aspect ratio > 1 is called landscape mode. An aspect ratio < 1 is called portrait mode.
aspect ratio > 1 aspect ratio < 1
(landscape) (portrait)
+----------------------+ +------------+
| | | |
| | | |
| | | |
| | | |
+----------------------+ | |
| |
| |
| |
+------------+
Some devices, like tablets and smart phones, can easily switch between portrait and landscape modes. Other devices, like a movie screen, can't.
5.5 View2Camera pipeline stage¶
This renderer implements arbitrary view volumes with the View2Camera
pipeline stage. This pipeline stage defines a new coordinate system
and we need to derive the transformation formulas for this new
coordinate system.
5.5.1 View and camera coordinate systems¶
In previous renderers, the clipping stage of the pipeline assumed that every
Vertex was in a coordinate system where the Camera had the standard view
volume. But in this renderer, we are assuming that every Vertex is in a
coordinate system where the Camera has the view volume determined by the
data in the Scene object's Camera object. So the vertex data in our
pipeline is not in the coordinate system that our clipping stage expects.
We could rewrite the clipping stage to use the new view volumes, but we would
rather not do that (the clipping stage would need too many parameters, which
would just slow it down). So we use a trick. We define a new pipeline stage,
View2Camera.java, that transforms the coordinates of every Vertex from the
coordinate system of the camera's (arbitrary) view volume to the coordinate
system of the standard view volume. Another way to put this is that the new
stage transforms the camera's arbitrary view volume into the normalized (or
standard) view volume.
After this transformation, the previous clipping stage works just as it did in the previous renderers. (NOTE: We could put the new transformation stage either before or after the projection stage. We put it before the projection stage because that is where it needs to be in future renderers.)
We call the coordinate system relative to the camera's view volume the view coordinate system. We call the coordinate system relative to the standard view volume the camera coordinate system. So the new pipeline stage converts vertices from view to camera coordinates.
5.5.2 View-to-camera transformation¶
Here is a picture that describes what we need to do. On the left is the view
rectangle of a view volume with left = -1, right = 3, bottom = -2, and
top = 3. On the right is a standard view rectangle from a standard view
volume with left = bottom = -1 and right = top = 1.
y-axis
/|\
|
+-----+ 3 --------------+
| | |
| | | y-axis
| + 2 | /|\
| | | |
| | | +-------| 1 ----+
| + 1 | | | |
| | | | | |
| | | | | |
--|-----+-----|-----|-----|--> x --|-------+-------|---> x
-1 | 1 2 3 -1 | 1
| | | | | |
| + -1 | | | |
| | | +-------| -1 ---+
| | | |
+-----+ -2 -------------+ |
| Camera Coordinates
|
View Coordianates
Notice that the view rectangle in view coordinates is 4 units wide and 5 units tall (so it is in "portrait mode") and it is not centered on the x-axis or on the y-axis. This is the view rectangle from an "asymmetric view volume".
We need a transformation from three-dimensional view coordinate space to
three-dimensional camera coordinate space that transforms the asymmetric
view volume so that its view rectangle in the plane z = -1 is transformed
into the standard view rectangle in the image-plane of camera coordinate
space.
We first derive the transformation formulas for a perspective view volume.
Here is a brief description of the steps that transform a camera's arbitrary
perspective view volume into the normalized perspective view volume (and
transform view coordinates into camera coordinates). We use two steps to
derive the transform. The first step "skews" (or "shears") the arbitrary view
volume so that its centerline is the negative z-axis (that is, we skew an
asymmetric view volume (like the one shown above) into a symmetric one). The
second step scales the skewed, symmetric view volume so that it intersects the
plane z = -1 with corners (-1, -1, -1) and (+1, +1, -1) (that is, we
scale the symmetric view volume so that it has a 90 degree field-of-view and
becomes the normalized view volume).
Let R, L, t, b denote the right, left, top, and bottom fields
of the Camera. These numbers do not have to define a symmetric view volume.
We are not assuming that R = -L, or t = -b.
Let v = (x_v, y_v, z_v) be a vertex in view coordinates. Skew the perspective
view volume in each of the x and y directions so that the negative z-axis is the
centerline of the transformed view volume.
Next, scale the skewed view volume in each of the x and y directions so that it
intersects the image plane z = -1 with corners (-1, -1, -1) and (+1, +1, -1).
Here is a derivation of the above formulas for the x-coordinate (the derivation for the y-coordinate is similar). We need to skew the xz-plane of the arbitrary view volume in the x-direction so that the centerline of the arbitrary view volume skews to the negative z-axis. For some skew factor s, the skew equations are
The point (x_v, z_v) = ( (R + L)/2, -1) from the arbitrary view volume's
centerline should skew to the point (0, -1) on the negative z-axis. So
so
Using this skew factor, we can compute that the point (x_v, z_v) = (R, -1)
from the arbitrary view volume skews to the point (x', z') = ((R - L)/2, -1)
and the point (L, -1) skews to the symmetric point (-(R - L)/2, -1).
After skewing the arbitrary view volume, we need to scale the xz-plane of the
new symmetric view volume in the x-direction so that it has a 90 degree
field-of-view. For some scale factor s, the scaling equations are
We know that the point (x', z') = ((R - L)/2, -1) should scale to the point
(x_c, z_c) = (1, -1) so
so
We have a similar set of equations for transforming an arbitrary orthographic view volume into the normalized orthographic view volume.
We use two steps to transform the camera's arbitrary orthographic view volume into the normalized orthographic view volume. The first step translates the arbitrary view volume so that its centerline is the z-axis. The second step scales the translated view volume so that it intersects the plane z = 0 with corners (-1, -1, 0) and (+1, +1, 0).
Let v = (x_v, y_v, z_v) be a vertex in view coordinates. Translate the
orthographic view volume in each of the x and y directions so that the
z-axis is the centerline of the translated view volume.
Next, scale the translated view volume in each of the x and y directions so that it intersects the plane z = 0 with corners (-1, -1, 0) and (1, 1, 0).
5.5.3 View-to-camera vs. viewport transformations¶
The Viewport transformation is, in a way, the opposite of the
View2Camera transformation. The View2Camera transformation takes an
arbitrary view volume, and its arbitrarily shaped view rectangle, and
transforms them into the normalized view volume and view rectangle so that
the clipping stage can do its work in the standard view rectangle. Then
the Viewport transformation transforms the standard view rectangle into
an arbitrarily shaped logical viewport in the pixel-plane. If the aspect
ratio of the camera's view rectangle matches the aspect ratio of the
framebuffer's viewport, then the Viewport transformation will undo the
distortion caused by the View2Camera transformation.
Suppose we have a sphere positioned in camera space and the camera's view
rectangle is not a square. Then the View2camera transformation will distort
the sphere into an ellipsoid shape when the transformation transforms the
camera's non-square view rectangle into the normalized, square, view rectangle.
But, if the framebuffer's viewport has the same aspect ratio as the camera's
view rectangle, then the Viewport transformation will distort the ellipsoid
back into a sphere, undoing the distortion caused by the View2Camera
transformation.
If the aspect ratios of the camera's view rectangle and the framebuffer's
viewport are not equal to each other, then the distortions caused by the
View2Camera and Viewport transformations do not "cancel" each other
out. In that case, we are left with a distorted image in the framebuffer's
viewport. The next section is about dealing with this situation.
5.6 Mismatched aspect ratios¶
When the aspect ratios of the view volume's view rectangle and the framebuffer's viewport are not equal, one of three possible compromises must be made when rendering the contents of the view volume into the viewport.
-
The image in the viewport is a distorted representation of the scene in the view volume.
-
The aspect ratio of the viewport must be changed to match the aspect ratio of the view rectangle. Some part of the framebuffer will not be used (in film, this is called letterboxing).
-
The aspect ratio of the view rectangle must be changed to match the aspect ratio of the viewport. Some part of the scene from the view rectangle will not be drawn into the viewport (in film, this is called cropping).
Another way to put this is that when the aspect ratios are not equal:
-
we can draw all of the contents from the view rectangle using all of the space in the viewport, but the resulting image must be a distorted representation of what is in the view rectangle,
-
we can draw an undistorted representation of all of the contents of the view rectangle but on only part of the viewport (letterboxing),
-
we can use all of the viewport to draw an undistorted representation of just part of what's in the view rectangle (cropping).
Here is another way to describe what we can do when the aspect ratio of the viewport is not the same as the aspect ratio of the view rectangle.
-
Distort the contents of the view rectangle to match the aspect ratio of the viewport.
-
Find a sub-rectangle within the viewport that has the same aspect ratio as the view rectangle, and then display the whole view rectangle in that viewport sub-rectangle. In other words, letterbox the contents of the view rectangle in a sub-rectangle of the viewport. How you position the sub-rectangle within the viewport is entirely arbitrary. It is most often either centered in the viewport, or attached to one edge, or one corner, of the viewport.
-
Find a sub-rectangle within the view rectangle that has the same aspect ratio as the viewport and then display that sub-rectangle of the view rectangle in the viewport. In other words, crop the contents of the view rectangle so that what is left has the aspect ratio of the viewport. How you position the sub-rectangle within the view rectangle is entirely arbitrary. It is often chosen so that the most important content of the view rectangle is centered in the sub-rectangle. If the most important content of the view rectangle is moving around, the chosen sub-rectangle may need to move around also. In film, this is called pan and scan.
Choice (1) is more or less the default choice in most renderers. If the aspect ratios of the view rectangle and the viewport do not agree, then the renderer will do the distorting.
We make choice (2) by resizing (and possibly repositioning) the framebuffer's viewport, or by creating a new viewport within the previous viewport.
We make choice (3) by resizing (and possibly repositioning) the camera's view volume.
5.7 Scale, fit, letterbox, crop, scroll¶
When a "source" rectangle (usually a rectangular region of the imaga-plane)
must be displayed within a "destination" rectangle (usually a FrameBuffer),
if the two rectangles do not have the same aspect ratio, then we must use
one of these effects.
- distort
- crop
- letterbox
That is, either the original image from the source is distorted into the destination rectangle, or part of the source rectangle is cropped off to fit its image in the destination rectangle, or the source rectangle is letterboxed within the destination rectangle so some of the destination rectangle is unused.
Let's analyze how we can implement these effects.
When we map the source rectangle onto the destination rectangle, we will always preserve horizontal and vertical directions. That is, we always map horizontal lines to horizontal lines and vertical lines to vertical lines.
Consider a horizontal line from the source rectangle that goes across the rectangle from the left edge to the right edge. We will scale (or "stretch") this line into a horizontal line in the destination rectangle. If the destination line stretches from the left edge to the right edge of the destination rectangle, then we say that we fit the horizontal direction. If the destination line does not stretch entirely across the destination rectangle, then we say that we letterbox the horizontal direction. If some sub-interval of the source line is stretched across the destination rectangle from the left edge to the right edge, then we say that we crop the horizontal direction. If we are allowed to interactively choose the sub-interval of the source line that gets stretched across the destination rectangle, then we say that we scroll the horizontal direction.
These four ways to scale a line from the source rectangle onto a line in the destination rectangle are our building blocks for ways to display a source rectangle in a destination rectangle.
- Fit along the horizontal (or vertical) direction.
- Letterbox along the horizontal (or vertical) direction.
- Crop along the horizontal (or vertical) direction.
- Scroll along the horizontal (or vertical) direction.
What we do in the horizontal direction is independent of what we do in the vertical direction. For example, we can fit along the x-axis while we crop along the y-axis. Or we can crop along the x-axis while we letterbox along the y-axis.
If the amount of scaling that we use in the horizontal direction is different from the amount of scaling in the vertical direction, then the image from the source rectangle will be distorted in the destination rectangle. If we use the same amount of scaling in both directions, then the aspect ration of the source image will be preserved in the destination rectangle. Usually, we want to avoid distortion and preserve the aspect ratio.
Since there are four choices we can make in each of two directions, there are a total of 16 possible ways we can display a source rectangle in a destination rectangle. Most of those choices will not make sense and will cause distortion in either the horizontal or vertical direction. More often than not, there are only a few (two or three) choices that make sense and look good.
Here are a variety of scenarios that can come up when we display a source rectangle in a destination rectangle.
5.7.1 Example 1: Portrait to landscape¶
Suppose that the source rectangle on the left must be displayed in the destination rectangle on the right. In this case, if we fit along both the x and y directions, then we get distortion. To avoid distortion, we need to preserve the aspect ratio of the source rectangle. To preserve the source's aspect ratio, we can fit along the x-axis and crop (or scroll) along the y-axis. Or we can fit along the y-axis and letterbox along the x-axis. (Imagine picking up the rectangle on the left and trying to fit it into the rectangle on the right while preserving its aspect ratio. If you want to cover the whole destination rectangle, then you must cut off part of the top or bottom of the source. If you want to display all of the source, then you must squeeze it into the destination with some empty space on its left or right sides.)
+-----------+
| |
| | #=====================#
| | # #
| | # #
| source | # destination #
| | # #
| | # #
| | #=====================#
| | aspect ratio > 1
+-----------+ (landscape)
aspect ratio < 1
(portrait)
5.7.2 Example 2: Landscape to portrait¶
If we fit both the x and y directions, then we again get distortion. To preserve the aspect ratio of the source rectangle, we can fit along the x-axis and letterbox along the y-axis. Or we can fit along the y-axis and crop (or scroll) along the x-axis. (Imagine picking up the rectangle on the left and trying to fit it into the rectangle on the right while preserving its aspect ratio. If you want to cover the whole destination rectangle, then you must cut off part of the left or right sides of the source. If you want to display all of the source rectangle, then you must squeeze it into the destination with some empty space above or below.)
#===========#
# #
# #
+--------------------+ # #
| | # #
| source | #destination#
| | # #
| | # #
+--------------------+ # #
aspect ratio > 1 # #
(landscape) #===========#
aspect ratio < 1
(portrait)
5.7.3 Example 3: Both portrait¶
In the case of a larger portrait aspect ratio displayed in a smaller portrait aspect ratio, we can either fit along the x-axis and letterbox along the y-axis, or fit along the y-axis and crop (or scroll) along the x-axis.
#===========#
# #
# #
# #
+-----------+ # #
| | # #
| | # #
| | # #
| source | #destination#
| | # #
| | # #
| | # #
+-----------+ # #
aspect ratio < 1 # #
(portrait) # #
# #
#===========#
aspect ratio << 1
(portrait)
In the case of a smaller portrait aspect ratio displayed in a larger portrait aspect ratio, we can either fit along the x-axis and crop (or scroll) along the y-axis, or fit along the y-axis and letterbox along the x-axis.
+-----------+
| |
| |
| | #===========#
| | # #
| | # #
| | # #
| source | #destination#
| | # #
| | # #
| | # #
| | #===========#
| | aspect ratio < 1
| | (portrait)
+-----------+
aspect ratio << 1
(portrait)
5.7.4 Example 4: Both landscape¶
In the case of a larger landscape aspect ratio displayed to a smaller landscape aspect ratio, we can either fit along the y-axis and crop (or scroll) along the x-axis, or fit along the x-axis and letterbox along the y-axis.
+---------------------------------+ #=======================#
| | # #
| | # #
| source | # destination #
| | # #
| | # #
+---------------------------------+ #=======================#
aspect ratio >> 1 aspect ratio > 1
(landscape) (landscape)
In the case of a smaller landscape aspect ratio displayed in a larger landscape aspect ratio, we can either fit along the y-axis and letterbox along the x-axis, or fit along the x-axis and crop (or scroll) along the y-axis.
+-----------------------+ #=================================#
| | # #
| | # #
| source | # destination #
| | # #
| | # #
+-----------------------+ #=================================#
aspect ratio > 1 aspect ratio >> 1
(landscape) (landscape)
5.7.5 The API¶
We want to consider what methods from the renderer API we can use to implement letterboxing and cropping.
The above examples might lead you to think that we are working with only two rectangles, the source rectangle and the destination rectangle. But in fact, we are working with four rectangles. We need an additional rectangle inside of the source rectangle to specify how much we crop the image in the source. And we need an additional rectangle inside of the destination rectangle to specify the position of our letterbox.
In the above examples, you should think of the source rectangle as a rectangular
region of the image-plane (with Left, Right, Bottom, and Top edges).
The source rectangle contains a scene that we wish to display. You should think
of the destination rectangle as a FrameBuffer (with dimensions wFB and
hFB). The sub-rectangle of the source rectangle that specifies how we crop
the source rectangle's image is the camera's view rectangle (with parameters
left, right, bottom, top). The sub-rectangle of the destination rectangle
that we actually fit the source into will be a Viewport (with parameters x_ul,
y_ul,wVP, hVP).
Image-plane
(0,0) FrameBuffer
y-axis #==================================#
/|\ # #
L | R # #
T +----------|------------+ # #
| | | # (x_ul,y_ul) #
| | view | # +~~~~~~~~~~~~~~~~~~~~~~~~#
| | rectangle | # { #
| t+---------------+ | # { #
| | | | | # { Viewport #
---|---|------+--------|---|---> x # { #
| | | | | # { #
| | | | | # +~~~~~~~~~~~~~~~~~~~~~~~~#
| b+---------------+ | # #
| l | r | # #
B +----------|------------+ # #
| source # #
| rectangle #==================================#
(wFB-1,hFB-1)
The general problem is, given the parameters Left, Right, Bottom, Top
of the source rectangle and the parameters wFB and hFB of the destination
rectangle, compute the parameters for a view rectangle and a Viewport. (And
remember
that the view rectangle is always mapped by the renderer entirely
over the whole Viewport.)
If the parameters for the view rectangle are not all of the source rectangle, then the view rectangle is cropping the image from the source rectangle.
If the parameters for the Viewport are not allof the FrameBuffer, then
the Viewport is letterboxing
Letterboxing and cropping are special cases of this general problem.
When we letterbox, the view rectangle is all of the source rectangle and we
need to compute parameters for a Viewport with the correct aspect ratio
that fits in the FrameBuffer. Usually the Viewport will only be part of
the FrameBuffer, so the rest of the FrameBuffer will be the letterboxing
part.
When we crop, the Viewport is all of the FrameBuffer and we need to compute
a view rectangle with the same aspect ratio as the FrameBufer. Usually, the
view rectangle will only be part of the source rectangle so we will be cropping
off the part of the source rectangle not covered by the view rectangle.
Exercise: In the case of cropping, if the source rectangle has aspect ratio
greater than the FrameBuffer, do we crop horizontally or vertically? If the
source rectangle has aspect ratio less than the FrameBuffer, do we crop
horizontally or vertically?
In general, letterboxing an image into a FrameBuffer is done by either
setting the default Viewport using the
FrameBuffer class, or by creating a new
Viewport using the
constructor in the Viewport class.
Cropping a source image is done by changing the camera's view rectangle using either the
or the method in theCamera class.
In the folder
there are two illustrations that try to visualize the relationship between cropping, letterboxing, and the parameters to theprojOrtho() and
setViewport() methods.
Scaling an image is done
automatically
by the renderer when it maps the whole of the camera's view-rectangle onto
the Viewport. If the aspect ratios of the camera's view-rectangle and the
framebuffer's Viewport do not agree, then the renderer will distort the
final image in the Viewport. Most of the time, we want to make sure that
the view rectangle and the viewport have the same aspect ratio so that we
get scaling without distortion.
When we crop an image in an interactive program, we can give the user the
option to "scroll" the image. In other words, we can give the user the
choice of which part of the original image gets cropped off. Scrolling is
part of the Java GUI system, it is not part of the renderer or part of our
FrameBuffer or Viewport classes. To allow a user to scroll through a
cropped image, we need to use a scrolling GUI component from the Java GUI
system. Java has three components that can be used for scrolling, JSlider,
JScrollbar, ScrolBar. Each component gives us an integer value that depends
on the placement of its "slider button". We use that value to set the view
rectangle in the camera's image-plane. For example code, see the following
three programs from the "renderer_5/clients_r5/aspect_ratio_examples/" folder.
- "Circle_v5_PanAndScan_JSlider.java"
- "Circle_v5_PanAndScan_JScrollBar.java"
- "Circle_v5_PanAndScan_Scrollbar.java"
There is a version using each of JSlider, JScrolBar, and Scrollbar
because the three components act differently when it comes to keyboard focus.
Play with all three of these programs and be sure to activate the scrolling
components using the keyboard's arrow keys and switching keyboard focus between
the components by using the Tab key.
5.8 Java's ComponentListener interface¶
For our client programs to respond to the user changing the size of the
program's JFrame, we need to implement the ComponentListener event
handler interface, in particular, the componentResized() method.
This listener is called ComponentListener because it is not just for resizing
a JFrame. This listener is used to resize any kind of component or container.
For example we can have a JFrame that contains a JPanel container. The
JPanel can contain a JButton. The user can use their mouse to resize the
JFrame on their desktop. That triggers a resize event on any ComponentListener
attached to the JFrame. The layout manager for the JFrame may decide to
trigger a resize event on any ComponentListener attached to the JPanel. And
the layout manager of the JPanel may decide to trigger a resize event on any
ComponentListener attached to the JButton. In other words, a resize event
on a top-level window like a JFrame can propagate to any component contained
anywhere inside of the top-level window.
JFrame
#==================================#
# #
# #
# #
# JPanel #
# +~~~~~~~~~~~~~~~~~~~~+ #
# { } #
# { JButton } #
# { +-----+ } #
# { | | } #
# { +-----+ } #
# { } #
# +~~~~~~~~~~~~~~~~~~~~+ #
# #
# #
# #
#==================================#
5.8.1 Resizing a JFrame¶
To get a sense of how we handle resize events, let's try some experiments in JShell.
We will start with just a JFrame that doesn't contain any components.
Open a command-prompt window and on the command-line start a JShell session.
When the JShell prompt appears, copy-and-paste the following block of code into the prompt. JShell allows you to copy several lines of code at a time. It will execute each line of code and then give you another prompt.
This code creates and displays a JFrame and attaches a ComponentListener
object to it. The ComponentListener interface declares four methods, but
we are interested in implementing only one of them, the
componentResized()
method. We subclass the ComponentAdapter class which implements the other
three methods for us using empty method bodies.
Resize the JFrame and notice the ComponentEvent objects displayed in the
JShell console window. The ComponentEvent objects tell you the size, and
location, of the JFrame after every resize event. Place the JFrame near
the upper left-hand corner of your computer's screen and then resize the
JFrame. Place the JFrame near the lower right-hand corner of your computer
screen and then resize the JFrame again.
Resize the JFrame window very slowly. Notice that there is one event for
every single pixel change in the dimension. Resize the JFrame very quickly.
You should see that there is no longer one event for every single pixel change
in the dimension. When you change the window size quickly the Java Virtual
Machine (JVM) drops some of the resize events. The user of the program will not
notice that some of the pixel events have been dropped, but dropping them makes
it easier for the JVM to keep up with other events that may also be happening.
You caused resize events by using your mouse to resize the JFrame window.
We can also cause resize events using code. The setSize() method in JFrame
sets the size of the JFrame, but it also triggers a resize event on any
ComponentListener attached to the JFrame. This is so the JFrame is
informed that its size has been changed.
Type the following lines of code into your JShell prompt, one at a time.
Notice that each method call also causes a resize event. But notice that
calling setSize() again with the same parameters doesn't cause a resize
event.
jshell> jf.setSize(200, 200)
jshell> jf.setSize(201, 200)
jshell> jf.setSize(202, 200)
jshell> jf.setSize(202, 201)
jshell> jf.setSize(202, 202)
jshell> jf.setSize(400, 400)
jshell> jf.setSize(400, 400)
5.8.2 Resizing a JPanel¶
Now let's watch a resize event propagate to a JPanel container inside of
a JFrame.
Copy-and-paste the following block of code into your JShell prompt.
This code creates a JFrame object containing three JPanel objects.
By default, a JFrame uses the BorderLayout layout manager.
- BorderLayout - A Visual Guide to Layout Managers
- java.awt.BorderLayout
A BorderLayout divides the JFrame into five regions. In this example
we are using three of them. We give each JPanel a distinct color so
that we can see it. We also give each JPanel object a string name. This
will make it easier to identify the object in the console logging.
Notice that the center JPanel gets most of the area from the JFrame.
Resize the JFrame and watch how each JPanel gets resized by the layout
manager. The center panel always gets most of the JFrame area and the other
two panels are always thin stipes.
Define a simple ComponentListener object that overrides just the
componentResized() method. Add that listener to the JFrame (later
we will also add it to each JPanel). Copy-and-paste the following code
into your JShell prompt.
Resize the JFrame and look at the output in the console window. The
ComponentEvent objects tell you the size and location of the JFrame
after every resize event.
Now add the listener object to each JPanel object. Do this one JPanel
at a time. Resize the JFrame, after adding the listener to each JPanel,
and notice the ComponentEvent objects that come from each panel (you
can tell them apart by their location, size, and name).
We can cause more controlled resize events by calling the setSize() method
on the JFrame. Type the following lines of code into your JShell prompt, one
at a time. Notice that the center (red) JPanel gets both horizontal and
vertical resize events. The north (yellow) JPanel only gets horizontal resize
events. The east (green) JPanel only gets vertical resize events.
jshell> jf.setSize(200, 200)
jshell> jf.setSize(201, 200)
jshell> jf.setSize(202, 200)
jshell> jf.setSize(202, 201)
jshell> jf.setSize(202, 202)
jshell> jf.setSize(203, 203)
Remember that the three panels get their resize events sent to them by the
layout manager for the JFrame. When the JFrame is resized only in the
horizontal direction, the JFrame layout manager knows that both the center
and north panels need to be resized, but the east panel is not resized (but
it is moved, so it will get a moved event). Similarly when the JFrame is
resized only vertically.
Try directly resizing the center JPanel.
The JPanel did resize, but the JFrame did not!
If we pack() the JFrame we do not get what we might expect.
Try giving the center JPanel a minimum size.
Try giving the center JPanel a preferred size.
You can check that the center panel really does have a minimum and a preferred size.
Try changing the size of the center JPanel again (one line at a time).
jshell> jpCenter.setSize(50, 50)
jshell> jf.pack()
jshell> jpCenter.setSize(500, 500)
jshell> jf.pack()
Add a component to each of the north and east JPanel so that they need more
than the bare minimum of area.
Try the following command. Do you see the negative dimensions in the components?
Restore the GUI to its "preferred" dimensions.
5.8.3 Resizing a FrameBufferPanel¶
A FrameBufferPanel
is a JPanel, so it resizes just like any other JPanel.
If a layout manager detects the need for a FrameBufferPanel to resize itself,
then the layout manager triggers a resize event on any ComponentListener
attached to the FrameBufferPanel. But a FrameBufferPanel contains a
FrameBuffer
If you haven't done so already, unzip the renderer_5.zip distribution.
Open a command-prompt window in the "renderer_5" folder. From the command-line run the build scripts to build the "renderer_5.jar" jar file.
We shall use the "renderer_5.jar" file in JShell to create resizeable GUIs
that use the FrameBufferPanel class.
On the command-line (still in the "renderer_5" folder) start a JShell
session. Test that JShell can use the renderer's jar file by typing the
following two lines of code. The first puts the renderer's jar file in
JShell's classpath. The second line should print out a small FrameBuffer
object.
Copy-and-paste the following block of code into your JShell prompt.
Resize the JFrame several times. Notice from the ComponentEvent objects
in the console window that the FrameBufferPanel object gets resized by the
layout manager, but the FrameBuffer object in the FrameBufferPanel is not
being resized. Try these lines of code.
jshell> fbp.getSize()
jshell> fbp.getFrameBuffer().getWidthFB()
jshell> fbp.getFrameBuffer().getHeightFB()
Here s a way to think about this. We have a nested configuration where a
JFrame window contains a FrameBufferPanel which contains a FrameBuffer.
JFrame (resized by user)
|
\---FrameBufferPanel (resized by layout manager)
|
\---FrameBuffer (not being resized)
The JFrame window gets resized by a user. The layout manager from the JFrame
tells the nested FrameBufferPanel how it should resize itself. But nothing
(yet) is resizing the FrameBuffer nested inside of the FrameBufferPanel.
The ComponentListener object attached to the FrameBufferPanel does not
(yet) make the FrameBufferPanel resize its FrameBuffer. But a FrameBuffer
does not have a resize method. The dimensions of a FrameBuffer object are
final and immutable. In order for a FrameBufferPanel to "resize" its
FrameBuffer object, the FrameBufferPanel must instantiate a new
FrameBuffer object with the desired size.
Here is a ComponentListener object for the FrameBufferpanel that responds
to resize events by replacing the FrameBuffer with a new FrameBuffer that
fills the resized FrameBufferpanel.
Replace the previous ComponentListener object with this new one.
Resize the JFrame several more times. Notice from the ComponentEvent
objects in the console window that the FrameBufferPanel object gets resized
by the layout manager. The FrameBuffer object in the FrameBufferPanel gets
"resized" by the event handler attached to the FrameBufferPanel.
jshell> fbp.getSize()
jshell> fbp.getFrameBuffer().getWidthFB()
jshell> fbp.getFrameBuffer().getHeightFB()
Exercise: Rewrite the fbpResizeHandler0 resize event handler so that
it creates a Viewport within the FrameBuffer. Give the Viewport the
background color orange. Have the Viewport be centered in the FrameBuffer
and occupy 80% of the horizontal width of the FrameBuffer and 80% of the
vertical height of the FrameBuffer.
Let us use the renderer to put some 3D geometry in the FrameBuffer. First,
create a Scene.
We need a resize event handler that renders this Scene into the
FrameBuffer in the FrameBufferPanel.
Give the FrameBufferPanel this new event handler.
Resize the JFrame several more times. Be sure to try many different aspect
ratios. Notice that the FrameBuffer always has the aspect ratio of the
FrameBufferPanel (that is what the resize event handler guarantees).
When the FrameBufferPanel is not square, the sphere is distorted into
an ellipsoid.
We can think about this situation the following way. We have a nested
configuration where a JFrame window contains a FrameBufferPanel
which contains a FrameBuffer which contains a Viewport on which
an image is drawn.
JFrame (resized by user)
|
\---FrameBufferPanel (resized by layout manager)
|
\---FrameBuffer (resized by event handler)
|
\---Viewport (fills the FrameBuffer)
|
\---picture (gets distorted)
The JFrame window gets resized by a user. The JFrame's layout manager
tells the nested FrameBufferPanel how it should resize itself. Our component
listener resizes the FrameBuffer to fit the FrameBufferPanel. But our
component listener leaves the default Viewport filling up the FrameBuffer.
The distortion is caused by a mismatch in aspect ratios. The camera's view volume is projected onto the view rectangle in the image-plane. The view rectangle has an aspect ratio. The renderer renders the image in the view rectangle into the framebuffer's viewport. The viewport also has an aspect ratio. The renderer always fits the entire view rectangle onto the entire viewport. When their aspect ratios do not match, the final image in the viewport is a distorted version of the image in the view rectangle.
To solve this distortion problem we must either make the aspect ratio of the viewport match that of the view rectangle, or make the aspect ratio of the view rectangle (and the view volume) match the aspect ratio of the viewport. Neither strategy is better than the other. Neither strategy is easier to implement than the other. Both are commonly used, but they do not quite have the same visual effect. We will implement both strategies and then see how they look a bit different.
The following resize event handler makes the aspect ratio of the viewport match the aspect ratio of the view rectangle. We can think about this code this way.
JFrame (resized by user)
|
\---FrameBufferPanel (resized by layout manager)
|
\---FrameBuffer (resized by event handler)
|
\---Viewport (resized by event handler)
|
\---picture (drawn without distortion)
Since we are using the default camera, without any change in the standard view volume, the view rectangle is a square, with aspect ratio 1. In order to make the viewport have an aspect ratio of 1, while the framebuffer's aspect ratio can be anything, we letterbox a square viewport inside of the non-square framebuffer. In this example, we letterbox the viewport in the center of the framebuffer.
Give the FrameBufferPanel this new event handler.
Resize the JFrame several times. Be sure to try many different aspect
ratios. Notice that the framebuffer has an orange background color and
the viewport has a cyan background color, so we can see the viewport
letterboxed in the framebuffer. Also notice that the viewport is always
the maximally sized square that can fit in the framebuffer.
Look carefully at the code. The quantity d is the smaller of the framebuffer's
two dimensions. That's the dimension we use for the viewport (so the viewport
will "fill" one of the framebuffer's two dimensions). The quantity w - d
(respectively, h - d) is the "excess" length of the framebuffer in the
horizontal (respectively, vertical) direction. We do not know which one of
these really is an "excess", and which one is 0. We divide the excess by 2,
and put half of the excess on either side of the viewport. We do this by
calculating coordinates for the upper left-hand corner of the viewport in
the framebuffer.
Exercise: Rewrite fbpResizeHandler3 so that it puts the square Viewport
on the left edge of the FrameBuffer when the FrameBufferPanel is in a
landscape orientation, and it puts the Viewport on the bottom edge of the
FrameBuffer when the FrameBufferPanel is in a portrait orientation.
Here is the other way to solve the distortion problem. The following resize event handler makes the aspect ratio of the camera's view rectangle match the aspect ratio of the (whole) framebuffer. We are using the framebuffer's default viewport which fills up the framebuffer (so we are not letterboxing). The framebuffer has a cyan background color. The user of this program is in control of the framebuffer's aspect ratio. The event handler changes the camera's view volume to match the aspect ratio of the framebuffer.
Do a calculation and check that the aspect ratio of the camera's view
rectangle is equal to the aspect ratio of the FrameBufferPanel (and
the FrameBuffer).
Give the FrameBufferPanel this new event handler.
Resize the JFrame several times. Be sure to try many different aspect
ratios. Notice how this event handler preserves the aspect ratio of the
sphere without any letterboxing (the framebuffer's viewport is the whole
framebuffer).
We can ask the scene's camera to tell us its current state.
Look carefully at the code. Notice that one of w/d or h/d will be 1. So
either the right (and left) edge or the top (and bottom) edge of the view
rectangle will match the standard view rectangle. It will be the right (and
left) edge when the framebuffer is in a portrait orientation. It will be the
top (and bottom) edge when the framebuffer is in a landscape orientation.
The two non-standard edges will always be > 1 and < -1. The code sets the
non-standard edges of the view rectangle to give the view rectangle the
aspect ratio of the framebuffer.
We can easily switch between the event handlers we have defined. The following two lines will restore the resize event handler that has the distortion problem.
When we want to switch away from fbpResizeHandler3, we need to reset
the Camera back to the standard (normalized) view volume.
By switching between the two event handlers that solve the distortion problem, we can see that while they both keep the sphere spherical, they do produce a slightly different visual effect.
To better see how the two solutions to the distortion problem differ, let us add a square grid pattern to the scene. This square grid acts as a "background image".
When we switch between the two solutions, we can see that the second solution
allows us to see more, or less, of this background image as we resize the
JFrame. The first solution always shows the same portion of the background
image. The second solution would be more appropriate in situations where the
JFrame window is thought of as a "window into a scene". The first solution
is more appropriate when the JFrame window is thought of as a fixed scene.
Here, in one block of code, is the example GUI with all the resize event handlers.
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 100 101 102 103 104 | |
The active event handler is the one that has the distortion problem. You can
switch between the event handlers using the next two lines of code. The third
line of code triggers a ComponentEvent that redraws the GUI.
When you create a GUI using JShell, if the GUI seems to look kind of ugly, and especially if the GUI is larger than it should be, then start JShell with the following command-line.
This tells the JVM running the JShell code to not rescale the GUI when it draws the GUI's pixels on the computer screen.
Exercise: Add a KeyListener to the above code and implement the
keyTyped() method so that the keys '0', '1', '2', and '3' switch the
program between fbpResizeHandler0, fbpResizeHandler1, fbpResizeHandler2,
and fbpResizeHandler3.
Exercise: Give jpEast a group of four JRadioButton components and
attach an ActionListener to the buttons so that they select an appropriate
ComponentListener for fbp.
Exercise: Convert the above script into a Java client program. Have the program use keyboard input, '0', '1', '2', '3', to switch between the four resize event handlers.
Exercise: Create a subclass of FrameBufferPanel, called ThreeDScenePanel,
that overrides the paintComponent() method to draw a simple 3D Scene into
the FrameBuffer. Give an instance of ThreeDScenePanel a ComponentListener
that overrides componentResized(). The componentResized() method should end
with a call to the repaint() method in the ThreeDScenePanel object. Compare
this with the MVC design pattern.
In the folder
there are programs that demonstrate several ways a graphics program can react to a user changing the shape of the program's window.In that folder are the two illustrations that try to visualize the
relationship between cropping, letterboxing, and the parameters to the
projOrtho() and setViewport() methods.