home *** CD-ROM | disk | FTP | other *** search
/ Ultra Pack / UltraComputing Technology Demos and Tools.iso / java / demo / WireFrame / ThreeD.java < prev   
Encoding:
Java Source  |  1996-04-26  |  11.3 KB  |  442 lines

  1. /*
  2.  * @(#)TreeD.java
  3.  *
  4.  * Copyright (c) 1994-1996 Sun Microsystems, Inc. All Rights Reserved.
  5.  *
  6.  * Permission to use, copy, modify, and distribute this software
  7.  * and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and
  8.  * without fee is hereby granted. 
  9.  * Please refer to the file http://java.sun.com/copy_trademarks.html
  10.  * for further important copyright and trademark information and to
  11.  * http://java.sun.com/licensing.html for further important licensing
  12.  * information for the Java (tm) Technology.
  13.  * 
  14.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  15.  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  16.  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  17.  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  18.  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  19.  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  20.  * 
  21.  * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
  22.  * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
  23.  * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
  24.  * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
  25.  * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
  26.  * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
  27.  * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES").  SUN
  28.  * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
  29.  * HIGH RISK ACTIVITIES.
  30.  */
  31. /* A set of classes to parse, represent and display 3D wireframe models
  32.    represented in Wavefront .obj format. */
  33.  
  34. import java.applet.Applet;
  35. import java.awt.Graphics;
  36. import java.awt.Color;
  37. import java.awt.Event;
  38. import java.io.StreamTokenizer;
  39. import java.io.InputStream;
  40. import java.io.IOException;
  41. import java.net.URL;
  42.  
  43. class FileFormatException extends Exception {
  44.     public FileFormatException(String s) {
  45.     super(s);
  46.     }
  47. }
  48.  
  49. /** The representation of a 3D model */
  50. class Model3D {
  51.     float vert[];
  52.     int tvert[];
  53.     int nvert, maxvert;
  54.     int con[];
  55.     int ncon, maxcon;
  56.     boolean transformed;
  57.     Matrix3D mat;
  58.  
  59.     float xmin, xmax, ymin, ymax, zmin, zmax;
  60.  
  61.     Model3D () {
  62.     mat = new Matrix3D ();
  63.     mat.xrot(20);
  64.     mat.yrot(30);
  65.     }
  66.     /** Create a 3D model by parsing an input stream */
  67.     Model3D (InputStream is) throws IOException, FileFormatException {
  68.     this();
  69.     StreamTokenizer st = new StreamTokenizer(is);
  70.     st.eolIsSignificant(true);
  71.     st.commentChar('#');
  72. scan:
  73.     while (true) {
  74.         switch (st.nextToken()) {
  75.           default:
  76.         break scan;
  77.           case StreamTokenizer.TT_EOL:
  78.         break;
  79.           case StreamTokenizer.TT_WORD:
  80.         if ("v".equals(st.sval)) {
  81.             double x = 0, y = 0, z = 0;
  82.             if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
  83.             x = st.nval;
  84.             if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
  85.                 y = st.nval;
  86.                 if (st.nextToken() == StreamTokenizer.TT_NUMBER)
  87.                 z = st.nval;
  88.             }
  89.             }
  90.             addVert((float) x, (float) y, (float) z);
  91.             while (st.ttype != StreamTokenizer.TT_EOL &&
  92.                 st.ttype != StreamTokenizer.TT_EOF)
  93.             st.nextToken();
  94.         } else if ("f".equals(st.sval) || "fo".equals(st.sval) || "l".equals(st.sval)) {
  95.             int start = -1;
  96.             int prev = -1;
  97.             int n = -1;
  98.             while (true)
  99.             if (st.nextToken() == StreamTokenizer.TT_NUMBER) {
  100.                 n = (int) st.nval;
  101.                 if (prev >= 0)
  102.                 add(prev - 1, n - 1);
  103.                 if (start < 0)
  104.                 start = n;
  105.                 prev = n;
  106.             } else if (st.ttype == '/')
  107.                 st.nextToken();
  108.             else
  109.                 break;
  110.             if (start >= 0)
  111.             add(start - 1, prev - 1);
  112.             if (st.ttype != StreamTokenizer.TT_EOL)
  113.             break scan;
  114.         } else {
  115.             while (st.nextToken() != StreamTokenizer.TT_EOL
  116.                 && st.ttype != StreamTokenizer.TT_EOF);
  117.         }
  118.         }
  119.     }
  120.     is.close();
  121.     if (st.ttype != StreamTokenizer.TT_EOF)
  122.         throw new FileFormatException(st.toString());
  123.     }
  124.  
  125.     /** Add a vertex to this model */
  126.     int addVert(float x, float y, float z) {
  127.     int i = nvert;
  128.     if (i >= maxvert)
  129.         if (vert == null) {
  130.         maxvert = 100;
  131.         vert = new float[maxvert * 3];
  132.         } else {
  133.         maxvert *= 2;
  134.         float nv[] = new float[maxvert * 3];
  135.         System.arraycopy(vert, 0, nv, 0, vert.length);
  136.         vert = nv;
  137.         }
  138.     i *= 3;
  139.     vert[i] = x;
  140.     vert[i + 1] = y;
  141.     vert[i + 2] = z;
  142.     return nvert++;
  143.     }
  144.     /** Add a line from vertex p1 to vertex p2 */
  145.     void add(int p1, int p2) {
  146.     int i = ncon;
  147.     if (p1 >= nvert || p2 >= nvert)
  148.         return;
  149.     if (i >= maxcon)
  150.         if (con == null) {
  151.         maxcon = 100;
  152.         con = new int[maxcon];
  153.         } else {
  154.         maxcon *= 2;
  155.         int nv[] = new int[maxcon];
  156.         System.arraycopy(con, 0, nv, 0, con.length);
  157.         con = nv;
  158.         }
  159.     if (p1 > p2) {
  160.         int t = p1;
  161.         p1 = p2;
  162.         p2 = t;
  163.     }
  164.     con[i] = (p1 << 16) | p2;
  165.     ncon = i + 1;
  166.     }
  167.     /** Transform all the points in this model */
  168.     void transform() {
  169.     if (transformed || nvert <= 0)
  170.         return;
  171.     if (tvert == null || tvert.length < nvert * 3)
  172.         tvert = new int[nvert*3];
  173.     mat.transform(vert, tvert, nvert);
  174.     transformed = true;
  175.     }
  176.  
  177.    /* Quick Sort implementation
  178.     */
  179.    private void quickSort(int a[], int left, int right)
  180.    {
  181.       int leftIndex = left;
  182.       int rightIndex = right;
  183.       int partionElement;
  184.       if ( right > left)
  185.       {
  186.  
  187.          /* Arbitrarily establishing partition element as the midpoint of
  188.           * the array.
  189.           */
  190.          partionElement = a[ ( left + right ) / 2 ];
  191.  
  192.          // loop through the array until indices cross
  193.          while( leftIndex <= rightIndex )
  194.          {
  195.             /* find the first element that is greater than or equal to 
  196.              * the partionElement starting from the leftIndex.
  197.              */
  198.             while( ( leftIndex < right ) && ( a[leftIndex] < partionElement ) )
  199.                ++leftIndex;
  200.  
  201.             /* find an element that is smaller than or equal to 
  202.              * the partionElement starting from the rightIndex.
  203.              */
  204.             while( ( rightIndex > left ) && 
  205.                    ( a[rightIndex] > partionElement ) )
  206.                --rightIndex;
  207.  
  208.             // if the indexes have not crossed, swap
  209.             if( leftIndex <= rightIndex ) 
  210.             {
  211.                swap(a, leftIndex, rightIndex);
  212.                ++leftIndex;
  213.                --rightIndex;
  214.             }
  215.          }
  216.  
  217.          /* If the right index has not reached the left side of array
  218.           * must now sort the left partition.
  219.           */
  220.          if( left < rightIndex )
  221.             quickSort( a, left, rightIndex );
  222.  
  223.          /* If the left index has not reached the right side of array
  224.           * must now sort the right partition.
  225.           */
  226.          if( leftIndex < right )
  227.             quickSort( a, leftIndex, right );
  228.  
  229.       }
  230.    }
  231.  
  232.    private void swap(int a[], int i, int j)
  233.    {
  234.       int T;
  235.       T = a[i]; 
  236.       a[i] = a[j];
  237.       a[j] = T;
  238.    }
  239.  
  240.  
  241.     /** eliminate duplicate lines */
  242.     void compress() {
  243.     int limit = ncon;
  244.     int c[] = con;
  245.     quickSort(con, 0, ncon - 1);
  246.     int d = 0;
  247.     int pp1 = -1;
  248.     for (int i = 0; i < limit; i++) {
  249.         int p1 = c[i];
  250.         if (pp1 != p1) {
  251.         c[d] = p1;
  252.         d++;
  253.         }
  254.         pp1 = p1;
  255.     }
  256.     ncon = d;
  257.     }
  258.  
  259.     static Color gr[];
  260.  
  261.     /** Paint this model to a graphics context.  It uses the matrix associated
  262.     with this model to map from model space to screen space.
  263.     The next version of the browser should have double buffering,
  264.     which will make this *much* nicer */
  265.     void paint(Graphics g) {
  266.     if (vert == null || nvert <= 0)
  267.         return;
  268.     transform();
  269.     if (gr == null) {
  270.         gr = new Color[16];
  271.         for (int i = 0; i < 16; i++) {
  272.         int grey = (int) (170*(1-Math.pow(i/15.0, 2.3)));
  273.         gr[i] = new Color(grey, grey, grey);
  274.         }
  275.     }
  276.     int lg = 0;
  277.     int lim = ncon;
  278.     int c[] = con;
  279.     int v[] = tvert;
  280.     if (lim <= 0 || nvert <= 0)
  281.         return;
  282.     for (int i = 0; i < lim; i++) {
  283.         int T = c[i];
  284.         int p1 = ((T >> 16) & 0xFFFF) * 3;
  285.         int p2 = (T & 0xFFFF) * 3;
  286.         int grey = v[p1 + 2] + v[p2 + 2];
  287.         if (grey < 0)
  288.         grey = 0;
  289.         if (grey > 15)
  290.         grey = 15;
  291.         if (grey != lg) {
  292.         lg = grey;
  293.         g.setColor(gr[grey]);
  294.         }
  295.         g.drawLine(v[p1], v[p1 + 1],
  296.                v[p2], v[p2 + 1]);
  297.     }
  298.     }
  299.  
  300.     /** Find the bounding box of this model */
  301.     void findBB() {
  302.     if (nvert <= 0)
  303.         return;
  304.     float v[] = vert;
  305.     float xmin = v[0], xmax = xmin;
  306.     float ymin = v[1], ymax = ymin;
  307.     float zmin = v[2], zmax = zmin;
  308.     for (int i = nvert * 3; (i -= 3) > 0;) {
  309.         float x = v[i];
  310.         if (x < xmin)
  311.         xmin = x;
  312.         if (x > xmax)
  313.         xmax = x;
  314.         float y = v[i + 1];
  315.         if (y < ymin)
  316.         ymin = y;
  317.         if (y > ymax)
  318.         ymax = y;
  319.         float z = v[i + 2];
  320.         if (z < zmin)
  321.         zmin = z;
  322.         if (z > zmax)
  323.         zmax = z;
  324.     }
  325.     this.xmax = xmax;
  326.     this.xmin = xmin;
  327.     this.ymax = ymax;
  328.     this.ymin = ymin;
  329.     this.zmax = zmax;
  330.     this.zmin = zmin;
  331.     }
  332. }
  333.  
  334. /** An applet to put a 3D model into a page */
  335. public class ThreeD extends Applet implements Runnable {
  336.     Model3D md;
  337.     boolean painted = true;
  338.     float xfac;
  339.     int prevx, prevy;
  340.     float xtheta, ytheta;
  341.     float scalefudge = 1;
  342.     Matrix3D amat = new Matrix3D(), tmat = new Matrix3D();
  343.     String mdname = null;
  344.     String message = null;
  345.  
  346.     public void init() {
  347.     mdname = getParameter("model");
  348.     try {
  349.         scalefudge = Float.valueOf(getParameter("scale")).floatValue();
  350.     }catch(Exception e){};
  351.     amat.yrot(20);
  352.     amat.xrot(20);
  353.     if (mdname == null)
  354.         mdname = "model.obj";
  355.     resize(size().width <= 20 ? 400 : size().width,
  356.            size().height <= 20 ? 400 : size().height);
  357.     }
  358.     public void run() {
  359.     InputStream is = null;
  360.     try {
  361.         Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
  362.         is = new URL(getDocumentBase(), mdname).openStream();
  363.         Model3D m = new Model3D (is);
  364.         md = m;
  365.         m.findBB();
  366.         m.compress();
  367.         float xw = m.xmax - m.xmin;
  368.         float yw = m.ymax - m.ymin;
  369.         float zw = m.zmax - m.zmin;
  370.         if (yw > xw)
  371.         xw = yw;
  372.         if (zw > xw)
  373.         xw = zw;
  374.         float f1 = size().width / xw;
  375.         float f2 = size().height / xw;
  376.         xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge;
  377.     } catch(Exception e) {
  378.         md = null;
  379.         message = e.toString();
  380.     }
  381.     try {
  382.         if (is != null)
  383.         is.close();
  384.     } catch(Exception e) {
  385.     }
  386.     repaint();
  387.     }
  388.     public void start() {
  389.     if (md == null && message == null)
  390.         new Thread(this).start();
  391.     }
  392.     public void stop() {
  393.     }
  394.     public boolean mouseDown(Event e, int x, int y) {
  395.     prevx = x;
  396.     prevy = y;
  397.     return true;
  398.     }
  399.     public boolean mouseDrag(Event e, int x, int y) {
  400.     tmat.unit();
  401.     float xtheta = (prevy - y) * 360.0f / size().width;
  402.     float ytheta = (x - prevx) * 360.0f / size().height;
  403.     tmat.xrot(xtheta);
  404.     tmat.yrot(ytheta);
  405.     amat.mult(tmat);
  406.     if (painted) {
  407.         painted = false;
  408.         repaint();
  409.     }
  410.     prevx = x;
  411.     prevy = y;
  412.     return true;
  413.     }
  414.     public void paint(Graphics g) {
  415.     if (md != null) {
  416.         md.mat.unit();
  417.         md.mat.translate(-(md.xmin + md.xmax) / 2,
  418.                  -(md.ymin + md.ymax) / 2,
  419.                  -(md.zmin + md.zmax) / 2);
  420.         md.mat.mult(amat);
  421. //        md.mat.scale(xfac, -xfac, 8 * xfac / size().width);
  422.         md.mat.scale(xfac, -xfac, 16 * xfac / size().width);
  423.         md.mat.translate(size().width / 2, size().height / 2, 8);
  424.         md.transformed = false;
  425.         md.paint(g);
  426.         setPainted();
  427.     } else if (message != null) {
  428.         g.drawString("Error in model:", 3, 20);
  429.         g.drawString(message, 10, 40);
  430.     }
  431.     }
  432.     private synchronized void setPainted() {
  433.     painted = true;
  434.     notifyAll();
  435.     }
  436. //    private synchronized void waitPainted() {
  437. //    while (!painted)
  438. //        wait();
  439. //    painted = false;
  440. //    }
  441. }
  442.