Nothing Special   »   [go: up one dir, main page]

Academia.eduAcademia.edu

A new 3D visualization Java framework based on physics principles

2012, Computer Physics Communications

Computer Physics Communications 183 (2012) 231–244 Contents lists available at ScienceDirect Computer Physics Communications www.elsevier.com/locate/cpc A new 3D visualization Java framework based on physics principles Carlos A. Jara a , Francisco Esquembre b,∗ , Wolfgang Christian c , Francisco A. Candelas a , Fernando Torres a , Sebastián Dormido d a University of Alicante, Spain Departamento de Matemáticas, Universidad de Murcia, Spain c Davidson College, NC, USA d Spanish National Distance University, UNED, Spain b a r t i c l e i n f o a b s t r a c t Article history: Received 9 April 2011 Received in revised form 31 July 2011 Accepted 12 August 2011 Available online 19 August 2011 Keywords: Java Java 3D Three-dimensional visualization Simulations Computer modeling is a powerful instructional tool which can be used to engage students in the design of physical models to describe, explain, and predict physics phenomena. Because implementing a model is difficult for researchers and teachers as well as for students, professionals almost always use discipline-specific code libraries to access a needed functionality in a platform independent manner. For example, although three-dimensional (3D) visualization is of great importance when displaying computer-generated data or showing complex motion, few users are prepared to deal with hardware accelerated video cards to graphically display a visualization. This paper describes a Java-based 3D framework which is based on physics principles. Our framework is defined using abstract Java interfaces that are implemented in the Open Source Physics (OSP) code library. The library contains a Simple 3D implementation that uses only the standard Java distribution and will run on any Java-enabled computer. This paper introduces a new implementation that makes use of Java 3D to improve both the performance and the appearance of implemented models. Examples are presented using both pure Java code and the Easy Java Simulations authoring tool and these examples are available through the ComPADRE OSP digital library.  2011 Elsevier B.V. All rights reserved. 1. Introduction Modeling is a powerful instructional tool which can be used to engage students in the design of physical models to describe, explain, and predict physics phenomena. Although modeling can be used without computers, computer modeling allows students and instructors to study problems that are difficult, expensive, or time consuming, as well as to visualize their results and communicate with others in new ways, thus helping correct weaknesses of traditional instruction by complementing traditional lectures and laboratory work. However, computer modeling can be a daunting task, especially for students. Besides the initial effort of learning a programming language, a student must master a wide range of advanced techniques before being able to create a simulation with a reasonable degree of sophistication. Effective modeling requires numerical algorithms and libraries to create and manage the multithreaded graphical user interfaces and visualizations that are expected and needed for pedagogically effective simulations. To minimize these difficulties, a choice of an appropriate programming language and the provision of simplified and well adapted tools and libraries are required. The Open Source Physics (OSP) project [5] is a synergy of curriculum development, computational physics, and physics education research which uses Java as its preferred software platform and provides several Java frameworks for developing physics simulations. The main goal of this project is to make a large number of Java simulations together with source code available for education using the GNU Open Source model, allowing physics instructors and students to adapt existing simulations, or create new ones, through the use of consistent object-oriented libraries of Java components especially adapted for the requirement of physics modeling and simulation, including numeric, computer graphics, and system (such as multithreading) tools. These packages provide Java objects to build interactive user interfaces, draw 2D and 3D objects, numerically solve ordinary differential equations using different algorithms, and represent data using tables and graphs. For example, the drawing3D package contains a 3D application programming interface (API) based on physics * Corresponding author. E-mail address: fem@um.es (F. Esquembre). 0010-4655/$ – see front matter doi:10.1016/j.cpc.2011.08.007  2011 Elsevier B.V. All rights reserved. 232 C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 principles that enables computational physicists to create sophisticated 3D scenes and animations. The OSP 3D library simplifies 3D concepts to help users in the fast, accurate creation of physics visualizations. This paper describes how the OSP library is used to create 3D visualizations using Elements to represent 3D shapes such as spheres, cylinders, and VRML objects. OSP visualization objects are known as Elements and are defined using abstract interfaces. A 3D sphere, for example, has radius and color properties and may be rendered as a circle with a solid fill color, a collection of polygons, or a Phongshaded surface and these representations require varying amounts of computational effort. The Simple 3D implementation uses only the standard Java distribution and therefore runs on any Java-enabled computer. This implementation breaks an object into multiple polygons and renders them after sorting them along the line of sight. These computations are performed using the same processors that perform the model’s time evolution, and can therefore affect the simulation’s performance. However, modern personal computers include hardware accelerated cards that can shade millions of polygons per second and can significantly improve the appearance and performance of the Simple 3D implementation. But access to this hardware through dedicated software libraries can be platform specific, e.g. Direct X, or difficult for non-specialists, such as the direct use of OpenGL or Java 3D. This paper introduces an OSP 3D implementation, running on top of Java 3D but very much based on physics principles, which simplifies the use of this hardware acceleration for computational physicists. The combined choice of Java and Java 3D constitutes a suitable platform because it is implemented in virtually all platforms and their installation is straightforward. In addition, the object-oriented nature of the language makes it both a simple and a powerful language for programming physics. Finally, Java programs can be run as applets from within web browsers. The new OSP 3D implementation is used by the 3D visualization elements of Easy Java Simulations (EJS) versions 4.3 and later [4]. EJS is an authoring tool designed to further simplify the creation of physics simulations for those with modest programming capabilities. Because EJS integrates a Java compiler with authoring and packaging tools, it is the perfect tool for instructors without much programming experience to implement computational models with real time visualization (including 3D) and interactivity. EJS is also our preferred vehicle to teach beginning computational physics students. EJS is available through the ComPADRE OSP digital library [15], which also features a large number of 3D simulations for physics and astronomy based on EJS and OSP 3D. Some of these simulations have been created by students of a sophomore-level computational physics course at Davidson College [19–21]. In this context and with our OSP 3D library at hand, skilled physics-oriented Java programmers can create 3D visualization scenes programming in pure Java without the need to learn Java 3D concepts or techniques. Other, less skilled programmers can use the simplified structure provided by EJS to create 3D physics simulations using the provided OSP 3D-based view elements. Familiarization with some three-dimensional concepts, such as the camera, projections, lighting, VRML files, and textures (see Section 3), the last three requiring hardware acceleration, is then made easier by means of experimentation and inspection of existing examples. This paper is organized as follows: Section 2 describes briefly the different graphics libraries for 3D computer visualization and discusses the technical background for OSP 3D. Section 3 describes the basic physics principles in which the OSP 3D framework is based and its main components. Section 4 shows some sample code in pure OSP Java programming and Section 5 links present EJS examples and the ComPADRE digital library. Finally, conclusions are given in Section 6. A complete workspace for the Eclipse Java development environment with the source code for the OSP3D framework and the examples discussed in this paper can be downloaded from item 11136 in the OSP Collection, http://www.compadre.org/OSP/items/detail.cfm?ID=11136. 2. Three-dimensional graphic libraries Modeling computer learning environments for physics education started several years ago using programming languages such as Fortran [1] and Pascal [2]. Nowadays, modern and object-oriented languages such as Java [6] or Python [8] are widely preferred because they are easy to learn, very powerful, and can be easily extended with user created or third-party code. The standard libraries of all these programming languages lack three-dimensional graphics capabilities. Hence, particular 3D libraries or even full-featured 3D languages such as Java 3D, OpenGL (Open Graphics Library), Direct3D, JOGL (Java OpenGL), or Visual for Python (VPython) must be used to create realistic 3D physical scenes, usually by accessing hardware acceleration available in modern computer graphic cards. One of the most popular of these 3D libraries for Java is Java 3D. Java 3D is a scene graph-based 3D application programming interface (API) for the Java platform which encapsulates the graphics programming using a high-level, object-oriented concept. Java 3D has multi-platform support, which facilitates the use of the library on cross-platform or distributed environments. Using Java 3D, an expert programmer can create sophisticated 3D scenes and animations, including textures, morphs, and virtual reality models. However, creating even a basic scene in this programming language takes numerous lines of code and shows a computer-science oriented design of the library which seems unnatural to a physics-oriented programmer. For example, the simple static scene shown in the left picture of Fig. 1 requires the programmer to create a BranchGroup whose first child is a TransformGroup which has in turn a Box as child (as well as to understand these programming concepts). Also, apparently simple additions, like being able to see the scene (adding lights), setting color to the box, or displaying the scene in a Java window request a number of very technical lines of code for which the user must consult frequently the documentation to find appropriate methods and values for their arguments. (The complete code spans some 65 lines and is included in the Eclipse workspace for this paper.) More advanced features, like setting a coordinate system or offering interactivity would require a good number of additional, technical lines of code. Although the structural concepts makes Java 3D extremely versatile, scene creation can become tedious and difficult to understand for beginning programmers. The OSP 3D Java library addresses precisely this problem by providing a simple and natural interface to the original Java 3D classes and methods. As an example, Listing 1 shows the OSP 3D code that creates a similar 3D scene with the advantage of having a navigable view where users can use the mouse to rotate the point of view and to zoom in and out. The scene is defined by a DrawingPanel3D object which provides, by default, standard (but user-customizable) elements required by physicists, such as a coordinate system, Cartesian axes, default lights, and a camera whose position can be changed interactively with the mouse to inspect the scene from different points of view. The scene can then host three-dimensional elements, such as a box (given by the ElementBox class), with physical position, size, and orientation, as well as visual clues (such as color) as indicated in their display style. The resulting visualization is displayed in the right picture of Fig. 1. C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 233 Fig. 1. The static 3D scene using Java 3D code (left) cannot be rotated. The dynamic 3D scene using OSP 3D (right) can be rotated and zoomed using the mouse. Listing 1. Creating a dynamic scene using OSP 3D import org . opensourcephysics . drawing3d . ∗ ; import org . opensourcephysics . drawing3d . u t i l s . ∗ ; p u b l i c c l a s s DynamicSceneOSP3D { s t a t i c p u b l i c void main ( S t r i n g [ ] args ) { / / Create a 3D scene with i t s own coordinate system DrawingPanel3D panel3D = new DrawingPanel3D ( ) ; panel3D . setImplementation ( DrawingPanel3D . IMPLEMENTATION_JAVA3D ) ; panel3D . setPreferredMinMax ( − 1, 1 , −1, 1 , −1, 1 ) ; V i s u a l i z a t i o n H i n t s h i n t s = panel3D . g e t V i s u a l i z a t i o n H i n t s ( ) ; h i n t s . setDecorationType ( V i s u a l i z a t i o n H i n t s . DECORATION_CENTERED_AXES ) ; Camera camera = panel3D . getCamera ( ) ; camera . setAzimuthAndAltitude ( 0 . 6 , 0 . 4 ) ; camera . setDistanceToScreen ( 6 ) ; / / Create a Box f o r the scene and customize i t Element box = new ElementBox ( ) ; box . setXYZ ( 0 , 0 , 0 ) ; box . setSizeXYZ ( 1 , 1 , 1 ) ; box . g e t S t y l e ( ) . s e t F i l l C o l o r ( j a v a . awt . Color . RED ) ; / / Add the element to the scene panel3D . addElement ( box ) ; panel3D . update ( ) ; / / update the scene / / Standard J a v a code to d i s p l a y the panel in a window javax . swing . JFrame frame = new javax . swing . JFrame ( " Dynamic Scene with OSP3D " ) ; frame . getContentPane ( ) . add ( panel3D . getComponent ( ) , j a v a . awt . BorderLayout . CENTER ) ; frame . getContentPane ( ) . s e t P r e f e r r e d S i z e (new j a v a . awt . Dimension ( 2 5 6 , 2 5 6 ) ) ; frame . s e t D e f a u l t C l o s e O p e r a t i o n ( javax . swing . JFrame . EXIT_ON_CLOSE ) ; frame . s e t T i t l e ( " Dynamic scene in OSP3D " ) ; frame . pack ( ) ; frame . s e t V i s i b l e ( true ) ; } } The rest of the paper describes the library in more detail and shows more advanced examples of use. There exist similar approaches to that of the Java OSP 3D library, for other programming languages. ROOT [9] is a powerful objectoriented program and library developed in C++, specifically designed for particle physics data analysis. The CERN Program Library (CERNLIB) [11] is a collection of libraries and modules developed in Fortran, specialized on data analysis of high energy. Finally, VPython [3] is a programming package (consisting of Python plus the 3D graphics Visual module) designed to create interactive 3D physics animations developed in Python, even for users with limited programming experience. We chose to create OSP 3D because of our stated preference for the Java programming language, because of the difficulty to use plain Java 3D programming, and because OSP 3D integrates perfectly with the rest of the Open Source Physics library for tasks such as 234 C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 the numerical solution of ordinary differential equations, the implementation of multitasking, and the interactive graphical visualization (animations and plots) of scientific data. 3. Elements of the OSP 3D package The OSP 3D Java package has the following two main constituent Java classes, DrawingPanel3D and Element, together with a number of subclasses of Element that provide different three-dimensional objects. Finally, a collection of utility classes provide finer access to several manipulation and visualization options. The basic procedure to create and animate three-dimensional scenes using OSP 3D is to instantiate a DrawingPanel3D object, add the interface object it provides to a standard Java graphical user interface, and then instantiate and add as many 3D Element objects to the 3D panel as needed. The scene can be customized by adding decorations (such as axes, lights, etc.) or setting the projection camera of the panel at a suitable location. Finally, the scene can be animated by modifying the properties of the 3D elements in run time to change their aspect, position, or orientation, using the panel’s coordinate system. A final call to the update() method of the panel will redraw the scene in its new situation using double-buffering techniques to produce smooth animation. We now describe in more detail the main classes of the package. The Javadoc reference pages for the classes in the package can be found on-line [14]. 3.1. Three-dimensional drawing panels The DrawingPanel3D class represents a three-dimensional scene rendered in a java.awt.Component panel [12]. DrawingPanel3D provides standard affordances for physics programming, such as a coordinate system, a bounding box or axes that can be mapped to the XYZ directions in different ways and with different user-defined scales, and default lighting. The panel has a camera object which projects the scene into a two-dimensional plane which is then mapped to the Component object for rendering to the computer screen. The camera can be instructed to produce a perspective projection of the scene or a planar one using only XY, XZ, or YZ coordinates. The panel provides default interaction gestures to move the camera around and hence project the scene from different points of view. The 3D panel has a default implementation which does not use hardware acceleration, in case the user has not installed Java 3D in the computer. This SIMPLE3D implementation uses the so-called painter’s algorithm [13] which provides a basic rendering for simple (although interesting) scenes and animations. The full power of the library is only obtained when the user installs Java 3D (an add-on to standard Java that must be installed separately in some platforms), and sets the JAVA3D implementation for the panel. Hardware acceleration then provides better intersection of surfaces and hidden-lines removal, as well as additional features such as textures and lighting. The following code snippet shows a typical configuration of a drawing panel 3D and its inception in a Java Swing user interface. The code shows that coordinates may have different ranges in each dimension but axes can be forced to scale to the same size. Also, the standard axes mapping with the Z axis point upwards can be changed to show the Z axis ‘coming out’ of the computer screen. / / import org . opensourcephysics . drawing3d . ∗ ; must be added to the c l a s s code / / Create and customize the panel 3D DrawingPanel3D panel3D = new DrawingPanel3D ( ) ; panel3D . setImplementation ( DrawingPanel3D . IMPLEMENTATION_JAVA3D ) ; panel3D . setPreferredMinMax ( 0 . 0 , 1 . 0 , 0 . 0 , 1 . 0 , 0 . 0 , 2 0 . 0 ) ; panel3D . s e t A x e s S i z e ( 1 , 1 , 1 ) ; panel3D . g e t V i s u a l i z a t i o n H i n t s ( ) . setDecorationType ( V i s u a l i z a t i o n H i n t s . DECORATION_CENTERED_AXES ) ; panel3D . getCamera ( ) . setMapping ( Mapping . MAP_ZYX ) ; / / Add the panel to a Swing JFrame javax . swing . JFrame frame = new javax . swing . JFrame ( " 3D V i s u a l i z a t i o n " ) ; frame . getContentPane ( ) . add ( panel3D . getComponent ( ) , j a v a . awt . BorderLayout . CENTER ) ; 3.2. Three-dimensional elements The Element abstract class is the base class for every three-dimensional object that can appear in a 3D scene. Each element has a number of properties that can be changed programmatically using standard setter and getter Java methods. Some of these properties have physical nature, such as the position and size of the element in space, or its orientation. Others are related to the computer graphics aspects of the element, such as its color, the textures of its surfaces, its visibility, or its interaction capabilities. The position and size of the element are simply given using the panel’s coordinate system. The orientation of an element is modified by changing its built-in transformation object or adding extra spatial transformations to the element. Transformations typically consist of affine matrix or quaternion transformations, that correctly position the element in space. Because of the possible combination of several transformations, together with the fact that elements can be grouped to any level of depth (and the Group element used for this grouping can have its own transformations), it may be difficult for the user to keep track of the final position of the element. To help the user program the physics of the simulation, elements provide methods to convert coordinates expressed in their local (body) reference frame to the global (space) reference of the scene. The Element abstract class has a plethora of subclasses which implement particular 3D objects, from primitive elements such as planes, boxes, spheres, trails, and text, to complex bodies defined by three-dimensional surfaces, vector fields, or VRML (virtual reality modeling language) objects. Each element adds its own configuration methods according to the particular type of 3D object displayed. Table 1 list some of the most popular elements. Fig. 2 shows the simulation of an electromagnetic rail gun [17] and a model of equinox precession [16], both displaying animated 3D scenes created using some of these elements. The following listing illustrates the code typically required to create and manipulate 3D elements, by adding and positioning a red colored hollow cylinder to a previously created 3D panel. C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 235 Table 1 List of some basic three-dimensional primitive elements. Name Description ElementArrow An arrow displaying a vector ElementPlane A piece of plane ElementDisk A planar disk ElementPolygon A three-dimensional polygon. The polygons are created from an array of points ElementImage A three-dimensional image. Images can be rotated and scaled ElementText A three-dimensional text string ElementSpring A three-dimensional coil spring. Springs can be configured with the number of loops ElementBox A three-dimensional parallelepiped. Boxes can be displayed with a tilt in its Z coordinate, thus forming an inclined plane block ElementCone A cone. Cones can be truncated at a specific height and can be open or closed ElementCylinder A cylinder. Cylinders can be closed or open and can be displayed in full or selecting a range for the angle ElementEllipsoid An ellipsoid. Ellipsoids can be displayed in full or selecting a range for the azimuthal and elevation angles ElementSphere A sphere. Spheres can be displayed in full, open or closed at top or bottom, or by specifying a range for the azimuthal and altitude angles ElementSurface A three-dimensional surface ElementCylinder c y l i n d e r = new ElementCylinder ( ) ; c y l i n d e r . setXYZ ( 0 . 5 , 0 . 5 , 1 0 ) ; c y l i n d e r . setSizeXYZ ( 0 . 5 , 0 . 5 , 1 0 ) ; c y l i n d e r . g e t S t y l e ( ) . s e t F i l l C o l o r ( Color . RED ) ; c y l i n d e r . setClosedTop ( f a l s e ) ; c y l i n d e r . setClosedBottom ( f a l s e ) ; panel3D . addElement ( c y l i n d e r ) ; / / Add the element to the scene 3.2.1. Complex geometries The primitive elements alone can be used to visualize many interesting physics phenomena. For situations where more complex geometries must be displayed, or more realistic scenes are desired, the ElementObjectVRML and the ElementObject3DS classes can display (in the JAVA3D implementation only) objects defined in VRML or 3DS files, respectively. These are popular formats for the specification of objects with many facets and colors. The object is loaded from the file and displayed in its full complexity using hardware acceleration, 236 C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 Fig. 2. Three-dimensional simulation of an electromagnetic rail gun (above) and a model of equinox precession. The celestial sphere is three-dimensional and can be rotated to appreciate the relative positions of the elements. Fig. 3. Visualization of a robotic hand (left) using several ElementObjectVRML objects, and of the Columbia space shuttle using a single ElementObject3DS object. but behaves physically as simply as any other OSP 3D element, including moving or rotating in space using the same utility methods. As an example, the left image of Fig. 3 visualizes a robotic hand using VRML description files of its components. Each individually moving part of the hand is visualized using a different ElementObjectVRML so that it can be correctly positioned in space as the hand operates [10]. The right image of the figure was created using the following code: ElementObject3DS s h u t t l e = new ElementObject3DS ( ) ; s h u t t l e . s e t O b j e c t F i l e ( " s r c /demo/ data / S h u t t l e / space_shuttle_columbia . 3 ds " ) ; s h u t t l e . setXYZ ( 0 , 0 , 0 ) ; s h u t t l e . setSizeXYZ ( 1 , 1 , 1 ) ; panel3D . addElement ( s h u t t l e ) ; 3.3. Utility classes Besides these two main classes, the OSP 3D package includes a number of utility classes which help the user customize the scene. DrawingPanel3D uses a number of objects of these classes to provide customization of its visual aspect. The most important of these objects is the Camera. Each element contains an object of the Style utility class to help configure its visual aspect on the screen, including customizing its colors, position relative to their (x, y , z) coordinates, or textures. Some elements use a Resolution object to indicate the number of subdivisions in segments or rectangles required to display their lines or surfaces, respectively. C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 237 Fig. 4. The same 3D scene displayed using different projection modes. The last three are planar modes. Fig. 5. The same 3D object displayed using different axes mapping. The combination of DrawingPanel3D, the many subclasses of Element, and all the configuration methods of these and of their contained objects, makes a very flexible and complete visualization set which can be used to display virtually all physical objects of interest. Finally, the library can be extended (by subclassing), if required, to add new, more sophisticated visualization elements. 3.3.1. The camera The scene in the drawing panel 3D is viewed through a camera that has itself a location in space and points in a direction known as the line of sight. The default line of sight is located on the direction of the X axis and points from the camera towards the center of the scene as determined by the mean of the extremes along each coordinate. This makes it easy to rotate the camera around a physical world that has been created near the center of the coordinate system. Although most users will adjust a 3D view using the mouse, the camera can be moved programmatically using setter and getter methods after obtaining a reference to the camera from the drawing panel, as the following code shows. / / Getting the camera o b j e c t Camera camera = panel3D . getCamera ( ) ; camera . s e t P o s i t i o n ( x , y , z ) ; camera . setAzimuthAndAltitude ( azimuth , a l t i t u d e ) ; The setPosition method sets the camera’s location in space using Cartesian coordinates. The setAzimutAndAltitude method positions the camera using spherical polar coordinates. The azimuth is the rotation angle around the Z axis and the altitude is the angle above or below the XY plane. For further user customization, a CameraInspector class provides a small panel with interactive controls for the camera. The camera object uses a mathematical transformation to map or project a three-dimensional point onto the two-dimensional plane in one of several projection modes, as illustrated in Fig. 4. The drawing panel inserts and places the 3D drawing elements within the scene using a world coordinate system based on the standard XYZ configuration. But the camera object has an option to map or project the 3D scene in different axes configuration of the drawing panel reference, as illustrated in Fig. 5. 3.3.2. Interaction Although OSP 3D elements are, by default, insensitive to user interaction, they are endowed with one or more InteractionTarget objects which can be enabled programmatically. All elements have a position target, located at their spatial position, which can be used to interactively move them in all or some of the axes directions. Some elements, such as arrows, have also a second target at their tip, which allows them to be resized interactively. Elements accept interaction listeners which add user-defined actions to the interaction. The following code snippet illustrates the use of the OSP 3D interaction framework. / / Create a Sphere element ElementSphere sphere = new ElementSphere ( ) ; sphere . setRadius ( 0 . 1 ) ; sphere . setName ( " Main b a l l " ) ; / / Make i t respond to motion in the Z a x i s only I n t e r a c t i o n T a r g e t p o s i t i o n T a r g e t = sphere . g e t I n t e r a c t i o n T a r g e t ( Element . TARGET_POSITION ) ; p o s i t i o n T a r g e t . setEnabled ( I n t e r a c t i o n T a r g e t . ENABLED_Z ) ; 238 C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 Table 2 Types of lights supported by the JAVA3D implementation. Type Description Ambient light Directional light An ambient light shines equally everywhere within its zone of influence and does not possess position or direction. This type of light shines in a particular direction but does not emanate from any particular location. All light rays of a directional light travel in parallel. This is a light that shines from a given point and varies with distance and the orientation of the surface upon which it falls. A spot light shines from a given location and in a given direction. Point light Spot light / / Add a l i s t e n e r to the i n t e r a c t i o n sphere . a d d I n t e r a c t i o n L i s t e n e r (new I n t e r a c t i o n L i s t e n e r ( ) { p u b l i c void interactionPerformed ( I n t e r a c t i o n E v e n t _event ) { Element element = ( Element ) _event . getSource ( ) ; switch ( _event . getID ( ) ) { case I n t e r a c t i o n E v e n t . MOUSE_ENTERED : System . out . p r i n t l n ( " You are now e n t e r i n g element : "+ element . getName ( ) ) ; break ; case I n t e r a c t i o n E v e n t . MOUSE_EXITED : System . out . p r i n t l n ( " You are now e x i t i n g element : "+ element . getName ( ) ) ; break ; case I n t e r a c t i o n E v e n t . MOUSE_DRAGGED : System . out . p r i n t l n ( " Z p o s i t i o n of "+ element . getName ( ) + "="+ element . getZ ( ) ) ; break ; }}}); 3.3.3. Lights Drawing panels 3D can be added one or more light sources to customize the scene illumination, although only the Java 3D implementation will use the lights correctly. Lights are implemented as just one more element and therefore have a position in space and a size which indicates the direction for lights which require it. The ElementLight class provides methods to turn the light on and off, to change the type of light, and to customize its parameters. Table 2 lists the different types of light. The 3D drawing panel has a default illumination consisting of an ambient light and a directional light. These default lights can be switched off using the setDefaultIllumination() method of the panel’s visualization hints. 4. Examples of use In this section we provide examples of use of the OSP 3D framework in combination with the Open Source Physics core library to produce simulations of physical interest. 4.1. The falling ball A simple non-trivial simulation is the motion of a ball which falls in space and bounces off the floor. We solve the second order ordinary differential equation of motion numerically (although a simple closed-form solution is easy to compute), and compute the collision with the floor precisely using an event (or discontinuity in the equations), so that energy is preserved in time. The visualization is made more realistic by adding textures to both the ball and the floor. The code for this application is contained in the BallApplication class of the Eclipse workspace for this paper. We now explain in more detail some parts of the code. The model is described by an ordinary differential equation (ODE) z′′ (t ) = − g, where g is gravity. When the ball hits the floor, we must find the exact moment of the collision and then reverse its vertical velocity. The numerical solution of the ODE and the computation of the collision are computed using an ODEEventSolver object of the org.opensourcephysics.numerics package [7]. For this, our BallApplication class implements the ODE Java interface, by implementing the methods: p u b l i c double [ ] g e t S t a t e ( ) { p u b l i c void getRate ( double [ ] aRate [ 0 ] = a S t a t e [ 1 ] ; / / d aRate [ 1 ] = − g r a v i t y ; / / d aRate [ 2 ] = 1; // d } return s t a t e ; } aState , double [ ] aRate ) { z / dt = vz vz / dt = −g t / dt = 1; where state is a double array with three values for the vertical position of the ball, its vertical velocity, and time. Lines: s o l v e r = new ODEBisectionEventSolver ( t h i s , RK4 . c l a s s ) ; solver . i n i t i a l i z e (0.05); s o l v e r . addEvent (new StateEvent ( ) { p u b l i c double getTolerance ( ) { return 1.0 e −6; } p u b l i c double evaluate ( double [ ] _ s t a t e ) { return _ s t a t e [0] − b a l l . getRadius () − f l o o r . g e t S i z e Z ( ) / 2 ; / / z−r a d i u s above the f l o o r } p u b l i c boolean a c t i o n ( ) { C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 239 Fig. 6. The falling ball application displayed in three different moments and viewed from different camera positions. i f ( s t a t e [ 1 ] < 0 ) s t a t e [ 1 ] = Math . abs ( s t a t e [ 1 ] ) ; return true ; } }); in the class constructor create an ODEEventSolver, initialize it, and add to it a StateEvent that will trigger an action to revert the vertical velocity whenever the ball hits the floor. The rest of the class constructor is devoted to add a 3D visualization. The code shows how naturally the OSP 3D package couples with the physics of the problem. We just create 3D elements to display the ball and the floor, and add them to our panel using our own coordinate system. ball ball ball ball = new ElementSphere ( ) ; . setRadius ( 1 ) ; . g e t S t y l e ( ) . s e t T e x t u r e ( " s r c /demo/ data / b a s k e t b a l l . jpg " , null , 0 , f a l s e ) ; . setZ ( s t a t e [ 0 ] ) ; / / Create a box element f o r the scene and customize i t f l o o r = new ElementBox ( ) ; f l o o r . setXYZ ( 0 , 0 , 0 ) ; f l o o r . setSizeXYZ ( 1 0 , 10 , 1 ) ; f l o o r . g e t S t y l e ( ) . s e t F i l l C o l o r ( j a v a . awt . Color . RED ) ; / / d i v i d e the block in subblocks f l o o r . g e t S t y l e ( ) . s e t R e s o l u t i o n (new R esolution ( 1 , 1 , 1 ) ) ; f l o o r . g e t S t y l e ( ) . s e t T e x t u r e ( " s r c /demo/ data / ceramic . jpg " , n u l l , 0 , f a l s e ) ; / / Create a 3D scene with i t s own coordinate system panel = new DrawingPanel3D ( ) ; panel . setImplementation ( DrawingPanel3D . IMPLEMENTATION_JAVA3D ) ; panel . setPreferredMinMax ( − 5.0 , 5 . 0 , − 5.0 , 5 . 0 , 0 . 0 , 1 0 . 0 ) ; panel . addElement ( b a l l ) ; / / Add the b a l l to the scene panel . addElement ( f l o o r ) ; / / Add the f l o o r to the scene The panel is then added to a Swing frame as in previous examples. Once the model and the visualization have been configured, the simulation is animated by extending the doStep() method of the AbstractAnimation class with the lines s o l v e r . step ( ) ; b a l l . setZ ( s t a t e [ 0 ] ) ; panel . update ( ) ; Some sixty lines of code is all that was needed to create a rather sophisticated simulation which uses both advanced numeric techniques and the full fledged 3D visualization of Fig. 6. 4.2. The torque visualization In our second complete example, we use the OSP 3D package to visualize the angular momentum and torque of a block rotating with constant angular velocity on a fixed shaft. The block is tilted with respect to the shaft to produce an unbalanced configuration that requires a torque to prevent the block from shaking. We use a first group element (bodyGroup) to host the block and two ElementArrow objects that display the angular momentum and the torque. A second group (shaftGroup) hosts the shaft and the body group, which both rotate around the Z axis. Finally, an ElementTrail will display the trajectory of the tip of the angular momentum vector in space. The details of the construction of the scene can be inspected on the code for the constructor of the TorqueVisualization class in the workspace for the paper. The animation step is achieved using the following code: phi += w∗ dt ; / / Rotate the group before c a l l i n g toBodyFrame ( ) 240 C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 Fig. 7. Visualization of the angular momentum of a rotating block and of the torque required to prevent the block from shaking. bodyGroup . setTransformation ( Matrix3DTransformation . r o t a t i o n X ( t i l t ) ) ; shaftGroup . setTransformation ( Matrix3DTransformation . r o t a t i o n Z ( phi ) ) ; / / Compute the angular v e l o c i t y in the body frame double [ ] omega = bodyGroup . toBodyFrame (new double [ ] { 0 , 0 ,w} ) ; / / Compute the angular momentum double [ ] L = new double [ ] { I 1 ∗omega [ 0 ] , I 2 ∗omega [ 1 ] , I 3 ∗omega [ 2 ] } ; / / Compute the torque double N1=omega[ 1 ] ∗ omega [ 2 ] ∗ ( I3−I 2 ) ; double N2=omega[ 0 ] ∗ omega [ 2 ] ∗ ( I1−I 3 ) ; double N3=omega[ 0 ] ∗ omega [ 1 ] ∗ ( I2−I 1 ) ; / / update the v i s u a l i z a t i o n angularMomentum . s e t S i z e ( L ) ; torque . s e t P o s i t i o n ( L ) ; torque . setSizeXYZ ( s c a l e F a c t o r ∗N1 , s c a l e F a c t o r ∗N2 , s c a l e F a c t o r ∗N3 ) ; / / The t r a i l needs space frame c o o r d i n a t e s t r a i l . addPoint ( bodyGroup . toSpaceFrame ( L ) ) ; / / t h i s changes the ar r ay L panel3D . update ( ) ; The angular momentum vector L of a rotating object in the space (laboratory) frame is given by L = I × ω , where I is the inertia tensor and ω is the angular velocity vector. Because the body rotates about a fixed axis in the Z direction, its angular velocity can be written as (0, 0, ω). Although we could transform the inertia tensor from the (non-inertial) body frame into the (inertial) space frame using the rotation transformation that connects the two frames, it is easier to just write the moment of inertia tensor in the frame of the rotating block, where it is constant and diagonal, use the toBodyFrame() method of the body group to transform the angular velocity vector into the body frame, and then perform the simplified matrix multiplication to compute the angular momentum L. Once the angular momentum has been computed, we can obtain its coordinates back in the laboratory frame (needed for the trail that visualizes its trajectory), using the corresponding toSpaceFrame() method. The resulting visualization can be seen in Fig. 7. 5. Easy Java Simulations modeling This section describes a modeling and authoring approach that further reduces the amount of programming when designing, implementing, and distributing 3D computer models. It is based on the integration of the OSP 3D library with the Easy Java Simulations (EJS) program. 5.1. EJS authoring tool Although the OSP 3D package allows scientists and engineers who are familiar with Java to create realistic 3D models, the implementation of a computational modeling-based pedagogy requires a considerable programming effort for teachers and students. Easy Java Simulations is a free open-source modeling and authoring tool that is designed to minimize this effort yet teach good computational techniques. The program sits atop the OSP libraries described in this paper. While some programming knowledge is assumed, EJS users are encouraged to focus on modeling and prototyping rather than on programming user interfaces and data visualizations [6]. The architecture of EJS as shown in Fig. 8 is based on the model-view-control (MVC) design pattern with documentation, where a simulation is composed of: 1. The description which provides an opportunity for the author to document the theory, assumptions, and range of validity of the model. C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 241 Fig. 8. The Tree of Elements in the EJS user interface presents a graphical representation of a 3D view. 2. The computational model which implements the phenomena under study in terms of a. Variables and parameters that describe the state of the system. b. Algorithms, such as ODE solvers, that advance the state of the model. c. Relations among variables, such as the conservation laws in physics, expressed as Java code. 3. The control which defines actions that a user can perform on the simulation. 4. The view which shows a graphical representation (either realistic or schematic) of the model and its data. An EJS View is usually both a view and a control because the graphical user interface displays data and responds to mouse and keyboard actions. Elements are incorporated into an EJS view by dragging and dropping Java interface components, such as buttons and input fields, and visualization Elements, such as spheres and cylinders, from a palette onto a Tree of Elements. For example, the EJS user interface for the torque visualization described Section 4 is shown schematically in the Tree of Elements on the left in Fig. 8. Note the nesting within the tree. A topmost frame contains a 3D drawing panel which contains a group, an arrow, a trail, and text. This group is rotated about the z-axis and contains another group and a 3D cylinder. This innermost group contains additional 3D Elements and is acted on by an x-axis rotation. The entire view for the EJS model, including buttons and input-output fields hidden within collapsed Tree of Elements nodes, was created without programming. Java code (not shown) in the Evolution workpanel advances the state and computes the physics. Clicking the package button on the right-hand toolbar generates the user interface code, connects the user interface to the computation model, compiles the code, and packages everything into a ready-to-run stand alone jar file. The connection between the EJS View and the underlying computational model is one of the key features of EJS. View components, such as buttons or 3D Elements, each have an inspector that can be used to set the properties of that element. Each property can either be a constant value or a Java expression containing model variables. Fig. 9 displays the inspector for the torque arrow in our example. Its color property is set to the constant RED while its position and size are set to model variables. EJS automatically establishes two-way communication between these view properties and model variables so that the view changes as the model evolves and so that the model changes if the user drags an object in the view. Inspectors can also contain code that is invoked in response to user actions such as On Drag. Short code fragments can be entered directly into the inspector’s action fields although it is common to define a longer action as a custom method. 5.2. Physics education The OSP libraries, EJS modeling and authoring tool, ready to run computer models, and associated curricular material are being distributed through the National Science Foundation (NSF) funded ComPADRE National Science Digital Library (NSDL) in the United States. The aim of this library is to reform undergraduate physics and astronomy education by providing simulations and curriculum resources that 242 C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 Fig. 9. EJS inspector of properties for a given view element. Fig. 10. A 3D Gyroscope model. engage teachers and students in physics, astronomy, computation, and computer modeling. For example, item 11136 in the OSP Collection http://www.compadre.org/OSP/items/detail.cfm?ID=11136 is a zip file containing an Eclipse workspace with the Java source code for the pure Java examples in this paper whereas item 10680 in the OSP Collection http://www.compadre.org/OSP/items/detail.cfm?ID=10680 is a computational physics book chapter in PDF format that describes rotational dynamics using EJS 3D models. A ready-to-run jar file and an EJS source-code zip-archive are available as item subdocuments so that the models can easily be adapted and adopted by teachers to their local needs. EJS produces modular self-contained teaching units that are extensible, adaptable, and easily modifiable because the model’s documentation and XML description are packaged within the executable jar file. Right-clicking within the running model allows the user to extract the EJS source code. For example, the Gyroscope model shown in Fig. 10 is used in the computational book chapter and is packaged in the chapter’s multi-model jar file. The gyroscope model simulates the three-dimensional dynamics of a gyroscope under the influence of a gravitational torque acting on the center of mass. The rigid body is shown supported at one end and given an initial angular velocity component about its axis of symmetry and a component perpendicular to its axis of symmetry. Although the model is designed to show the cycloidal motion (precession and nutation) of the gyroscope axle when the initial angular velocity is large, the numerical solution using quaternion-based rotations shows the motion for all initial conditions including zero initial angular momentum. Because this model is useful for teaching mechanics, it has been repackaged as a single-model jar file and cataloged under item 10681 in ComPADRE for use with an article in The Physics Teacher [18]. Despite its current focus on upper-level physics, the ComPADRE OSP Collection fall 2010 usage statistics show an average of 35,000 page views, 9000 visitors, and 7000 downloads per month, and between 2009 and 2010 the usage of the OSP Collection has grown 20%. ComPADRE also supports personal resource collections, personal profiles, discussions, group Web pages, and integrated Wikis. As with any good digital library, items are indexed and are searchable according to document type, author, subject area, and keywords. C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 243 Fig. 11. Robotic simulations developed using EJS. 5.3. Engineering education In some fields of engineering education such as automatic control, robotics and computer vision, experimentation plays an important role. The use of modeling and simulation tools helps students to experiment outside the laboratory with flexible schedules, and for teachers to explain concepts in lectures without having real equipment. With the addition of the new 3D capabilities in EJS, users can develop more realistic virtual applications so that students can experiment with simulated equipment in a way that improves the performance of their practical learning. In the special case of robotics, the use of 3D simulations is particularly interesting because it allows students to easily model the working environment of a robot using virtual reality. The new 3D capabilities of OSP greatly improve the practical experiences of students in the field of engineering education. Fig. 11 shows three robotic simulations developed with EJS. A robotic arm system has a complex physical model and contains a complex geometry. Thus, the simulation of this type of system requires tools with a high support for creating applications with full 3D interactive graphical interfaces. The OSP 3D framework included in EJS has allowed users to develop robotic simulations with a realistic 3D visualization. 6. Conclusions Three-dimensional visualization is not an unnecessary luxury anymore. Many physical phenomena require or are better visualized by an animated, sometimes even interactive, three-dimensional scene. Standard computers already support the hardware-acceleration required for this visualization. However, the programming effort required to use the standard libraries provided by the languages, or by their add-ons, is too demanding for physics oriented programmers, and in particular to teach computational science and modeling to students. The OSP 3D Java framework introduced in this paper is our answer to this problem. The framework consists of a package of Java classes which very much correspond to physical objects, providing a palette of elements which have physical properties of position, size, orientation, and body coordinate system, as well as other computer graphic properties. The programmer constructs the three-dimensional scene by putting together elements in a way very similar to how one would construct it in a laboratory, if only with the flexibility of working with virtual objects. The scene is later animated by programmatically changing the elements’ properties. Interaction with the elements is also built in, and the programmer can implement the response of the program to user interaction using standard language features. The OSP 3D framework is easily integrated with other OSP frameworks, such as the Animation framework, which transparently handles Java threads for the creation of simulations, the Numerics framework, which provides solvers and algorithms for the numerical solution of ordinary differential equations and a collection of three-dimensional transformations suitable for the manipulation of the three-dimensional elements, and the two-dimensional Drawing framework, which provides extensive drawing and plotting capabilities for the creation of 2D visualizations and graphs of scientific data. The combined use of the OSP 3D framework with these other OSP frameworks configures a powerful toolbox for the creation of simulations of scientific and engineering models. For those interested in visualization alone, the OSP 3D framework leverages considerably the programming effort, serving as an excellent entry point for three-dimensional visualization. The extensibility of the package and its Open Source availability make the OSP 3D framework also suitable for the creation of further visualization elements. Finally, the use of the OSP 3D package by the Easy Java Simulations authoring tool makes it possible for professionals or students of science and engineering with modest programming capabilities to create sophisticated physics simulations with minimal effort, making it a perfect choice for teaching computational modeling with three-dimensional visualization. Acknowledgements This work has been partially supported by several research projects in which one or some of the authors participate: the Spanish Ministry of Education and Science projects DPI2008-02647, DPI2007-61068, and MTM2008-03679, a GITE grant of the Technology and Educational Innovation Vicepresident Office of the University of Alicante, the research project 08667/PI/08 of the Fundación Séneca of the Region of Murcia, and the US NSF research project DUE-0937731. References [1] A. Bork, Fortran for Physics, Addison-Wesley, Reading, MA, USA, 1967. [2] E. Redish, J. Wilson, Student programming in the introductory physics course: M.U.P.P.E.T, American Journal of Physics 61 (1993) 222–232. [3] D. Scherer, P. Dubois, B. Sherwood, VPython: 3D interactive scientific graphics for students, Computing in Science and Engineering 2 (5) (2000) 56–62. 244 [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16] [17] [18] [19] [20] [21] C.A. Jara et al. / Computer Physics Communications 183 (2012) 231–244 F. Esquembre, Easy Java simulations: a software tool to create scientific simulations in Java, Computer Physics Communications 156 (2) (2004) 199–204. W. Christian, Open Source Physics: A User’s Guide with Examples, Addison-Wesley, 2007. W. Christian, F. Esquembre, Modeling physics with Easy Java simulations, The Physics Teacher 45 (8) (2007) 475–480. W. Christian, F. Esquembre, Ordinary differential equations, in: CRC Handbook of Dynamic System Modeling, in: CRC Computer and Information Science Series, Chapman and Hall, 2007. R. Chabay, B. Sherwood, Computational physics in the introductory calculus based course, American Journal of Physics 76 (2008) 307–313. I. Antcheva, et al., ROOT — A C++ framework for petabyte data storage, statistical analysis and visualization, Computer Physics Communications 180 (2009) 2499–2512. C.A. Jara, F.A. Candelas, J. Pomares, P. Gil, F. Torres, Ejs+EjsRL, a free Java tool for advanced Robotics simulation and Computer Vision processing, in: Proceedings of 7th International Conference on Informatics in Control, Automation and Robotics, vol. 2, Maderia, Portugal, 2010, pp. 153–160. CERN Program Library, http://cernlib.web.cern.ch/cernlib/. Java Swing application programming interface on-line documentation, http://download.oracle.com/javase/tutorial/uiswing, 2010. J. Foley, A. van Dam, S.K. Feiner, J.F. Hughes, Computer Graphics: Principles and Practice, Addison-Wesley, Reading, MA, USA, 1990, p. 1174, see also http://en.wikipedia. org/wiki/Painter’s_algorithm. OSP 3D Javadoc on-line documentation: http://www.um.es/fem/Javadoc/OSP3D/index.html. Open Source Physics ComPADRE site: http://www.compadre.org/osp. T. Timberlake, Equinox precession model. Computer program at the Open Source Physics ComPADRE site, http://www.compadre.org/OSP/items/detail.cfm?ID=9388, 2010. A.J. Cox, Rail gun model. Computer program at the Open Source Physics ComPADRE site, http://www.compadre.org/osp/items/detail.cfm?ID=8992, 2010. S. Kostov, D. Hammer, ‘It has to go down a little, in order to go around’ — revisiting Feynman on the gyroscope, The Physics Teacher 49 (4) (April 2011) 216. R. Mitchell, Orbiting and colliding galaxies 3-D. Computer program at the Open Source Physics ComPADRE site, http://www.compadre.org/osp/items/detail.cfm?ID=11246, 2011. D. Onken, The long path of photons out of the Sun. Computer program at the Open Source Physics ComPADRE site, http://www.compadre.org/OSP/items/detail. cfm?ID=11349, 2011. J. Pav, Slash-dot system. Computer program at the Open Source Physics ComPADRE site, http://www.compadre.org/osp/items/detail.cfm?ID=11347, 2011.