You are on page 1of 53

Computer Graphics Programming in

OpenGL with Java Gordon


Visit to download the full and correct content document:
https://textbookfull.com/product/computer-graphics-programming-in-opengl-with-java-
gordon/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Computer Graphics Programming in OpenGL with Java 2nd


Edition V. Scott Gordon

https://textbookfull.com/product/computer-graphics-programming-
in-opengl-with-java-2nd-edition-v-scott-gordon/

Computer Graphics Programming in OpenGL Using C++,


Third Edition Gordon Phd

https://textbookfull.com/product/computer-graphics-programming-
in-opengl-using-c-third-edition-gordon-phd/

Introduction to Computer Graphics with OpenGL ES First


Edition Junghyun Han

https://textbookfull.com/product/introduction-to-computer-
graphics-with-opengl-es-first-edition-junghyun-han/

Computer graphics through openGL Third Edition Guha

https://textbookfull.com/product/computer-graphics-through-
opengl-third-edition-guha/
Computer Graphics Through OpenGL: From Theory to
Experiments Sumanta Guha

https://textbookfull.com/product/computer-graphics-through-
opengl-from-theory-to-experiments-sumanta-guha/

Learn OpenGL Learn modern OpenGL graphics programming


in a step by step fashion 1st Edition Joey De Vries

https://textbookfull.com/product/learn-opengl-learn-modern-
opengl-graphics-programming-in-a-step-by-step-fashion-1st-
edition-joey-de-vries/

Computer Graphics for Java Programmers 3rd Edition Leen


Ammeraal

https://textbookfull.com/product/computer-graphics-for-java-
programmers-3rd-edition-leen-ammeraal/

OpenGL Programming Guide The Official Guide to Learning


OpenGL Version 4 5 with SPIR V 9th Edition Kessenich

https://textbookfull.com/product/opengl-programming-guide-the-
official-guide-to-learning-opengl-version-4-5-with-spir-v-9th-
edition-kessenich/

Learning Java An Introduction to Real World Programming


with Java Marc Loy

https://textbookfull.com/product/learning-java-an-introduction-
to-real-world-programming-with-java-marc-loy/
Computer GraphiCs
proGramminG in openGL
with Java
LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY

By purchasing or using this book (the “Work”), you agree that this license grants
permission to use the contents contained herein, but does not give you the right
of ownership to any of the textual content in the book or ownership to any of the
information or products contained in it. This license does not permit uploading of the
Work onto the Internet or on a network (of any kind) without the written consent of
the Publisher. Duplication or dissemination of any text, code, simulations, images,
etc. contained herein is limited to and subject to licensing terms for the respective
products, and permission must be obtained from the Publisher or the owner of the
content, etc., in order to reproduce or network any portion of the textual material
(in any media) that is contained in the Work.

Mercury Learning and inforMation (“MLI” or “the Publisher”) and anyone


involved in the creation, writing, or production of the companion disc,
accompanying algorithms, code, or computer programs (“the software”), and any
accompanying Web site or software of the Work, cannot and do not warrant the
performance or results that might be obtained by using the contents of the Work.
The authors, developers, and the Publisher have used their best efforts to insure
the accuracy and functionality of the textual material and/or programs contained
in this package; we, however, make no warranty of any kind, express or implied,
regarding the performance of these contents or programs. The Work is sold “as is”
without warranty (except for defective materials used in manufacturing the book
or due to faulty workmanship).

The authors, developers, and the publisher of any accompanying content, and
anyone involved in the composition, production, and manufacturing of this work
will not be liable for damages of any kind arising out of the use of (or the inability to
use) the algorithms, source code, computer programs, or textual material contained
in this publication. This includes, but is not limited to, loss of revenue or profit, or
other incidental, physical, or consequential damages arising out of the use of this
Work.

The sole remedy in the event of a claim of any kind is expressly limited to
replacement of the book, and only at the discretion of the Publisher. The use of
“implied warranty” and certain “exclusions” vary from state to state, and might not
apply to the purchaser of this product.

Companion disc files are available for download from the publisher by writing to
info@merclearning.com.
Computer GraphiCs
proGramminG in openGL
with Java

V. Scott Gordon, Ph.D.


California State University, Sacramento

John Clevenger, Ph.D.


California State University, Sacramento

merCury LearninG and information


Dulles, Virginia
Boston, Massachusetts
New Delhi
Copyright ©2017 by Mercury Learning and InforMation LLC. All rights reserved.

This publication, portions of it, or any accompanying software may not be reproduced in any way,
stored in a retrieval system of any type, or transmitted by any means, media, electronic display or
mechanical display, including, but not limited to, photocopy, recording, Internet postings, or scan-
ning, without prior permission in writing from the publisher.

Publisher: David Pallai

Mercury Learning and InforMation


22841 Quicksilver Drive
Dulles, VA 20166
info@merclearning.com
www.merclearning.com
(800) 232-0223

V. Scott Gordon & John Clevenger


Computer Graphics Programming in OpenGL with Java
ISBN: 978-1-683920-27-4

The publisher recognizes and respects all marks used by companies, manufacturers, and
developers as a means to distinguish their products. All brand names and product names mentioned
in this book are trademarks or service marks of their respective companies. Any omission or misuse
(of any kind) of service marks or trademarks, etc. is not an attempt to infringe on the property
of others.

Library of Congress Control Number: 2016962393

171819321 Printed in the United States of America on acid-free paper

Our titles are available for adoption, license, or bulk purchase by institutions, corporations, etc.
For additional information, please contact the Customer Service Dept. at 800-232-0223 (toll free).
Digital versions of our titles are available at: www.authorcloudware.com and other e-vendors. All
companion files are available by writing to the publisher at info@merclearning.com.

The sole obligation of Mercury Learning and InforMation to the purchaser is to replace the book
and/or disc, based on defective materials or faulty workmanship, but not based on the operation or
functionality of the product.
Contents
Preface xi
Intended Audience xiii
How to Use This Book xiii
Acknowledgments xv
About the Authors xv

Chapter 1 Getting Started 1


1.1 Languages and Libraries 1
1.1.1 Java 2
1.1.2 OpenGL / GLSL 2
1.1.3 JOGL 3
1.1.4 graphicslib3D 3
1.2 Installation and Configuration 3
1.2.1 Installing Java 3
1.2.2 Installing OpenGL / GLSL 4
1.2.3 Installing JOGL 4
1.2.4 Installing graphicslib3D 4

Chapter 2 JOGL and the OpenGL Graphics Pipeline 7


2.1 The OpenGL Pipeline 8
2.1.1 Java/JOGL Application 9
2.1.2 Vertex and Fragment Shaders 12
2.1.3 Tessellation 17
2.1.4 Geometry Shader 18
2.1.5 Rasterization 19
2.1.6 Fragment Shader 20
2.1.7 Pixel Operations 21
2.2 Detecting OpenGL and GLSL Errors 23
2.3 Reading GLSL Source Code from Files 27
2.4 Building Objects from Vertices 29
2.5 Animating a Scene 30

Chapter 3 Mathematical Foundations 35


3.1 3D Coordinate Systems 36
3.2 Points 36
3.3 Matrices 37
3.4 Transformation Matrices 40
3.4.1 Translation 40
3.4.2 Scaling 41
3.4.3 Rotation 42
3.5 Vectors 44
3.5.1 Uses for Dot Product 45
3.5.2 Uses for Cross Product 47
3.6 Local and World Space 48
3.7 Eye Space and the Synthetic Camera 49
3.8 Projection Matrices 52
3.8.1 The Perspective Projection Matrix 52
3.8.2 The Orthographic Projection Matrix 54
3.9 Look-At Matrix 56
3.10 GLSL Functions for Building Matrix Transforms 57

Chapter 4 Managing 3D Graphics Data 63


4.1 Buffers & Vertex Attributes 64
4.2 Uniform Variables 67
4.3 Interpolation of Vertex Attributes 68
4.4 Model-View and Perspective Matrices 69
4.5 Our First 3D Program – a 3D Cube 71
4.6 Rendering Multiple Copies of an Object 80
4.6.1 Instancing 81
4.7 Rendering Multiple Different Models in a Scene 85
4.8 Matrix Stacks 87

vi ■ C o n t e n ts
4.9 Combating “Z-Fighting” Artifacts 94
4.10 Other Options for Primitives 95
4.11 Back-Face Culling 97

Chapter 5 Texture Mapping 103


5.1 Loading Texture Image Files 104
5.2 Texture Coordinates 106
5.3 Creating a Texture Object 108
5.4 Constructing Texture Coordinates 108
5.5 Loading Texture Coordinates into Buffers 110
5.6 Using the Texture in a Shader: Sampler Variables and Texture Units 110
5.7 Texture Mapping: Example Program 111
5.8 Mipmapping 114
5.9 Anisotropic Filtering 120
5.10 Wrapping and Tiling 121
5.11 Perspective Distortion 123
5.12 Loading Texture Image Files Using Java AWT Classes 124

Chapter 6 3D Models 129


6.1 Procedural Models – Building a Sphere 130
6.2 OpenGL Indexing – Building a Torus 137
6.2.1 The Torus 137
6.2.2 Indexing in OpenGL 139
6.3 Loading Externally Produced Models 144

Chapter 7 Lighting 157


7.1 Lighting Models 157
7.2 Lights 159
7.3 Materials 163
7.4 ADS Lighting Computations 165
7.5 Implementing ADS Lighting 168
7.5.1 Gouraud Shading 169
7.5.2 Phong Shading 177
7.6 Combining Lighting and Textures 182

Chapter 8 Shadows 189


8.1 The Importance of Shadows 189
8.2 Projective Shadows 190

C onte nts ■ vii


8.3 Shadow Volumes 191
8.4 Shadow Mapping 192
8.4.1 Shadow Mapping (PASS ONE) – “Draw” Objects
from Light Position 193
8.4.2 Shadow Mapping (Intermediate Step) – Copying the
Z-Buffer to a Texture 194
8.4.3 Shadow Mapping (PASS TWO) – Rendering the
Scene with Shadows 195
8.5 A Shadow Mapping Example 199
8.6 Shadow Mapping Artifacts 205

Chapter 9 Sky and Backgrounds 211


9.1 Skyboxes 211
9.2 Skydomes 214
9.3 Implementing a Skybox 215
9.3.1 Building a Skybox from Scratch 216
9.3.2 Using OpenGL Cube Maps 219
9.4 Environment Mapping 223

Chapter 10 Enhancing Surface Detail 231


10.1 Bump Mapping 232
10.2 Normal Mapping 233
10.3 Height Mapping 242

Chapter 11 Parametric Surfaces 249


11.1 Quadratic Bézier Curves 249
11.2 Cubic Bézier Curves 251
11.3 Quadratic Bézier Surfaces 254
11.4 Cubic Bézier Surfaces 256

Chapter 12 Tessellation 261


12.1 Tessellation in OpenGL 261
12.2 Tessellation for Bézier Surfaces 267
12.3 Tessellation for Terrain / Height Maps 273
12.4 Controlling Level of Detail (LOD) 281

viii ■ C o n t e n ts
Chapter 13 Geometry Shaders 287
13.1 Per-Primitive Processing in OpenGL 287
13.2 Altering Primitives 288
13.3 Deleting Primitives 293
13.4 Adding Primitives 294

Chapter 14 Other Techniques 299


14.1 Fog 299
14.2 Compositing / Blending / Transparency 302
14.3 User-Defined Clipping Planes 308
14.4 3D Textures 310
14.5 Noise 316
14.6 Noise Application – Marble 321
14.7 Noise Application – Wood 323
14.8 Noise Application – Clouds 327
14.9 Noise Application – Special Effects 332

Index 337

C onte nts ■ ix
Preface
This book is designed primarily as a textbook for a typical computer science undergradu-
ate course in OpenGL 3D graphics programming. However, we have also wanted to create
a text that could be used to teach oneself, without an accompanying course. With both of
those aims in mind, we have tried to explain things as clearly and simply as we can. Every
programming example is stripped-down and simplified as much as possible, but still com-
plete so that the reader may run them all as presented.

One of the things that we hope is unique about this book is that we have strived to make
it accessible to a beginner—that is, someone new to 3D graphics programming. While
there is by no means a lack of information available on the topic—quite the contrary—
many students are initially overwhelmed. This text is our attempt to write the book we
wish we had had when we were starting out, with step-by-step explanations of the basics,
progressing in an organized manner up through advanced topics. We considered titling the
book “shader programming made easy”; however, we don’t think that there really is any
way of making shader programming “easy.” We hope that we have come close.

Another thing that makes this book unique is that it teaches OpenGL programming
in Java, using JOGL—a Java “wrapper” for OpenGL’s native C calls [JO16]. There are
several advantages to learning graphics programming in Java rather than in C:
• It is more convenient for students at schools that conduct most of their curriculum
in Java.
• Java’s I/O, window, and event handling are arguably cleaner than in C.
• Java’s excellent support for object-oriented design patterns can foster good design.
It is worth mentioning that there do exist other Java bindings for OpenGL. One that
is becoming increasingly popular is Lightweight Java Game Library, or LWJGL [LW16].
Like JOGL, LWJGL also offers bindings for OpenAL and OpenCL. This textbook focuses
only on JOGL.

Another point of clarification is that there exist both different versions of OpenGL
(briefly discussed later) and different variants of OpenGL. For example, in addition to
“standard OpenGL” (sometimes called “desktop OpenGL”), there exists a variant called
“OpenGL ES” which is tailored for development of embedded systems (hence the “ES”).
“Embedded systems” include devices such as mobile phones, game consoles, automobiles,
and industrial control systems. OpenGL ES is mostly a subset of standard OpenGL, elimi-
nating a large number of operations that are typically not needed for embedded systems.
OpenGL ES also adds some additional functionality, typically application-specific opera-
tions for particular target environments. The JOGL suite of Java bindings includes inter-
faces for different versions of OpenGL ES, although we do not use them in this book.

Yet another variant of OpenGL is called “WebGL.” Based on OpenGL ES, WebGL is
designed to support the use of OpenGL in web browsers. WebGL allows an application to
use JavaScript1 to invoke OpenGL ES operations, which makes it easy to embed OpenGL
graphics into standard HTML (web) documents. Most modern web browsers support
WebGL, including Apple Safari, Google Chrome, Microsoft Internet Explorer, Mozilla
Firefox, and Opera. Since web programming is outside the scope of this book, we will not
cover any WebGL specifics. Note however that because WebGL is based on OpenGL ES,
which in turn is based on standard OpenGL, much of what is covered in this book can be
transferred directly to learning about these OpenGL variants.

The very topic of 3D graphics lends itself to impressive, even beautiful images.
Indeed, many popular textbooks on the topic are filled with breathtaking scenes, and it
is enticing to leaf through their galleries. While we acknowledge the motivational utility
of such examples, our aim is to teach, not to impress. The images in this book are simply
the outputs of the example programs, and since this is an introductory text, the resulting
scenes are unlikely to impress an expert. However, the techniques presented do constitute
the foundational elements for producing today’s stunning 3D effects.

We also haven’t tried to create an OpenGL or JOGL “reference.” Our coverage of


OpenGL and JOGL represents only a tiny fraction of their capabilities. Rather, our aim is to

1
JavaScript is a scripting language that can be used to embed code in webpages. It has strong
similarities to Java, but also many important differences.

xii ■ Pr e f a c e
use OpenGL and JOGL as vehicles for teaching the fundamentals of modern shader-based
3D graphics programming, and provide the reader with a sufficiently deep understanding
for further study. If along the way this text helps to expand awareness of JOGL and other
JogAmp technologies, that would be nice too.

Intended Audience
This book is targeted at students of computer science. This could mean undergraduates pur-
suing a BS degree, but it could also mean anyone who studies computer science. As such, we
are assuming that the reader has at least a solid background in object-oriented programming,
at the level of someone who is, say, a computer science major at the junior or senior level.

There are also some specific things that we use in this book, but that we don’t cover
because we assume the reader already has sufficient background. In particular:
• Java and its Abstract Window Toolkit (AWT) or Swing library, especially for
GUI-building
• Java configuration details, such as manipulating the CLASSPATH
• event-driven programming
• basic matrix algebra and trigonometry
• awareness of color models, such as RGB, RGBA, etc.

How to Use This Book


This book is designed to be read from front to back. That is, material in later chapters
frequently relies on information learned in earlier chapters. So it probably won’t work to
jump back and forth in the chapters; rather, work your way forwards through the material.

This is also intended mostly as a practical, hands-on guide. While there is plenty of
theoretical material included, the reader should treat this text as a sort of “workbook,” in
which you learn basic concepts by actually programming them yourself. We have provided
code for all of the examples, but to really learn the concepts you will want to play with
those examples—extend them to build your own 3D scenes.

At the end of each chapter are a few problems to solve. Some are very simple, involv-
ing merely making simple modifications to the provided code. The problems that are
marked “(PROJECT),” however, are expected to take some time to solve, and require writ-
ing a significant amount of code, or combining techniques from various examples. There
are also a few marked “(RESEARCH)”—those are problems that encourage independent
study because this textbook doesn’t provide sufficient detail to solve them.

Pre fa c e ■ xiii
OpenGL calls, whether made in C or in Java through JOGL, often involve long lists of
parameters. While writing this book, the authors debated whether or not to, in each case,
describe all of the parameters. We decided that at the very beginning, we would describe
every detail. But as the topics progress, we decided to avoid getting bogged down in every
piece of minutiae in the OpenGL calls (and there are many), for fear of the reader losing
sight of the big picture. For this reason, it is essential when working through the examples
to have ready access to reference material for Java, OpenGL, and JOGL.

For this, there are a number of excellent reference sources that we recommend using
in conjunction with this book. The javadocs for Java and JOGL are absolutely essential,
and can be accessed online or downloaded (we explain in Chapter 1 how to download the
JOGL javadoc). The reader should bookmark them for easy access in a browser, and expect
to access them continuously for looking up items such as parameter and constructor details.
The URLs for the Java and JOGL javadocs are:

https://docs.oracle.com/javase/8/docs/api/
https://jogamp.org/deployment/webstart/javadoc/jogl/javadoc

Many of the entries in the JOGL javadoc are simply pointers to the corresponding
entry in the OpenGL documentation, available here:

https://www.opengl.org/sdk/docs/man/

Our examples utilize a mathematics library called graphicslib3D. This is a Java library
that also has its own set of javadocs included. After installing graphicslib3D (described in
Chapter 1), the reader should locate the accompanying javadoc folder and bookmark its
root file (index.html).

Finally, there are many other books on 3D graphics programming that we recommend
reading in parallel with this book (such as for solving the “research” problems). Here are
five that we often refer to:
• (Sellers et al.) OpenGL SuperBible [SW15]
• (Kessenich et al.) OpenGL Programming Guide [KS16] (the “red book”)
• (Wolff) OpenGL 4 Shading Language Cookbook [WO13]
• (Angel and Shreiner) Interactive Computer Graphics [AS14]
• (Luna) Introduction to 3D Game Programming with DirectX 12 [LU16]

xiv ■ Pr e f a c e
Acknowledgments
Early drafts of this book were used in the CSc-155 (Advanced Computer Graphics
Programming) course at CSU Sacramento, and benefited from many student corrections
and comments (and in some cases, code). The authors would particularly like to thank
Mitchell Brannan, Tiffany Chiapuzio-Wong, Samson Chua, Anthony Doan, Kian Faroughi,
Cody Jackson, John Johnston, Zeeshan Khaliq, Raymond Rivera, Oscar Solorzano, Darren
Takemoto, Jon Tinney, James Womack, and Victor Zepeda for their suggestions. We
apologize if we have missed anyone.

We are extremely grateful for the invaluable advice provided to us by Julien Gouesse,
engine support maintainer at Jogamp. Mr. Gouesse provided technical information on
JOGL textures, cube maps, buffer handling, and proper loading of shader source files that
led to improvements in our text.

Jay Turberville of Studio 522 Productions in Scottsdale (Arizona) built the dolphin
model shown on the cover and used throughout this book. Studio 522 Productions does
incredibly high-quality 3D animation and video production, as well as custom 3D mod-
eling. We were thrilled that Mr. Turberville kindly offered to build such a wonderful new
model just for this book project.

We wish to thank a few other artists and researchers who were gracious enough
to allow us to utilize their models and textures. James Hastings-Trew of Planet Pixel
Emporium provided many of the planetary surface textures. Paul Bourke allowed us to use
his wonderful star field. Dr. Marc Levoy of Stanford University granted us permission to
use the famous “Stanford Dragon” model. Paul Baker’s bump-mapping tutorial formed the
basis of the “torus” model we used in many examples. We also thank Mercury Learning
for allowing us to use some of the textures from [LU16].

Dr. Danny Kopec connected us with Mercury Learning and introduced us to its pub-
lisher, David Pallai. Dr. Kopec’s Artificial Intelligence textbook inspired us to consider
Mercury, and our telephone conversations with him were extremely informative. We were
deeply saddened to hear of Dr. Kopec’s untimely passing, and regret that he didn’t have the
chance to see our book come to fruition.

Finally, we wish to thank David Pallai and Jennifer Blaney of Mercury Learning for
believing in this project and guiding us through the textbook publishing process.

Pre fa c e ■ xv
About the Authors
Dr. V. Scott Gordon has been a professor in the California State University system for
over twenty years, and currently teaches advanced graphics and game engineering courses
at CSU Sacramento. He has authored or coauthored over thirty publications in a variety
of areas including video and strategy game programming, artificial intelligence, neural net-
works, software engineering, and computer science education. Dr. Gordon obtained his PhD
at Colorado State University. He is also a jazz drummer and a competitive table tennis player.

Dr. John Clevenger has over forty years of experience teaching a wide variety of courses
including advanced graphics, game architecture, operating systems, VLSI chip design,
system simulation, and other topics. He is the developer of several software frameworks
and tools for teaching graphics and game architecture, including the graphicslib3D library
used in this textbook. He is the technical director of the ACM International Collegiate
Programming Contest, and oversees the ongoing development of PC^2, the most widely
used programming contest support system in the world. Dr. Clevenger obtained his PhD
at the University of California, Davis. He is also a performing jazz musician, and spends
summer vacations in his mountain cabin.

References
[AS14] E. Angel, and D. Shreiner, Interactive Computer Graphics: A Top-Down
Approach with WebGL, 7th ed. (Pearson, 2014).

[JO16] Jogamp, accessed July 2016, http://jogamp.org/.

[LW16] Lightweight Java Game Library (LWJGL), accessed July 2016, https://www.
lwjgl.org/.

[LU16] F. Luna, Introduction to 3D Game Programming with DirectX 12, 2nd ed.
(Mercury Learning, 2016).

[KS16] J. Kessenich, G. Sellers, and D. Shreiner, OpenGL Programming Guide: The


Official Guide to Learning OpenGL, Version 4.5 with SPIR-V, 9th ed. (Addison-
Wesley, 2016).

[SW15] G. Sellers, R. Wright Jr., and N. Haemel., OpenGL SuperBible: Comprehensive


Tutorial and Reference, 7th ed. (Addison-Wesley, 2015).

[WO13] D. Wolff, OpenGL Shading Language Cookbook, 2nd ed. (Packt Publishing, 2013).

xvi ■ Pr e f a c e
C hapter 1
GettinG started
1.1 Languages and Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . .1
1.2 Installation and Configuration . . . . . . . . . . . . . . . . . . . . . .3

■ ■ ■■■
Graphics programming has a reputation of being among the most challeng-
ing computer science topics to learn. These days, graphics programming is shader
based—that is, some of the program is written in a standard language such as Java
or C++ for running on the CPU, and some is written in a special-purpose shader
language for running directly on the graphics card (GPU). Shader programming has
a steep learning curve, so that even drawing something simple requires a convoluted
set of steps to pass graphics data down a “pipeline.” Modern graphics cards are able
to process this data in parallel, and so the graphics programmer must understand the
parallel architecture of the GPU, even when drawing simple shapes.
The payoff, however, is extraordinary power. The blossoming of stunning virtual
reality in videogames and increasingly realistic effects in Hollywood movies can be
greatly attributed to advances in shader programming. If reading this book is your
entrée into 3D graphics, you are taking on a personal challenge that will reward you
not only with pretty pictures, but with a level of control over your machine that you
never imagined was possible. Welcome to the exciting world of computer graphics!

1.1 LANGUAGES AND LIBRARIES


Running the programs in this book requires the use of the following four lan-
guages and libraries:

• Java
• OpenGL / GLSL
• JOGL
• graphicslib3D
2 ■ C o m p uter G rap h ics P ro g ram min g in O pe nG L w ith J a va

It is likely that the reader will need to do a few preparatory steps to ensure that
each of these are installed and properly accessible on his/her system. In this sec-
tion we briefly describe each of them. Then in the following section we show how
to install and/or configure them for use.

1.1.1 Java
Java was developed at Sun Microsystems in the early 1990s, and the first
stable release of a development kit (JDK) was in 1995. In 2010, Oracle Corp. ac-
quired Sun, and has maintained Java since that time [OR16]. This book assumes
Java version 8, which was released in 2014.

1.1.2 OpenGL / GLSL


Version 1.0 of OpenGL appeared in 1992 as an “open” alternative to vendor-
specific Application Programming Interfaces (APIs) for computer graphics. Its
specification and development was managed and controlled by the OpenGL Archi-
tecture Review Board (ARB), a then newly formed group of industry participants.
In 2006 the ARB transferred control of the OpenGL specification to the Khronos
Group, a nonprofit consortium which manages not only the OpenGL specification
but a wide variety of other open industry standards.
Since its beginning OpenGL has been revised and extended regularly. In 2004,
version 2.0 introduced the OpenGL Shading Language (GLSL), allowing “shader
programs” to be installed and run directly in graphics pipeline stages.
In 2009, version 3.1 removed a large number of features that had been depre-
cated, to enforce the use of shader programming as opposed to earlier approaches
(referred to as “immediate mode”).1 Among the more recent features, version 4.0
(in 2010) added a tessellation stage to the programmable pipeline.
This textbook assumes that the user is using a machine with a graphics card
that supports at least version 4.3 of OpenGL. If you are not sure which version of
OpenGL your GPU supports, there are free applications available on the web that
can be used to find out. One such application is GLView, by a company named
“realtechvr” [GV16].

1
Despite this, many graphics card manufacturers (notably NVIDIA) continue to support
deprecated functionality.
C ha pte r 1 · G e tting Sta rte d ■ 3

1.1.3 JOGL
JOGL first appeared in 2003, published on the website Java.net. Since 2010
it has been an independent open source project, and part of a suite of Java bind-
ings maintained by JogAmp [JO15], an online community of developers. JogAmp
also maintains JOAL and JOCL, bindings for OpenAL and OpenCL, respectively.
As new versions of OpenGL and/or Java are released, new versions of JOGL are
developed to support continued compatibility. JogAmp also maintains a short
online user’s guide that includes valuable guidelines for installing and using JOGL
efficiently and effectively [JU16]. This book assumes at least version 2.3 of JOGL.

1.1.4 graphicslib3D
3D graphics programming makes heavy use of vector and matrix algebra.
For this reason, use of OpenGL is greatly facilitated by accompanying it with
a function library or class package to support common mathematical functions.
For example, the popular OpenGL Superbible [SW15] utilizes a C library called
“vecmath”. In this book, we use a Java library called graphicslib3D.
graphicslib3D provides classes for basic math functions related to graphics con-
cepts, such as vector, matrix, point, vertex, and quaternion. It also contains a few
utility classes for storing frequently used 3D graphics structures, such as a stack
for building hierarchical structures, lighting and material information, and a few
basic shapes such as a sphere and a torus.
graphicslib3D was first developed in 2005 by John Clevenger at California State
University Sacramento, and is maintained by the authors.

1.2 INSTALLATION AND CONFIGURATION


1.2.1 Installing Java
To use Java for the examples in this book, you will need both the JRE (Java
Runtime Environment) and the JDK (Java Development Kit). To install them, use
Oracle’s download site, http://www.oracle.com/technetwork/java, and click the “Java
SE” (Standard Edition) link under “Software Downloads.” From there you can
find instructions for downloading the latest JDK, which includes both the Java
compiler and the JRE. It is assumed that the reader is experienced with program-
ming in Java. At the time of this writing, the current version of Java is version 8.
4 ■ C o m p uter G rap h ics P ro g ram min g in O pe nG L w ith J a va

1.2.2 Installing OpenGL / GLSL


It is not necessary to “install” OpenGL or GLSL, but it is necessary to ensure
that your graphics card supports at least version 4.3 of OpenGL. If you do not
know what version of OpenGL your machine supports, you can use one of the
various free applications (such as GLView [GV16]) to find out.

1.2.3 Installing JOGL


To install JOGL, visit http://jogamp.org. As of this writing, the current version
of JOGL is in the “Builds/Downloads” section—look under “Current” and click on
[zip]. This displays the latest stable JOGL files in a folder named “/deployment/
jogamp-current/archive”. Download the following:

jogamp-all-platforms.7z
jogl-javadoc.7z

Unzip these files into the folder on your machine where you would like to
store the JOGL system. A typical location in Windows could be, for example, in a
folder at the root of the C: drive.
The unzipped “jogamp-all-platforms” file contains a folder named “jar”, which
contains two important files that will be used by your applications:

jogl-all.jar
gluegen-rt.jar

Add the full path name of each of these two files to your CLASSPATH environ-
ment variable.
In the jogl-javadoc folder, double-click the file named index.html. This opens the
JOGL javadocs in a browser, which you should then bookmark.

1.2.4 Installing graphicslib3D


To install graphicslib3D, download the graphicslib3D.zip file from the
textbook support website or the accompanying disc. Unzipping this file
ON THE CD
produces a folder containing the following two items:
C ha pte r 1 · G e tting Sta rte d ■ 5

• A file named graphicslib3D.jar


• A folder named javadoc
Move these files to wherever you would like to store graphicslib3D—a typical
location in Windows could be, for example, in a folder at the root of the C: drive.
Add the full path name of the .jar file to your CLASSPATH environment variable.
Open the index.html file in the javadoc folder, and bookmark it as you did for
the JOGL Javadoc.

References
[GV16] GLView, realtech-vr, accessed July 2016, http://www.realtech-vr.com/
glview/.
[JO16] Jogamp, accessed July 2016, http://jogamp.org/.
[JU16] JOGL Users Guide, accessed July 2016, https://jogamp.org/jogl/doc/
userguide/.
[OR16] Java Software, Oracle Corp., accessed July 2016, https://www.oracle.com/
java/index.html.
[SW15] G. Sellers, R. Wright Jr., and N. Haemel, OpenGL SuperBible:
Comprehensive Tutorial and Reference, 7th ed. (Addison-Wesley, 2015).
C hapter 2
JoGL and the openGL
GraphiCs pipeLine

2.1 The OpenGL Pipeline . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8


2.2 Detecting OpenGL and GLSL Errors. . . . . . . . . . . . . . . .23
2.3 Reading GLSL Source Code from Files . . . . . . . . . . . . . .27
2.4 Building Objects from Vertices . . . . . . . . . . . . . . . . . . . . .29
2.5 Animating a Scene . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30
Supplemental Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

■ ■ ■■■
OpenGL (Open Graphics Library) is a multi-platform 2D and 3D graphics API
that incorporates both hardware and software. Using OpenGL requires a graphics
card (GPU) that supports a sufficiently up-to-date version of OpenGL (as described
in Chapter 1).
On the hardware side, OpenGL provides a multi-stage graphics pipeline that is
partially programmable using a language called GLSL (OpenGL Shading Language).
On the software side, OpenGL’s API is written in C, and thus the calls are directly
compatible with C and C++. However, stable language bindings (or “wrappers”) are
available for more than a dozen other popular languages (Java, Perl, Python, Visual
Basic, Delphi, Haskell, Lisp, Ruby, etc.) with virtually equivalent performance. This
textbook uses the popular Java wrapper JOGL (Java OpenGL). When using JOGL,
the programmer writes a Java program that runs on the CPU (more specifically, on
the Java Virtual Machine, or JVM) and includes JOGL (and thus, OpenGL) calls. We
will refer to a Java program that contains JOGL calls as a Java/JOGL application.
One important task of a Java/JOGL application is to install the programmer’s GLSL
code onto the GPU.
8 ■ C o m p uter G rap h ics P ro g ram min g in O pe nG L w ith J a va

An overview of a JOGL-based
graphics application is shown in Fig-
ure 2.1, with the software components
highlighted in red:
Some of the code we will write
will be in Java, with JOGL calls, and
some will be written in GLSL. Our
Java/JOGL application will work to-
gether with our GLSL modules, and
the hardware, to create our 3D graph-
ics output. Once our application is
Figure 2.1 complete, the end user will interact
Overview of a JOGL-based graphics application. with the Java application.
GLSL is an example of a shader language. Shader languages are intended
to run on a GPU, in the context of a graphics pipeline. There are other shader
languages, such as HLSL, which works with Microsoft’s 3D framework DirectX.
GLSL is the specific shader language that is compatible with OpenGL, and thus
we will write shader code in GLSL, in addition to our Java/JOGL application code.
For the rest of this chapter, we will take a brief “tour” of the OpenGL pipeline.
The reader is not expected to understand every detail thoroughly, but just to get a
feel for how the stages work together.

2.1 THE OPENGL PIPELINE


Modern 3D graphics programming utilizes a pipeline, in which the process
of converting a 3D scene to a 2D image is broken down into a series of steps.
OpenGL and DirectX both utilize similar pipelines.
A simplified overview of the OpenGL graphics pipeline is shown in Figure 2.2
(not every stage is shown, just the major ones we will study). The Java/JOGL ap-
plication sends graphics data into the vertex shader—processing proceeds through
the pipeline, and pixels emerge for display on the monitor.
The stages shaded in blue (vertex, tessellation, geometry, and fragment) are
programmable in GLSL. It is one of the responsibilities of the Java/JOGL applica-
tion to load GLSL programs into these shader stages, as follows:

1. It uses Java to obtain the GLSL code, either from text files or hardcoded
as strings.
Ch ap ter 2 · J O G L and the O pe nG L G ra phic s Pipe line ■ 9

2. It then creates OpenGL shader ob-


jects, and loads the GLSL shader
code into them.
3. Finally, it uses OpenGL commands
to compile and link objects and in-
stall them on the GPU.
In practice, it is usually necessary to pro-
vide GLSL code for at least the vertex and
fragment stages, whereas the tessellation
and geometry stages are optional. Let’s walk
through the entire process and see what takes
place at each step. Figure 2.2
Overview of the OpenGL pipeline.

2.1.1 Java/JOGL Application


The bulk of our graphics application is written in Java. Depending on the pur-
pose of the program, it may interact with the end user using standard Java libraries
such as AWT or Swing. For tasks related to 3D rendering, it uses the JOGL library.
Other windowing libraries exist that interface with JOGL, such as SWT and NEWT,
that have some performance advantages; in this book, however, we use AWT and
Swing because of the likelihood the reader already has familiarity with them.
JOGL includes a class called GLCanvas that is compatible with the standard Java
JFrame, and on which we can draw 3D scenes. As already mentioned, JOGL also
gives us commands for installing GLSL programs onto the programmable shader
stages and compiling them. Finally, JOGL uses buffers for sending 3D models and
other related graphics data down the pipeline.
Before we try writing shaders, let’s write a simple Java/JOGL application
that instantiates a GLCanvas and sets its background color. Doing that won’t
require any shaders at all! The code is shown in Program 2.1 (translated to
Java from the C++ version in [SW15]). It extends JFrame, and instantiates a
GLCanvas, adding it to the JFrame. It also implements GLEventListener, required
to utilize OpenGL—this necessitates implementing some methods, specifi-
cally display(), init(), reshape(), and dispose(). The display() method is where we
place code that draws to the GLCanvas. In this example, we load a FloatBuffer
with values (1,0,0,1), corresponding to the RGB values of the color red (plus a
“1” for the opacity component), and use the OpenGL call glClearBuffer() to fill
the display buffer with that color.
10 ■ C o m p uter G rap h ics P ro g ram min g i n O pe nG L w ith J a va

Program 2.1 First Java/JOGL Application


import java.nio.*;
import javax.swing.*;
import static com.jogamp.opengl.GL4.*;
import com.jogamp.opengl.*;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.common.nio.Buffers;
public class Code extends JFrame implements GLEventListener
{ private GLCanvas myCanvas;
public Code()
{ setTitle(″Chapter2 - program1″);
setSize(600, 400);
setLocation(200, 200);
myCanvas = new GLCanvas();
myCanvas.addGLEventListener(this);
this.add(myCanvas);
setVisible(true);
}
public void display(GLAutoDrawable drawable)
{ GL4 gl = (GL4) GLContext.getCurrentGL();
float bkg[] = { 1.0f, 0.0f, 0.0f, 1.0f };
FloatBuffer bkgBuffer = Buffers.newDirectFloatBuffer(bkg);
gl.glClearBufferfv(GL_COLOR, 0, bkgBuffer);
}
public static void main(String[ ] args)
{ new Code();
}
public void init(GLAutoDrawable drawable) { }
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { }
public void dispose(GLAutoDrawable drawable) { }
}

When running a Java/JOGL application


(such as the above Program 2.1) on a Micro-
soft Windows machine, it is advisable to add
the command-line option to disable the use of
Direct3D acceleration, such as:

java -Dsun.java2d.d3d=false Code

Figure 2.3
The mechanism by which these functions
Output of Program 2-1. are deployed is as follows: When a GLCanvas
Ch ap ter 2 · J O G L and the O pe nG L G ra phic s Pipe line ■ 11

is made “visible” (by our calling “setVisible(true)” on the JFrame that contains it), it
initializes OpenGL, which in turn creates a “GL4” object that our application can use
for making OpenGL function calls. OpenGL then does a “callback,” calling init(),
and passes it a “drawable” object (in this case the drawable object is the GLCanvas,
although that isn’t obvious from the code). In this particular example, init() doesn’t
do anything—in most applications it is where we would read in GLSL code, load 3D
models, and so on. OpenGL next calls display(), also sending it the drawable object.
It is typical to immediately obtain the GL4 object and put it in a variable called “gl”.
(Actually, GL4 is an interface—in practice we don’t need to know the actual GL ob-
ject class).
Later we will see that if we want our scene to be animated, our Java/JOGL ap-
plication will need to tell OpenGL to make additional calls to display().
Now is an appropriate time to take a closer look at JOGL calls in Program 2.1.
Consider this one:

gl.glClearBufferfv(GL_COLOR, 0, bkgBuffer);

Since JOGL is a Java binding for OpenGL, that means that calls to JOGL in
turn generate calls to OpenGL’s library of C functions. In this case, the C function
being called, as described in the OpenGL reference documentation (available on
the web at https://www.opengl.org/sdk/docs) is:

glClearBufferfv(GLenum buffer, Glint drawbuffer, const GLfloat * value);

The first thing to notice is that the name of the JOGL function is the same as
that of the original OpenGL C function, except it is preceded by “gl.”, which is the
name of the GL4 object. The period “.” after the “gl” is significant because “gl” is
the object on which we are invoking the OpenGL function.
To reiterate, GL4 is a Java interface to the OpenGL functions. We can obtain
it in one of two ways: (a) by calling drawable.getGL(), utilizing the “GLAutoDraw-
able” object provided automatically when the various GLEventListener functions
are invoked (called back) by OpenGL, or (b) by calling GLContext.getCurrentGL()
as done in Program 2.1. Obtaining the current GL4 object is important because,
in general, any OpenGL function described in the OpenGL documentation can
be called from JOGL by preceding it with the name of the appropriate GL4 object
(such as “gl.”, here).
The next detail to notice is that the first parameter makes reference to a “GLenum”.
OpenGL has many predefined constants (enums); this one references the color buffer
GL_COLOR that contains the pixels as they are rendered. In actuality, there is more
12 ■ C o m p uter G rap h ics P ro g ram min g i n O pe nG L w ith J a va

than one color buffer, and the second parameter is used to specify which one we are
using (in this case, the 0th or first one).
Next, notice that the third parameter is defined in OpenGL as a C pointer.
While JOGL makes every effort to match the original OpenGL C calls, Java does
not have pointers. Any parameter in OpenGL that is a pointer is changed in JOGL.
In this case, the JOGL version utilizes a FloatBuffer instead. Whenever there is a
discrepancy between a JOGL call and the original C call, consult the JOGL Java-
doc for details on the revised parameter(s).1
Immediately before the call to glClearBufferfv() is a call to newDirectFloatBuffer().
We will learn about this function later in Chapter 4 when we discuss buffers and
the JOGL buffer tools.
Finally, besides display() and init(), we also must implement reshape() and
dispose(). The reshape() function is called when a GLCanvas is resized, and dispose()
is called when the application exits. In Program 2.1 we left them both empty.

2.1.2 Vertex and Fragment Shaders


Our first JOGL program didn’t actually draw anything—it simply filled the
color buffer with a single color. To actually draw something, we need to include a
vertex shader and a fragment shader.
You may be surprised to learn that OpenGL is capable of drawing only a few
kinds of very simple things, such as points, lines, or triangles. These simple things
are called primitives, and for this reason, most 3D models are made up of lots and
lots of primitives, usually triangles.
Primitives are made up of vertices—for example, a triangle consists of three
vertices. The vertices can come from a variety of sources—they can be read from
files and then loaded into buffers by the Java/JOGL application, or they can be
hardcoded in the Java code or even in the GLSL code.

1
In this example, we have described each parameter in the call. However, as the book proceeds,
we will sometimes not bother describing a parameter when we believe that doing so would
complicate matters unnecessarily. The reader should get used to using the JOGL/OpenGL
documentation to fill in such details as necessary.
Another random document with
no related content on Scribd:
he attempts to write quickly, there is a marked tremor which renders
the letters sometimes almost illegible. The up strokes show the most
tremor. There is no festination, no change in voice, no loss of power
over the sphincters, and no loss of reflexes; the reaction to the
galvanic current is normal.

Case II.—W. H——, æt. 58, male. For fifty years the patient has
been a hard writer, first as an editor and later as a cashier. In 1882
he noticed difficulty in raising arm to put away papers in pigeon-
holes above his head; this movement caused pain in shoulder and
arm. Shortly after this he found that his hand became tremulous
when he attempted to write, and later any voluntary effort was
sufficient to cause the tremor. There has been no cramp. The grip of
both hands is good, nor is there any wasting of the muscles.
Standing with eyes closed causes no swaying, although there are
occasional vertiginous attacks. While walking he has noticed that the
right arm does not swing with its usual freedom. No ataxic pains are
present. Reflexes of right arm and shoulder are very much
exaggerated; there are no changes in nutrition or sensation.
Galvanic reaction normal and alike in both arms. The urine is non-
albuminous.

The following case is in all probability one of diffused sclerotic


changes in the right lateral half of the cord, where the disease has
apparently ceased advancing:

Case III.—T. L——, æt. 45. In 1880, three years ago, patient noticed
occasional formication in various parts of the right face, hand, and
leg, which ceased after he suspended the use of tea and coffee;
soon after this he noticed that his writing began to lack ease and that
the letters became crowded toward the end of the line; later, a fine
tremor appeared in the fingers of the right hand; crampy sensations
then appeared in the hamstring muscles of right leg, chiefly while
sitting with the knee bent at right angles; writing with the right hand
was sufficient to cause, or at least aggravate, this. In 1882 the right
arm lost its automatic swing during walking, although holding the left
arm still would enable the right arm to swing automatically. Lately the
symptoms have ceased advancing, and some seem to improve. His
present condition is an inability to write with right hand without
paying great attention and making each letter separately, and a
trembling of fingers during excitement of any kind. Coarse
movements of co-ordination can, as a rule, be well performed; there
is no increase of reflexes, nor are they absent; there is no ataxic gait,
and there are no trophic changes. Galvanic reaction is normal, and
alike on both sides. There is no history of hereditary disease or of
venereal taint.

In this connection it is proper to mention tremor mercurialis and


tremor saturninus, which might possibly lead to mistake should
proper attention not be paid to the history and to the symptoms.
Paul51 reports a case of the former affection, and gives a specimen
of the handwriting of the patient.
51 C. Paul, Bull. et Mém. de la Soc. de Thérap., Paris, 1881, xiii. pp. 129-131.

Traumatisms, etc. of the various nerves of the arm usually interfere


with the proper play of the muscles supplied by them, and although
certain of the milder forms of inflammation or of congestion, as
previously mentioned, are sometimes present in cases of
copodyscinesia, it is manifestly improper to include all cases of
impairment of hand-and-arm movement from nerve-injury under this
head.

Palsy from pressure, as from sleeping with the head resting upon the
arm or with the arm hanging over the back of a chair, is a frequent
cause of paresis or paralysis of the muscles supplied by the
musculo-spiral.

Tumors pressing upon the nerves in any part of their course, or


neuromata, may be mentioned among the more ordinary affections
that possibly might mislead.

Tenosynovitis which is described by Hopkins52 as a congestion of the


tendinous sheaths in the forearm, with insufficient lubrication of the
same, causing pain and interfering with motion, might be mistaken
for the disease in question, especially as it occurs in many of the
same occupations which furnish cases of copodyscinesia.
52 Wm. Barton Hopkins, “Tenosynovitis,” Med. News, Philada., July 15, 1882.

The exciting cause of tenosynovitis is “usually the resumption of


work to which the individual is thoroughly accustomed after a shorter
or longer interval when he is out of practice,” and not the
monotonous repetition of the same act. The differential diagnosis
should occasion no difficulty, as there is soreness amounting to
positive pain upon motion or pressure along the course of the
affected tendons, and the peculiar creaking which is communicated
to the finger on palpation.

PATHOLOGY AND MORBID ANATOMY.—Unfortunately for correct


determination of the pathological conditions underlying these
neuroses, there have been no reported examinations of the spinal
cord and nerves in subjects affected with copodyscinesia dying from
intercurrent diseases, although it is probable that no macroscopic
lesion would be discovered.

Solly53 reports the post-mortem appearance in a case of impaired


writing-power in which he found a granular disintegration of the
cervical portion of the cord; but this case, from his description, was
evidently one in which the impairment of power was merely one of
the numerous symptoms dependent upon disease of the cervical
cord from degenerative changes, and not a true case of writers'
cramp. If such a condition underlaid these neuroses, the cures
occasionally reported and the relief frequently felt after the use of the
galvanic current could not be explained.
53 London Lancet, vol i. p. 113.

In default, then, of positive information upon this point, conclusions


must be drawn from a study of the symptoms, the course, and the
behavior of these diseases under treatment. An affection of such
protean aspect is not likely to have one settled pathological condition
underlying it.
Many affections considered hitherto purely functional have under our
more advanced knowledge been found to have as a basis a positive
organic change.

On the subject of fatigue, Poore54 concisely states that the


symptoms “are referable to the muscles, but we must always bear in
mind that muscles and motor-nerve are one and indivisible, and that
recent experiments have given great probability to the idea that
every muscle is connected with a definite spot in the brain; when,
therefore, we speak of a sense of fatigue, we must necessarily be in
doubt, notwithstanding the fact that the symptoms are referred to the
muscles, whether brain, nerve, or muscle, one or all of them, be
really at fault.”
54 “On Fatigue,” London Lancet, vol. i., 1875, p. 163.

There is a certain limit to which exercise of a given group of muscles


may be carried without producing fatigue and local congestion, or
perhaps even inflammatory results; this varies greatly in different
individuals, but if it is continually and uninterruptedly overstepped,
and insufficient time given for rest and recuperation, the centres in
the spinal cord which regulate the action of the various muscles
implicated become overstimulated, and the result is an undue
amount of nervous energy induced by the peripheral excitation, or
there is a distortion of the central impulses in passing through these
centres: a perturbation of the co-ordinating power ensues and inco-
ordination is the result. Under rest and appropriate treatment these
symptoms may pass away, but if the part is continuously used it is
highly probable that nutritive changes will be produced in that part of
the spinal cord from which the nerves supplying the overtaxed
muscles proceed.

In some cases of hemiplegia there is produced during gaping and


sneezing an automatic movement of the paralyzed arm; this was
noticed as early as 1834 by Marshall Hall,55 and in 1872, Onimus56
noticed that movements of the hand and fingers of the non-paralyzed
arm produced similar movements in the paralyzed side.
55 Quoted by Charcot, Diseases of Spinal Cord, transl. by Comyges, Cincinnati, 1881,
p. 110.

56 Ibid.

Erb57 states that these movements in certain spinal troubles are


partly owing to the establishment of conditions of irritation in the
neighborhood of the lesion.
57 Ziemssen's Cyclopædia, Amer. ed., vol. xi. p. 409.

Hitzig58 states that in certain pathological conditions where the


ganglionic elements (in the cord) are superexcitable, the least
disturbance produced on one side, and which determines there a
voluntary movement, may be communicated to the other side, and
provoke, according to the case, either movements similar to a
voluntary one or a spasmodic movement which is really a
contraction; and also in certain cases relations of the same nature
may be established among cellular groups quite distant from each
other; and we can comprehend that in these cases the voluntary
movements executed by the sound side may be re-echoed in that
which is diseased.
58 Quoted by Charcot, loc. cit., p. 124.

This apparent digression bears an important relation to the pathology


of copodyscinesia, and lends force to the view that the associated
movements which occur in the well arm, or in the affected arm when
the sound side is used, or even in the face and legs, and which are
quite often seen in these affections, are due to the fact that there is a
central change.

Mitchell,59 in speaking of functional spasms, states that it will be


found in all these cases that when an ordinary functional motor act
gives rise to spasms elsewhere, these occur in muscles which have
physiological, and therefore anatomical, relations to the muscles
which by their normal use give rise to the morbid activities. He
considers that there is a hypersensitizing of the sensory centre which
takes record of the activities of the affected muscles.
59 “Functional Spasms,” Amer. J. Med. Sciences, Oct., 1876.

The fact that the left hand becomes implicated in some cases where
it is used to relieve the right should be mentioned in this connection
as lending weight to this hypothesis, especially as in a few cases of
telegraphers' cramp the left hand has been found implicated in the
very first attempt to use it in telegraphing.

Poore60 considers this transfer as no evidence that the change is


central, and is one of the few who consider the pathological
conditions as purely peripheral in character. Hamilton61 and De
Watteville62 also consider the peripheral hypothesis the correct one.
60 Loc. cit.

61 Nervous Diseases, Philada., 1881.

62 “The Cure of Writers' Cramp,” Brit. Med. Journ., 1885, vol. i. pp. 323-325.

Fritz63 (and after him Poincaré64) considers the disease a reflected


neurosis, due to a perversion of the muscular sense. Onimus and
Legros65 incline to the same opinion.
63 Oesterr. Jahrb., März u. April, 1844.

64 Le Système nerveux-péripherique, Paris, 1876.

65 Traité d'Electricite médicale, Paris, 1872, p. 327.

The older theory that the disease is solely central in its pathology is
advocated by Duchenne,66 Solly,67 Reynolds,68 Althaus,69 Wood,70
Vance,71 Erb,72 Dally,73 Axenfield,74 Whittaker,75 Waller,76 Gowers,77
Hammond,78 Romberg,79 Cederschjöld,80 Robins,81 Ross,82 and
some others. Roth83 considers that there are two entirely separate
classes, the central and the peripheral or local.
66 De l'Électrisation localisée, 3d ed., pp. 1021 et seq.

67 London Lancet, Jan. 28, 1865.

68 System of Medicine.

69 Julius Althaus, London Mirror, vol. vii., Aug. 1, 1870; also, pamphlet, Scriveners'
Palsy, London, 1870.

70 Practice of Medicine.

71 Reuben A. Vance, Bost. Med. and Surg. Journal, vol. lxxxviii. p. 261.

72 Ziemssen's Cyclopædia, vol. xi. p. 355.

73 Journal de Thérapeutique, Paris, 10 Fév., 1882.

74 Des Névroses, Paris, 1864.

75 Cincinnati Lancet and Clinic, 1880, N. S., vol. iv. p. 496.

76 Aug. Waller, Practitioner, 1880, vol. ii. p. 101.

77 W. R. Gowers, Med. Times and Gaz., 1877, vol. ii. p. 536.

78 Treatise on Dis. of Nervous System, 6th ed., New York, 1876.

79 Manual of Nervous Dis. in Man, Sydenham Society, vol. i.

80 Gustaf. Upsala läkarefören, förhandl. xv., 3 och. 4, S. 165, 1880, review in


Schmidt's Jahrb., Bd. clxxxvii., 1880, p. 239.

81 “Writers' Cramp,” Amer. Journ. Med. Sci., April, 1885, pp. 452-462.

82 A Treatise on Diseases of the Nervous System, London, 1881, vol. i. pp. 464-469.

83 The Treatment of Writers' Cramp, by Roth, London, 1885.


The later theory, that the disease is at first peripheral, but that by
abuse may become central (spinal), is advocated by Beard,84
Liebman,85 Bartholow,86 Frazer,87 and a few others. The latter theory,
and not the idea that it is a disease of the co-ordinating centres in
the brain or of the spinal centres only, best explains, in my opinion,
the various symptoms encountered.
84 New York Med. Record, 1879, p. 244.

85 Maryland Med. Journ., June, 1880-81, vol. vii.

86 Medical Electricity.

87 Glasgow Med. Journ., 1881, vol. xv. p. 169.

Many others have written upon this subject, but upon the probable
pathology they have been silent.

The experiments recently made by Dercum and Parker88 on the


artificial induction of convulsive seizures are of considerable interest,
and certainly tend to throw light on the point in question. These
convulsions were produced by subjecting a group of muscles to a
constant and precise effort, the attention being at the time
concentrated upon some train of thought. The position most
frequently adopted was to cause the arms to be held so that the tips
of the fingers barely touched the surface of the table before which
the subject was seated, the fingers not being allowed to rest upon
the table, but maintained by a constant muscular effort barely in
contact with it. After this position was maintained for a variable
length of time tremors commenced in the hands; a little later these
tremors became rapidly magnified into rapid movements of great
extent sometimes to and fro, sometimes irregular; if the experiment
was carried still farther, the muscles of the arms, shoulders, back,
buttocks, and legs become successively affected, and the subject
was frequently thrown violently to the ground in a strong general
convulsion, the consciousness being always retained.89 The more
frequently these experiments were performed, the more readily the
seizures were brought on, and, other things being equal, with
successively increasing intensity. One subject thus experimented
upon became so susceptible that the jar of a passing wagon sufficed
to induce a partial seizure. These experiments throw a new light
upon the associated movements previously mentioned, and show
how easily the phenomena noticed in one part may pass to another
having physiological relationship with it. It is highly probable that
some nutritional change in the cord would follow the too frequent
repetition of these experiments.
88 “The Artificial Induction of Convulsive Seizures,” Dercum-Parker, The Polyclinic,
Philada. 1884, vol. ii. pp. 95-97.

89 These experiments were subsequently repeated before the Philadelphia


Neurological Society in 1885.

Peripheral pathological conditions undoubtedly exist in many cases


of copodyscinesia; these may be so slight that they can scarcely be
demonstrated, or, on the other hand, they may be marked, and even
present a well-marked inflammation of one or more of the nerves of
the arm, as evidenced by pain on motion, tenderness on pressure,
and sensory and nutritive disturbances in the areas which they
supply.

There are some cases where the disability is pronounced, and yet
the most careful examination fails to reveal peripheral changes of
sufficient gravity to account for the severity of the symptoms; these,
in my opinion, are best explained by supposing a hyperexcitability of
the spinal centres, as previously expressed.

The electrical reaction in many cases tends to prove an irritable


condition of the spinal centres. In most of the cases of the spastic
group there will be found a quantitative increase in the reaction of
both nerve and muscle to the galvanic current. Gowers90 states that
he has found such an increase in diseases regarded as functional,
as paralysis agitans and chorea, and considers it an interesting proof
of the molecular changes which underlie or result from functional
maladies. He previously remarks91 that such a condition of exalted
irritability is to be ascribed to a corresponding change in the nutrition
of the nerve-cells of the spinal cord, secondary to the irritative
influence which caused it.
90 Dis. of Spinal Cord, 2d ed., Philada., 1881, p. 40.

91 Med. Times and Gaz., London, vol. ii., 1877, p. 536.

Erb92 also considers that quantitative increase in the electrical


reaction points to central lesion. Buzzard93 quotes several authors
upon tetany—which some cases of copodyscinesia closely resemble
—who state that the electrical reactions are increased quantitatively
in that affection, and considers, himself, that the change is due to
central lesion.
92 Loc. cit.

93 Thomas Buzzard, Dis. of the Nervous System, London, 1882.

It must be borne in mind, however, that in those cases of congestion


of the nerves, or neuritis, previously mentioned a quantitative
increase may be found, indicating a hypersensitiveness of the
peripheral nerve, and not necessarily of the spinal centres.

Poore94 states: “Thus we see that alterations of irritability” (he


especially alludes to depressions) “accompany many conditions,
both central and peripheral,” and “there is no necessity for assuming
that central change exists in every case of altered irritability, and we
have no warrant for such an assumption in the absence of
independent evidence of central change.”
94 “Impaired Writing-power,” loc. cit.

Exactly what the alteration in the condition of the spinal cord is which
probably occurs in many of these cases it is impossible to state, but
the view that it is a nutritive change of the upper dorsal and lower
cervical portion of the spinal cord (that is, when the arm is the part
affected, as it is in all but the rarer cases) is quite attractive, the
condition being secondary to a peripheral irritation in many cases.
Althaus95 considers that there is a “constriction of the small arteries,
dilatation of the veins, and slight serous effusions compressing the
nervous matter in the cervical spinal cord.”
95 Loc. cit.

Pain in the cervical and dorsal spine during work may be mentioned
here as an evidence that some of the symptoms are due to central
alterations.

Those few cases that exhibit great difficulty in performing one set of
movements that requires a certain combination of muscles, but are
able to use those same muscles in combination with others with
ease, are difficult of explanation by the peripheral theory of the
disease alone; but less difficulty is encountered if a superexcitability
of the spinal centres is supposed to exist, for here we can imagine
that when all the centres so affected are called into use, and only
then, there will be an undue amount of nervous energy transmitted to
the periphery, and disordered movement be the result.

The explanation offered by those who believe in the peripheral


theory is, that the affected muscle is always imperfect in its action,
but that this imperfection is masked in other combinations by the
action of the healthy muscles, so that it is no longer noticeable.

PROGNOSIS.—The prognosis in these affections varies with the


conditions found and with the previous duration of the disease.

A favorable prognosis may generally be given where the case is an


acute one, and where the disability can be proved to be due to some
one of the peripheral conditions previously mentioned. When the
condition is in the forming stage, when fatigue, stiffness, tremor,
tingling, aching, sense of heat, coldness, or powerlessness are the
only symptoms which exist, the disease is quite amenable to
treatment and a good prognosis may be given; but, unfortunately,
patients are loath to believe that these trivial symptoms, which do not
prevent their work, are precursors of any serious trouble, and
therefore pay but little attention, if any, to them, so that the physician
is seldom consulted during this period.

When positive cramp has made its appearance, it is an evidence of a


more advanced stage of the malady, and the prognosis becomes
less hopeful, although still the symptoms may be greatly
ameliorated, or a complete cure even be effected.

When the cramp has existed for years and is present in many of the
finer acts of co-ordination, the case becomes almost hopeless as far
as cure is concerned; and even though the part is rested, so far as
the disabling occupation is concerned, for months or even years, it
will be found to return upon resumption of the old work. Roth96
considers those cases due to central changes totally incurable.
96 Loc. cit.

When a congestion of the nerves or a well-defined neuritis is


discovered to be the cause of the trouble, the probability of a
favorable termination is rather more hopeful.

Paralysis is to be looked upon as an unfavorable symptom, pointing


as a rule to a late stage of the disease.

It may be stated with positiveness that when the premonitory


symptoms are neglected and constant work persevered in, the case
will go on from bad to worse: periods of amelioration, it is true, may
occur, but cramp usually supervenes, and the affection becomes
gradually progressive as group after group of muscles becomes
implicated, until the part becomes useless for all delicate work.

The probability of the left hand escaping, should it be used to relieve


or replace the right, is slight; and for two reasons: 1st. The same
predisposition which favored the trouble in the right arm still exists;
and, 2d. The proximity of the spinal centres for the two arms is such
that the morbid process may easily be conveyed from one to the
other, as was shown while considering associated movements.
Poore disbelieves in the possibility of such a transfer, and with
Gowers is of the opinion that the liability of the left hand to suffer has
been overestimated.

In my experience, as regards telegraph operators, the majority who


use the left arm soon notice symptoms of the disability in it. Of 43
cases of this form of copodyscinesia which have come under my
observation, in 21 the left arm was implicated; in 12 there was no
such implication, although the arm was used; of the remaining 10, 8
had never tried to telegraph or write with the left arm; 1 had only one
arm, the left; and 1 was doubtful. Throwing out of consideration the
last 10, 21 out of the 33 had this symptom, equivalent to 63.63 per
cent.

PROPHYLAXIS.—The only prophylactic measures are the observance


of the most easy and least fatiguing method of performing the act
which it is feared will bring on the trouble, and the avoidance of
overwork.

Tobacco and alcohol generally act injuriously, and therefore should


be avoided as much as possible by those who are predisposed by
occupation or otherwise to these disorders.

In writing it is advisable to avoid an awkward manner of holding the


pen-holder, which should be of good size; large, moderately soft
pens and paper of good quality should be used.

It is also important that the table or desk upon which the writing is
done should be of a convenient height, with plenty of room for the
arrangement of the paper; otherwise an awkward manner is
inevitable.

As regards the position of the paper, R. Berlin97 (Stuttgart) states


substantially as follows: In writing the head is almost invariably held
so that the line passing through the two eyes, if projected upon the
paper, shall cross at right angles the oblique line of the writing: when
the paper is placed to the right and parallel to the edge of the table,
as generally directed by teachers, the tendency is to twist the spine
and incline the head to the right in order to conform to this rule, and
a cramped position is the result; but by placing the paper in an
oblique position directly in front of the writer—i.e. turned toward the
left—this cramped position is avoided, and the least fatigue, both to
the muscles of the spine and arm, produced. Tight sleeves or
anything that might possibly impede the free play of the muscles or
cause pressure upon the nerves should be discarded.
97 “Physiology of Handwriting,” Von Graefe's Archiv, xxviii. p. 259, review in Ophth.
Review, London, vol. i. No. 14, Dec., 1882, and Jan. 1, 1883.

It is now almost universally conceded that the conjoint movement in


writing—that is, the arm movement for all the small letters, and the
finger movement only to assist in making the long ones—is least
likely to produce fatigue.

It has been stated, and quite generally believed, that the slighter
degrees of scriveners' palsy are relieved by avoiding contact with the
metallic portion of the pen-holder,98 and one of the methods taken to
avoid this contact, especially among telegraph operators, is to slip a
piece of rubber tubing over the pen-holder; this certainly does relieve
the fatigue slightly, but the cause is not the avoidance of contact with
metal or the insulation, etc., but simply that the holder is thus made
larger and softer for the fingers, and thus takes the place of a cork
pen-holder, which for some time has been in use for this purpose.
98 W. Bathurst Woodman, St. Andrews Grad. Ass., 1872-73.

Holding the pen-holder or pencil between the different fingers is


another prophylactic measure, and relieves fatigue considerably; for
instance, when it is placed between the index and middle fingers
there is much less effort at pen-prehension, and the fingers may be
temporarily rested without any effort to hold the pen-holder, as the
friction between the fingers keeps it in position. This method is
frequently adopted by stenographers.

The stylographic and Mackinnon pens, although they destroy much


of the originality in handwriting, are easier to write with than a pen,
as less pressure is needed and no particular angle is required to be
maintained between the point and the paper.

The type-writer is one of the newer inventions destined to come into


extended use for the purpose of relieving the fatigue of writing, which
it does to a marked degree, besides having other merits; and
although one of these is said to be the immunity of its users from
writers' cramp, I venture to assert that cases of this class of trouble
will ensue from its over-use, exactly as they do in piano-playing.99
99 To print this article by this machine would require nearly one hundred and fifty
thousand separate flexions of the fingers.

Thurber's kaligraph, which was invented before the type-writer, has


never come into general use: it works upon the principle of a
pentagraph, and all finger movements are done away with and the
arm movement used exclusively, the motions of writing being much
coarser than ordinary. This instrument is not as well adapted for
prophylaxis in these troubles as it is for use in some deformities of
the hand hindering pen-prehension, as rheumatoid arthritis,
contractions after burns, etc.

In regard to the means to be taken to avoid the occurrence of


telegraphers' cramp, but little can be said, except that if any of the
premonitory symptoms of the neurosis should occur (fatigue, pain,
tingling, numbness, flushing, associated movements, etc.) after
performing the amount of work which previously caused no
discomfort, it should be taken as a warning that the operator is
attempting more work than can be done without detriment, and that a
curtailment of the work is absolutely necessary if he or she wishes to
avoid the disease.

Onimus100 has said that if further investigation proves that the


operators upon the Morse instrument are more liable to suffer than
those using other systems, it should be the duty of those in authority
to abolish that system and adopt some other: he suggests for this
object the Hughes, which is a printing instrument. That the operators
upon the Morse are more liable to suffer than any others is self-
evident after a very slight inquiry, and because of the very general
introduction of that machine. This instrument is far more practical,
takes up less room, and is less likely to get out of order, than any
other yet invented, and no other, it is probable, will be introduced so
generally. The telephone has not diminished the amount of work for
the telegraph operator, but has given rise to a new industry. In all of
the systems the instruments are manipulated at least in part by the
fingers, so that all are liable to cause this disease.
100 Loc. cit.

The telegraph key should be placed some distance from the edge of
the table, so that the forearm may have sufficient support, resting
upon the bellies of the flexor group of muscles, and thus relieve the
shoulder-muscles, which otherwise would have to support the weight
of the arm. Some operators prefer to hold the arm raised from the
table, but this method is more liable to cause fatigue.

Several keys have been invented for the purpose of lessening the
amount of force needed to manipulate them, and to avoid the jarring
caused by the metallic contact; and, although everything that lessens
the amount of labor should be adopted, the movements of
telegraphing must remain the same no matter which key is used.

Tapping upon the key or attempting to operate by flexing the fingers


while the wrist is held still should be avoided.

It is needless to enumerate the other forms of copodyscinesia, as the


same general principles apply to the prophylaxis of all.

TREATMENT.—Rest.—It is an assured fact that as long as the patient


continues without curtailment the amount of work he was performing
when the symptoms of this trouble appeared, treatment will be
negative in its results. Rest in itself is powerless to cure, except in
the very earliest stages of the disease, for many sufferers have
found, to their dismay, that after having given the arm complete rest,
as far as the disabling occupation was concerned, for months at a
time, the symptoms reappear upon returning to the accustomed
work.

During treatment rest is essential, but this need not of necessity be


complete; a curtailment of the work will often be all that is needed in
the lighter cases. This may be effected by using the unaffected arm
for a part of the work at least, but great care must be exercised lest
the symptoms appear on this side also, as the left arm, from want of
use, is wanting in strength and dexterity, and is more liable to be
overtaxed by an amount of work that could be performed without
fatigue by the right; for should this happen the end sought for is
defeated, and the condition of the patient rendered far worse than
before.

In writers' cramp the type-writer, as mentioned under Prophylaxis, is


an important adjuvant in the treatment; unfortunately, it is not
applicable to much of the work done by clerks.

The other means described in the last section are also useful in the
treatment as affording temporary rest to the affected muscles.
Hamilton101 has seen occasional benefit from forced rest by
fastening the hand upon a splint.
101 Loc. cit.

In telegraphing, besides using the left arm, the key may be grasped
in a different manner, or if the operator has been holding his arm
raised from the table, let him rest it upon the latter, or vice versâ.

These remarks only apply to those who are compelled to continue


moderate work during treatment.

Electricity.—The majority of the later writers unite in considering


electricity as one of the most important agents in the treatment of
these affections: the form and the manner in which it is applied are,
however, all important.
The faradic or secondary current has often been tried in undoubted
cases of copodyscinesia, and in the majority has failed. It may be of
great service in the paralytic group, where the affected muscle
shows signs of atrophy and of being temporarily deprived of nerve-
influence; it may be also of service in those apparent cases of the
spastic group due to contracture of the unopposed muscles, but in
the vast majority, where there is a true spasm of the affected
muscles or a tendency in that direction, as evinced by rigidity more
or less pronounced during work, or even where there is only a
quantitative increase to either current (faradic or galvanic), the
application of this form of electricity is contraindicated, as the
muscular contraction is already excessive, and should this extra
stimulus be applied the muscle may be exhausted, for we know how
readily this effect may be produced by a too strong or a too lengthy
application in a perfectly healthy subject.

It is hardly necessary to mention that the manner of applying


electricity so often followed by individuals—viz. holding the
electrodes in the palms of the hands—is unscientific and productive
of no good. The proper method of application in the suitable cases is
to place one electrode of the secondary coil (preferably the negative,
so called) over the muscle that is weakened or over its nerve-point,
and the other in some indifferent position, using a current that is just
strong enough to cause a fair contraction, and employing a slow
interrupter, which breaks the current from one to four times a
second. The application should be short, five to ten good
contractions of each muscle being sufficient.

Buzzard102 has used this current with success in two cases of


impaired writing-power, one of these depending upon a local
paralysis. Zuradelli,103 Meyer,104 and Haupt105 have also seen good
results by this method. Duchenne106 states that he has “not even
seen one success obtained by those who have praised this method
of treatment.” The majority of the later writers coincide with this last
opinion as regards the spastic form at least.
102 “Two Cases of Impaired Writing-power,” Practitioner, Aug., 1872.
103 Quoted by Erb and Poore, loc. cit.

104 Ibid., loc. cit.

105 Der Schreibekrampf mit Rücksicht auf Path. u. Therap., Wiesbaden, 1860, review
in Schmidt's Jahrbucher, Bd. cxv. 3, 136, 1862.

106 Loc. cit.

The galvanic current has of late been considered one of the most
important agents in the treatment of these affections, but there is
considerable variance among authorities as to how it should be
applied. The most efficacious method is the descending current
(anode on the spine and the cathode at the periphery), as this has
been found to be more soothing in its effects than the reverse. The
anode should be placed upon the spine over the cervical cord, and
the cathode in the hand of the affected side or over the affected
muscles or nerves.

A stabile current—i.e. where the poles are not moved about—is to


be preferred to a labile current—i.e. where the poles are moved
constantly—as this is more stimulating than the former; but if a
current of proper strength is used, one that can be plainly felt when
the circuit is made and broken only, the importance of the stabile
over the labile does not obtain.

The treatment should not be prolonged for more than fifteen or


twenty minutes, and may be repeated three times a week or every
other day.

Onimus and Legros107 recommend this mode of treatment, but from


a different pathological standpoint, as they consider the neurosis to
be an excitability of the sensitive nerves of the muscles, and employ
the descending current to allay this.
107 Loc. cit.
All sudden shocks or reversals of the current should be avoided in
the treatment, although this may be necessary in using the galvanic
current for diagnosis.

As the seat of the trouble in many cases is probably in the cervical


cord, it is well that special treatment should be applied to this part,
and for this purpose Althaus108 recommends that the anode be
placed, as previously mentioned, over the cervical cord, and the
cathode in the depression between the angle of the lower jaw and
the sterno-cleido-mastoid muscle, which position corresponds to the
superior cervical ganglion of the sympathetic. The current should be
allowed to flow from three to five minutes at a time; it should be a
mild one, and not be broken or increased or diminished suddenly, as
vertigo may be produced. Both sides should be treated should the
left hand be suffering also. A reversal of this method—i.e. cathode to
spine—does little if any good, according to the same author.
108 Loc. cit.

Poore109 employs the descending stabile current of a strength just


short of producing muscular contraction when the current is broken,
but at the same time he employs rhythmical movements of the
muscles supplied by the nerve upon which the cathode is placed
during the flow of the current.
109 Loc. cit.

A novel mode of applying the galvanic current in scriveners' palsy


has been recommended by Imlach.110 He has an electric desk so
constructed that when the patient makes the movements of writing
the extensors and flexors are alternately galvanized, the muscles
being thus assisted in their movements. While this might be of
service in some cases, it is entirely too complicated for practical use.
He reports one case benefited by its use.
110 Francis Imlach, “Automatic and Other Medical Electricity,” Practitioner, vol. ii. p.
270, 1879.

You might also like