package kartoMNT.visu3d;
import java.io.*;
import java.applet.Applet;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.media.j3d.*;
import javax.media.j3d.Raster;
import javax.media.j3d.Canvas3D;
import javax.vecmath.*;
import com.sun.j3d.utils.applet.JMainFrame;
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.image.TextureLoader;
import com.sun.image.codec.jpeg.*;
import kartoMNT.*;
import kartoMNT.visu3d.gif.*;
/**
* <P>
*
* kartoMNT V2 <BR>
* Application de visualisation de MNT en 3D de kartoMNT<BR>
* <BR>
* Ce travail est inspir� de celui de Matti Kannala (matti.kannala@hut.fi) <BR>
* de l'Helsinki University of Technology<BR>
* <BR>
* R�alis� sous la direction de LINGRAND Diane et FERNANDES Gilbert <BR>
* Ecole Sup�rieure en Sciences Informatiques de Sophia-Antipolis (FRANCE)
* </P>
*
* @author DERHI Roland
*
*/
public class Visu3DkartoMNT extends JApplet implements ChangeListener, ActionListener, ItemListener
{
/** URL de la texture de background */
private java.net.URL backGroundUrl = null;
/** L'univers o� est affich� le monde */
private SimpleUniverse universe = null;
/** Taille du monde */
private double worldSize;
/** Le "HeightMap" repr�sentant le MNT */
private LandScape L = null;
/** Bouton de Capture d'�cran */
private JButton bCaptEcran;
/** Bouton de Capture s�quentielle d'images */
private JButton bSeq;
/** Bouton de Capture de film */
private JButton bFilm;
/** Bouton Stop */
private JButton bStop;
/** Bouton Haut */
private JButton bHaut;
/** Bouton Remise � l'horizontale */
private JButton bHor;
/** Bouton Roul�-Boul� Gauche */
private JButton bRG;
/** Bouton Avant */
private JButton bAvant;
/** Bouton Roul�-Boul� Gauche */
private JButton bRD;
/** Bouton Gauche */
private JButton bGauche;
/** Bouton Arri�re */
private JButton bArriere;
/** Bouton Droite */
private JButton bDroite;
/** Bouton Bas */
private JButton bBas;
/** Bouton Recentrage sur le MNT */
private JButton bRec;
/** Bouton mode Fil de Fer/Textur� */
private JButton bMode;
/** Bouton Rotation autour du MNT */
private JButton bRot;
/** Bouton de titre */
private JButton titre;
/** JTextField de coordonn�e en X */
private JTextField jTFcoordX;
/** JTextField de coordonn�e en Y */
private JTextField jTFcoordY;
/** JTextField de coordonn�e en Z */
private JTextField jTFcoordZ;
/** Bouton de changement de position */
private JButton bChPos;
/** JTextField d'angle d'azimut */
private JTextField jTFangA;
/** JTextField d'angle de pente */
private JTextField jTFangP;
/** JTextField d'angle de roulement */
private JTextField jTFangR;
/** Bouton de changement de direction du regard */
private JButton bChDir;
/** CheckBox du cockpit (croix centrale et rep�re) */
private JCheckBox jcbCC;
/** CheckBox du Socle du MNT */
private JCheckBox jcbS ;
/** slider de la qualit� du MNT */
private JSlider quality;
/** slider de changement de la vitesse de mouvement avant/arri�re */
private JSlider sliderMove;
/** slider de changement de la vitesse de mouvement lat�ral */
private JSlider sliderStrafe;
/** slider de changement de la vitesse de roulis */
private JSlider sliderRoll;
/** slider de changement de la vitesse de rotation */
private JSlider sliderRotation;
/** JPanel o� est affich� la visualisation 3D du MNT */
private JPanel panelCanvas;
/** Le canvas3D d'affichage */
private Canvas3D canvas;
/** Le canvas3D off-screen */
private OffScreenCanvas3D offCanvas;
/** Configuration des canvas3D */
private GraphicsConfiguration gc1;
/** Interface de Navigation de la cam�ra */
private Navigation navigation;
/** Classe permettant de faire des capture d'�cran */
//private Robot robot = null;
/** Classe permattant d'enregistrer des gifs anim�s */
private AnimatedGifEncoder gifEnc = new AnimatedGifEncoder();
/** Classe permettant de sauvegarder en JPEG */
private JPEGImageEncoder jpe=null;
/** Compteur de capture d'�cran */
private static int capture=0;
/** Thread de capture de s�quences d'images et de film */
private Sequenceur seq;
/** JFileChooser de capture */
private JFileChooser fcCapt= new JFileChooser(Options.getDirWrite());
/** BranchGroup contenant l'ensemble de la sc�ne */
private BranchGroup contentBranchGroup ;
/** Le MNT � visualiser en 3D */
private MNT landMNT =null;
/** Le document Karto courant */
private DocumentKarto docKarto;
/** BranchGroup du Socle du MNT */
private BranchGroup socle;
/** TransformGroup du cockpit (croix centrale verte) */
private BranchGroup cock;
/** Texture du MNT */
private Texture earth = null;
/** Thread r�actualisatrice de l'affichage des positions et des rotations */
private Reactualisateur reactualisateur=null;
/**
* M�thode d'initialisation de l'applet
**/
public void init()
{
// on d�marre le dialog
DialogVisu3DkartoMNT dKMNT = new DialogVisu3DkartoMNT(this,landMNT,docKarto);
// on attend que l'utilisateur quitte le dialog
while((!dKMNT.continu) && (!dKMNT.termine)){
try{
Thread.sleep(1000);
}
catch(InterruptedException e){}
}
//si l'utilisateur a cliqu� sur Annuler, on arr�te tout
if (dKMNT.termine){
dKMNT.dispose();
SwingUtilities.windowForComponent(this).dispose();
stop();
return;
}
dKMNT.dispose();
// initialisation de fcCapt
fcCapt.setAcceptAllFileFilterUsed(false);
ExampleFileFilter filterImg = new ExampleFileFilter();
filterImg.addExtension("jpg");
filterImg.setDescription(ResourceManager.get("jpgImage"));
fcCapt.addChoosableFileFilter(filterImg);
ExampleFileFilter filterImg2 = new ExampleFileFilter();
filterImg2.addExtension("gif");
filterImg2.setDescription(ResourceManager.get("gifImage"));
fcCapt.addChoosableFileFilter(filterImg2);
// on cr�e l'interface
Container contentPane=getContentPane();
contentPane.setLayout(new BorderLayout());
// panel de visualisation
panelCanvas = new JPanel();
panelCanvas.setLayout(new BorderLayout());
TitledBorder title3 = BorderFactory.createTitledBorder(ResourceManager.get("visuTitle"));
panelCanvas.setBorder(title3);
canvas = createCanvas();
panelCanvas.add("Center", canvas);
contentPane.add("Center", panelCanvas);
// construction de l'univers Java3D
universe = new SimpleUniverse(canvas);
// create an off Screen Buffer
offCanvas = new OffScreenCanvas3D(gc1, true);
Screen3D sOn = canvas.getScreen3D();
Screen3D sOff = offCanvas.getScreen3D();
sOff.setSize(new Dimension(Variables.qualCaptW,Variables.qualCaptH));
sOff.setPhysicalScreenWidth(sOn.getPhysicalScreenWidth());
sOff.setPhysicalScreenHeight(sOn.getPhysicalScreenHeight());
// attach the same view to the offscreen canvas
universe.getViewer().getView().addCanvas3D(offCanvas);
//myView.attachViewPlatform( myPlatform );
contentBranchGroup = new BranchGroup();
contentBranchGroup.setCapability(BranchGroup.ALLOW_CHILDREN_READ);
contentBranchGroup.setCapability(BranchGroup.ALLOW_CHILDREN_WRITE);
contentBranchGroup.setCapability(BranchGroup.ALLOW_CHILDREN_EXTEND);
// rajout du Terrain 3D � l'univers
addLandscape(contentBranchGroup);
// mettre � l'�chelle si l'unit� de calibration en x,y est diff�rente du z ( km et m)
//GFEGFE Tests
/* if (landMNT != null){
System.out.println("Anciens coeff : X ="+Variables.gridScaleX+" Y="+Variables.gridScaleY);
float hauteur = landMNT.getAltitudeMax();
float coeff=1;
while ( ((hauteur/coeff) > (landMNT.getX2()-landMNT.getX1()) )&&
((hauteur/coeff) > (landMNT.getY2()-landMNT.getY1()) ) ){
coeff*=10;
}
Variables.gridScaleX*= coeff;
Variables.gridScaleY*= coeff;
System.out.println("Nouveaux coeff : X ="+Variables.gridScaleX+" Y="+Variables.gridScaleY);
}
*/ // calcul de la taille max du monde
worldSize=Math.max(L.getXSize()*Variables.gridScaleX,L.getYSize()*Variables.gridScaleY)*10;
// clipping en z
if (Variables.paramAuto){
universe.getViewer().getView().setBackClipDistance(worldSize);
}
else{
universe.getViewer().getView().setBackClipDistance(Variables.zClip);
}
// rajout du fond
addBackGround(contentBranchGroup, backGroundUrl);
// rajout des lumi�res
addLights(contentBranchGroup);
//addFog(contentBranchGroup);
TransformGroup cockTG = addCockpit(contentBranchGroup);
TransformGroup repTG = addRepere(cockTG);
// rajout du socle du Landscape
addSocle(contentBranchGroup);
// rajout de la navigation de la cam�ra
addNavigation(contentBranchGroup, cockTG, repTG,
new Vector3d((L.getXSize()-1)*Variables.gridScaleX, L.getHeight(L.getXSize()-1,0)*Variables.zScale+400, 0)
, 3.14159,
new Vector2d(-worldSize, worldSize), new Vector2d(-worldSize, worldSize));
// compilation du monde
contentBranchGroup.compile();
universe.addBranchGraph(contentBranchGroup);
// panel de commande
JPanel panelGeneral = new JPanel();
panelGeneral.setSize(200,800);
panelGeneral.setLayout(new BoxLayout(panelGeneral,BoxLayout.Y_AXIS));
// screen capture
JPanel panelCapt=new JPanel(new FlowLayout());
TitledBorder title4 = BorderFactory.createTitledBorder(ResourceManager.get("captTitle"));
panelCapt.setBorder(title4);
bCaptEcran = new JButton(new ImageIcon("icones/photo.gif"));
bCaptEcran.addActionListener(this);
bCaptEcran.setToolTipText(ResourceManager.get("captHelp"));
bCaptEcran.setSize(40,40);
bSeq = new JButton(ResourceManager.get("start"),new ImageIcon("icones/sequence.gif"));
bSeq.addActionListener(this);
bSeq.setHorizontalTextPosition(SwingConstants.CENTER);
bSeq.setVerticalTextPosition(SwingConstants.BOTTOM);
bSeq.setToolTipText(ResourceManager.get("captSeqHelp"));
bSeq.setSize(40,40);
bFilm = new JButton(ResourceManager.get("start"),new ImageIcon("icones/film.gif"));
bFilm.addActionListener(this);
bFilm.setHorizontalTextPosition(SwingConstants.CENTER);
bFilm.setVerticalTextPosition(SwingConstants.BOTTOM);
bFilm.setToolTipText(ResourceManager.get("captFilm"));
bFilm.setSize(40,40);
panelCapt.add(bCaptEcran);
panelCapt.add(bSeq);
panelCapt.add(bFilm);
// panel commande
JPanel panelCommande = new JPanel();
panelCommande.setLayout(new BoxLayout(panelCommande,BoxLayout.Y_AXIS));
// position
JPanel panelPos=new JPanel();
panelPos.setLayout(new BoxLayout(panelPos,BoxLayout.Y_AXIS));
TitledBorder title5 = BorderFactory.createTitledBorder(ResourceManager.get("posHelp"));
panelPos.setBorder(title5);
JPanel jp1 = new JPanel(new FlowLayout());
JLabel jLX = new JLabel("X");
jTFcoordX = new JTextField(5);
jTFcoordX.setEditable(false);
JLabel jLY = new JLabel("Y");
jTFcoordY = new JTextField(5);
jTFcoordY.setEditable(false);
JLabel jLZ = new JLabel("Z");
jTFcoordZ = new JTextField(5);
jTFcoordZ.setEditable(false);
JPanel jp2 = new JPanel(new FlowLayout());
bChPos = new JButton(ResourceManager.get("posChange"));
bChPos.addActionListener(this);
jp1.add(jLX);
jp1.add(jTFcoordX);
jp1.add(jLY);
jp1.add(jTFcoordY);
jp1.add(jLZ);
jp1.add(jTFcoordZ);
jp2.add(bChPos);
panelPos.add(jp1);
panelPos.add(jp2);
// direction de regard
JPanel panelDir=new JPanel();
panelDir.setLayout(new BoxLayout(panelDir,BoxLayout.Y_AXIS));
TitledBorder title6 = BorderFactory.createTitledBorder(ResourceManager.get("dirRot"));
panelDir.setBorder(title6);
JPanel jp10 = new JPanel(new FlowLayout());
JLabel jLA = new JLabel("A");
jTFangA = new JTextField(5);
jTFangA.setEditable(false);
JLabel jLP = new JLabel("P");
jTFangP = new JTextField(5);
jTFangP.setEditable(false);
JLabel jLR = new JLabel("R");
jTFangR = new JTextField(5);
jTFangR.setEditable(false);
JPanel jp20 = new JPanel(new FlowLayout());
bChDir = new JButton(ResourceManager.get("rotChange"));
bChDir.addActionListener(this);
jp10.add(jLA);
jp10.add(jTFangA);
jp10.add(jLP);
jp10.add(jTFangP);
jp10.add(jLR);
jp10.add(jTFangR);
jp20.add(bChDir);
panelDir.add(jp10);
panelDir.add(jp20);
// boutons
JPanel boutonsDir = new JPanel();
boutonsDir.setLayout(new GridLayout(4,3));
TitledBorder title2 = BorderFactory.createTitledBorder(ResourceManager.get("nav"));
// panelGeneral.setIconImage(Toolkit.getDefaultToolkit().getImage("icones/kartoicon.gif"));
boutonsDir.setBorder(title2);
bStop=new JButton(new ImageIcon("icones/stop.gif"));
bStop.addActionListener(this);
bStop.setToolTipText(ResourceManager.get("stopHelp"));
bStop.setSize(40,40);
bHaut=new JButton(new ImageIcon("icones/haut.gif"));
bHaut.addActionListener(this);
bHaut.setToolTipText(ResourceManager.get("upHelp"));
bHaut.setSize(40,40);
bHor=new JButton(new ImageIcon("icones/horizon.gif"));
bHor.addActionListener(this);
bHor.setToolTipText(ResourceManager.get("horHelp"));
bHor.setSize(40,40);
bRG=new JButton(new ImageIcon("icones/quarttourgauche.gif"));
bRG.addActionListener(this);
bRG.setToolTipText(ResourceManager.get("leftRollHelp"));
bRG.setSize(40,40);
bAvant=new JButton(new ImageIcon("icones/avant.gif"));
bAvant.addActionListener(this);
bAvant.setToolTipText(ResourceManager.get("forwHelp"));
bAvant.setSize(40,40);
bRD=new JButton(new ImageIcon("icones/quarttourdroite.gif"));
bRD.addActionListener(this);
bRD.setToolTipText(ResourceManager.get("RightRollHelp"));
bRD.setSize(40,40);
bGauche=new JButton(new ImageIcon("icones/gauche.gif"));
bGauche.addActionListener(this);
bGauche.setToolTipText(ResourceManager.get("leftPas"));
bGauche.setSize(40,40);
bArriere=new JButton(new ImageIcon("icones/arriere.gif"));
bArriere.addActionListener(this);
bArriere.setToolTipText(ResourceManager.get("backHelp"));
bArriere.setSize(40,40);
bDroite=new JButton(new ImageIcon("icones/droite.gif"));
bDroite.addActionListener(this);
bDroite.setToolTipText(ResourceManager.get("rightPas"));
bDroite.setSize(40,40);
bRec=new JButton(new ImageIcon("icones/recentre.gif"));
bRec.setToolTipText(ResourceManager.get("centerHelp"));
bRec.addActionListener(this);
bRec.setSize(40,40);
bBas=new JButton(new ImageIcon("icones/bas.gif"));
bBas.addActionListener(this);
bBas.setToolTipText(ResourceManager.get("downHelp"));
bBas.setSize(40,40);
bRot=new JButton(new ImageIcon("icones/rotation.gif"));
bRot.addActionListener(this);
bRot.setToolTipText(ResourceManager.get("rotHelp"));
bRot.setActionCommand("Activ�");
bRot.setSize(40,40);
boutonsDir.add(bStop);
boutonsDir.add(bHaut);
boutonsDir.add(bHor);
boutonsDir.add(bRG);
boutonsDir.add(bAvant);
boutonsDir.add(bRD);
boutonsDir.add(bGauche);
boutonsDir.add(bArriere);
boutonsDir.add(bDroite);
boutonsDir.add(bRec);
boutonsDir.add(bBas);
boutonsDir.add(bRot);
boutonsDir.setSize(160,120);
// panel MNT
JPanel panelMNT = new JPanel();
panelMNT.setLayout(new BoxLayout(panelMNT,BoxLayout.Y_AXIS));
// Slider qualite
JPanel panelSlider=new JPanel();
TitledBorder title1 = BorderFactory.createTitledBorder(ResourceManager.get("quality"));
panelSlider.setBorder(title1);
quality = new JSlider(JSlider.HORIZONTAL, 1, 10, 5);
quality.addChangeListener(this);
quality.setMajorTickSpacing(1);
quality.setMinorTickSpacing(1);
quality.setPaintTicks(true);
quality.setPaintLabels(true);
quality.setSnapToTicks(true);
quality.setToolTipText(ResourceManager.get("qualHelp"));
panelSlider.add(quality);
JPanel panelRendu=new JPanel();
TitledBorder titleRendu = BorderFactory.createTitledBorder(ResourceManager.get("modeR"));
panelRendu.setBorder(titleRendu);
JLabel labR=new JLabel(ResourceManager.get("TexorFdF"));
panelRendu.add(labR);
bMode=new JButton(new ImageIcon("icones/fildefer.gif"));
bMode.addActionListener(this);
bMode.setToolTipText(ResourceManager.get("FdFmod"));
bMode.setActionCommand("Texture");
bMode.setSize(40,40);
panelRendu.add(bMode);
JPanel panelAide=new JPanel();
TitledBorder titleAide = BorderFactory.createTitledBorder(ResourceManager.get("help"));
panelAide.setBorder(titleAide);
jcbCC = new JCheckBox(ResourceManager.get("cockpit"));
jcbCC.setMnemonic(KeyEvent.VK_X);
jcbCC.setSelected(true);
jcbCC.addItemListener(this);
panelAide.add(jcbCC);
jcbS = new JCheckBox(ResourceManager.get("base"));
jcbS.setMnemonic(KeyEvent.VK_S);
jcbS.setSelected(true);
jcbS.addItemListener(this);
panelAide.add(jcbS);
JPanel panelTitre = new JPanel(new FlowLayout(FlowLayout.CENTER));
titre = new JButton(new ImageIcon("icones/kartoMNT.gif"));
titre.addActionListener(this);
panelTitre.add(titre);
JPanel panelVitesse=new JPanel();
panelVitesse.setLayout(new BoxLayout(panelVitesse,BoxLayout.Y_AXIS));
TitledBorder titlev1 = BorderFactory.createTitledBorder(ResourceManager.get("vitTitle"));
panelVitesse.setBorder(titlev1);
sliderMove = new JSlider(JSlider.HORIZONTAL,
0, 20, (int)Navigation.MAX_MOVE_SPEED);
sliderMove.addChangeListener(this);
sliderMove.setMajorTickSpacing(5);
sliderMove.setMinorTickSpacing(1);
sliderMove.setPaintTicks(true);
sliderMove.setPaintLabels(true);
sliderMove.setBorder(BorderFactory.createTitledBorder(ResourceManager.get("movAATitle")));
sliderMove.setToolTipText(ResourceManager.get("movAAHelp"));
panelVitesse.add(sliderMove);
sliderStrafe = new JSlider(JSlider.HORIZONTAL,
0, 20, (int)Navigation.MAX_STRAFE_SPEED);
sliderStrafe.addChangeListener(this);
sliderStrafe.setMajorTickSpacing(5);
sliderStrafe.setMinorTickSpacing(1);
sliderStrafe.setPaintTicks(true);
sliderStrafe.setPaintLabels(true);
sliderStrafe.setBorder(BorderFactory.createTitledBorder(ResourceManager.get("movStTitle")));
sliderStrafe.setToolTipText(ResourceManager.get("movStHelp"));
panelVitesse.add(sliderStrafe);
sliderRoll = new JSlider(JSlider.HORIZONTAL,
0, 20, (int)(Navigation.MAX_ROLL_SPEED*200));
sliderRoll.addChangeListener(this);
sliderRoll.setMajorTickSpacing(5);
sliderRoll.setMinorTickSpacing(1);
sliderRoll.setPaintTicks(true);
sliderRoll.setPaintLabels(true);
sliderRoll.setBorder(BorderFactory.createTitledBorder(ResourceManager.get("movRoTitle")));
sliderRoll.setToolTipText(ResourceManager.get("movRoHelp"));
panelVitesse.add(sliderRoll);
sliderRotation = new JSlider(JSlider.HORIZONTAL,
0, 20, (int)(Navigation.MAX_ROTATION_SPEED*200));
sliderRotation.addChangeListener(this);
sliderRotation.setMajorTickSpacing(5);
sliderRotation.setMinorTickSpacing(1);
sliderRotation.setPaintTicks(true);
sliderRotation.setPaintLabels(true);
sliderRotation.setBorder(BorderFactory.createTitledBorder(ResourceManager.get("movRotTitle")));
sliderRotation.setToolTipText(ResourceManager.get("movRotHelp"));
panelVitesse.add(sliderRotation);
panelCommande.add(panelPos);
panelCommande.add(panelDir);
panelCommande.add(boutonsDir);
panelMNT.add(panelSlider);
panelMNT.add(panelRendu);
panelMNT.add(panelAide);
// tabbed pane
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab(ResourceManager.get("nav"), null, panelCommande, ResourceManager.get("navHelp"));
tabbedPane.setSelectedIndex(0);
tabbedPane.addTab(ResourceManager.get("mnt"), null, panelMNT, ResourceManager.get("mntG"));
tabbedPane.addTab(ResourceManager.get("tabVitTitle"),null,panelVitesse,ResourceManager.get("tabVitHelp"));
panelGeneral.add(panelTitre);
panelGeneral.add(panelCapt);
panelGeneral.add(tabbedPane);
contentPane.add("East", panelGeneral);
setSize(800,600);
// robot de capture d'�cran
// try {
// robot = new Robot();
// } catch (AWTException awe) {
// throw new RuntimeException(ResourceManager.get("captNotSup"));
// }
// catch (SecurityException awe) {
// throw new RuntimeException(ResourceManager.get("captNotSup"));
// }
// thread de r�actualisation de la position
reactualisateur = new Reactualisateur(this,jTFcoordX,jTFcoordY,jTFcoordZ,jTFangA,jTFangP,jTFangR);
reactualisateur.start();
// r�pertoire de capture
File dir = new File("./capture/");
if (dir == null) {
System.err.println("Le r�pertoire ./capture/ n'a pas �t� trouv�");
}
else{
// on v�rifie si des captures ont d�j� �t� r�alis�. On peut ainsi initialiser
// capture afin de ne pas �craser les captures pr�c�dentes
try{
String[] list = dir.list();
for (int i = 0; i < list.length; i++) {
if (list[i].indexOf('$') == -1 && (list[i].endsWith(".gif")||list[i].endsWith(".jpg"))) {
String nomImage = list[i].substring(0,list[i].indexOf('.'));
String numero = nomImage.substring(4);
int nombre;
try{
nombre = Integer.parseInt(numero);
if (nombre>capture){
capture=nombre;
}
}
catch(NumberFormatException e){}
}
}
}
catch(NullPointerException e){}
}
}
/**
* Classe Interne <BR>
* Thread de r�actualisation de la position de la cam�ra
**/
class Reactualisateur extends Thread{
/** le Terrain 3D */
Visu3DkartoMNT d;
/** JTextField coordonn�e en X */
JTextField jTFX;
/** JTextField coordonn�e en Y */
JTextField jTFY;
/** JTextField coordonn�e en Z */
JTextField jTFZ;
/** JTextField d'angle d'azimut */
private JTextField jTFA;
/** JTextField d'angle de pente */
private JTextField jTFP;
/** JTextField d'angle de roulement */
private JTextField jTFR;
private boolean continu=true;
/**
* Constructeur
* @param d le Terrain 3D
* @param jTFX JTextField coordonn�e en X
* @param jTFY JTextField coordonn�e en Y
* @param jTFZ JTextField coordonn�e en Z
**/
public Reactualisateur(Visu3DkartoMNT d,JTextField jTFX,JTextField jTFY,JTextField jTFZ,JTextField jTFA,JTextField jTFP,JTextField jTFR){
this.d=d;
this.jTFX=jTFX;
this.jTFY=jTFY;
this.jTFZ=jTFZ;
this.jTFA=jTFA;
this.jTFP=jTFP;
this.jTFR=jTFR;
}
/**
* M�thode appel�e lors du d�marrage de la Thread
*/
public void run(){
while(continu){
if ((!jTFX.isEditable())&&(!jTFY.isEditable())&&(!jTFZ.isEditable())){
d.reactualisePos();
}
if ((!jTFA.isEditable())&&(!jTFP.isEditable())&&(!jTFR.isEditable())){
d.reactualiseRotations();
}
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
}
}
public void arrete(){
continu=false;
}
}
/**
* Constructeur
* @param l le MNT courant
*/
public Visu3DkartoMNT(MNT l,DocumentKarto docKarto)
{
this.landMNT=l;
this.backGroundUrl = null;
this.docKarto=docKarto;
}
/**
Fonction d'initialisation de texture calibr�e
@param docK documentKarto courant
*/
private void initTextureCalibree(DocumentKarto docK){
try{
if ((docK==null)||(docK.getCarteFileName()==null)){
//System.err.println("Erreur : Probl�me lors de l'initialisation de la texture calibr�e");
earth = new TextureLoader(new java.net.URL("file:/nofile"), this).getTexture();
return;
} else if (!docK.isCalibrated()){
earth = new TextureLoader(new java.net.URL("file:"+((docK.getCarteFileName().charAt(0)=='/')?"":"/")+docK.getCarteFileName()), this).getTexture();
return;
}
// rectangle englobant la texture dont les positions sont calibr�es
Rectangle2 rect=MathUtil.getEnglobingRect(docK.getProjection(),0,0,
docK.getLignesDeNiveaux().getXMax()-1,docK.getLignesDeNiveaux().getYMax()-1);
System.out.println("RectangleTexture : "+rect);
System.out.println("RectangleMNT : "+landMNT.getX1()+" "+landMNT.getY1()+" "+landMNT.getX2()+" "+landMNT.getY2());
MediaTracker monTracker = new MediaTracker(this);
Image img=Toolkit.getDefaultToolkit().getImage(docK.getCarteFileName());
monTracker.addImage(img,0);
try{
monTracker.waitForID(0);
}catch(InterruptedException e) {
System.out.println("Exception : " + e.toString());
}
Image imageTexture;
// rectangle � s�lectionner dans la texture
double rx=Math.max(landMNT.getX1(),rect.x1);
double ry=Math.max(landMNT.getY1(),rect.y1);
double rw=Math.min(landMNT.getX2(),rect.x2)-rx;
double rh=Math.min(landMNT.getY2(),rect.y2)-ry;
//System.out.println("RectangleTexture1' : "+rx+" "+ry+" "+rw+" "+rh);
//System.out.println("Taille image : "+img.getWidth(this)+"x"+img.getHeight(this));
// on transforme les coordonn�es sur la carte en pixel dans l'image
int x=(int)((rx-rect.x1)*img.getWidth(this)/(rect.x2-rect.x1));
int y=(int)((ry-rect.y1)*img.getHeight(this)/(rect.y2-rect.y1));
int w=(int)(rw*img.getWidth(this)/(rect.x2-rect.x1));
int h=(int)(rh*img.getHeight(this)/(rect.y2-rect.y1));
System.out.println("RectangleTexture2 : "+x+" "+y+" "+w+" "+h);
if ((w>0) && (h>0)){
// pixels contenant les donn�es de la texture
int[] pixels = new int[(int)(w * h)];
PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
try {
pg.grabPixels();
} catch (InterruptedException e) {
System.err.println("interrupted waiting for pixels!");
return;
}
if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
System.err.println("image fetch aborted or errored");
return;
}
// si le MNT se trouve dans la texture, c'est bon
if ((landMNT.getX1()>rect.x1)&&(landMNT.getY1()>rect.y1)&&(landMNT.getX2()<rect.x2)&&(landMNT.getY2()<rect.y2)){
imageTexture = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, pixels, 0, w));
}else{
// calcul de la taille de la texture calibr�e finale
int tailleW=(int)((landMNT.getX2()-landMNT.getX1())*w/rw);
int tailleH=(int)((landMNT.getY2()-landMNT.getY1())*h/rh);
int[] pixelsTex = new int[tailleW*tailleH];
// dialog bouche-trou
BoucheTrouDialog bchTrou=new BoucheTrouDialog();
// tant qu'on n'a pas une r�ponse, on attend
while (!bchTrou.isGood());
// si l'utilisateur a choisi la couleur
if (bchTrou.choiceIsColor()){
// on remplit le tableau de la couleur
Arrays.fill(pixelsTex,bchTrou.getCouleurBC().getRGB());
}else{
// sinon l'utilisateur a choisi la texture
// on r�cup�re la texture d�finie par l'utilisateur
Image imgBT=Toolkit.getDefaultToolkit().getImage(bchTrou.getNomFichier());
monTracker.addImage(imgBT,1);
try{
monTracker.waitForID(1);
}catch(InterruptedException e) {
System.out.println("Exception : " + e.toString());
}
// on transforme l'image en un tableau
int[] pixelsBT=new int[imgBT.getWidth(this)*imgBT.getHeight(this)];
//System.out.println("W : "+imgBT.getWidth(this)+" H : "+imgBT.getHeight(this)+" L : "+pixelsBT.length);
pg = new PixelGrabber(imgBT, 0, 0, imgBT.getWidth(this), imgBT.getHeight(this), pixelsBT, 0, imgBT.getWidth(this));
try {
pg.grabPixels();
} catch (InterruptedException e) {
System.err.println("interrupted waiting for pixels!");
return;
}
if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
System.err.println("image fetch aborted or errored");
return;
}
// on remplit notre tableau de texture avec la texture r�cup�r�e
// que l'on r�p�te au bord
for(int i=0;i<tailleW;i++){
for (int j=0;j<tailleH;j++){
pixelsTex[i+tailleW*j]=pixelsBT[(i%imgBT.getWidth(this))+imgBT.getWidth(this)*(j%imgBT.getHeight(this))];
}
}
} // else du if (bchTrou.choiceIsColor())
// on r�cup�re la m�moire
bchTrou.dispose();
// indice o� l'on doit commencer � remplir la texture
int debX=(int)((Math.max(rect.x1,landMNT.getX1())-landMNT.getX1())*w/rw);
int debY=(int)((Math.max(rect.y1,landMNT.getY1())-landMNT.getY1())*h/rh);
// remplissage
for(int i=0;i<w;i++){
for (int j=0;j<h;j++){
pixelsTex[(debX+i) + (debY+j)*tailleW]=pixels[i+w*j];
}
}
// on cr�e l'image � partir du tableau
imageTexture = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(tailleW, tailleH, pixelsTex, 0, tailleW));
} // else de if ((landMNT.getX1()>rect.x1)&&(landMNT.getY1()>rect.y1)&&(landMNT.getX2()<rect.x2)&&(landMNT.getY2()<rect.y2)){
}else{
// else du if ((w>0) && (h>0)){
imageTexture = createImage(16,16);
}
// taille de la texture finale calibr�e
// (le TextureLoader ne fonctionne pas si les textures qu'on lui donne
// sont trop grandes ou bien si elles ne sont pas assez carr�)
int newWidth=512;
int newHeight=512;
// retaillage de l'image � la nouvelle taille
BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics2D.drawImage(imageTexture, 0, 0, newWidth, newHeight, null);
//System.out.println("Visu3DkartoMNT : resize image taille "+imageTexture.getHeight(null)+"x"+imageTexture.getWidth(null)+" sur taille : "+resizedImage.getHeight()+"x"+resizedImage.getWidth());
// on affiche l'image et on demande a l'utilisateur s'il veut sauver
Object[] options2 = {ResourceManager.get("OkKey"),ResourceManager.get("save")};
int value = JOptionPane.showOptionDialog(this, "", ResourceManager.get("TextureMNT"),
JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE,
new ImageIcon(resizedImage),options2,options2[0]);
if (value==JOptionPane.NO_OPTION) {
enregistreImage(resizedImage);
}
//GFE?? imageTexture=img_ico;
// on charge la texture
earth = new TextureLoader(resizedImage).getTexture();
} catch (Exception e){
//System.out.println("Land texture init error: "+e.getMessage());
e.printStackTrace();
JOptionPane.showMessageDialog(null,ResourceManager.get("errorTexMNT"),ResourceManager.get("error"),JOptionPane.WARNING_MESSAGE);
SwingUtilities.windowForComponent(this).dispose();
stop();
}
}
private void enregistreImage(BufferedImage image){
//System.out.println("enregistreImage");
int returnVal = fcCapt.showSaveDialog(this);
String nomFichier=null;
if (returnVal==JFileChooser.APPROVE_OPTION){
File file=fcCapt.getSelectedFile();
// on v�rifie si le fichier est accessible
if (file.exists()){
if (!file.canRead()){
JOptionPane.showMessageDialog(this,ResourceManager.get("errorFileRead"),ResourceManager.get("error"),JOptionPane.WARNING_MESSAGE);
return;
}
}
String extensionChoisie = (String)(((ExampleFileFilter)(fcCapt.getFileFilter())).getExtensions().nextElement());
nomFichier=file.getPath();
if (extensionChoisie.equals("gif")){
if (!nomFichier.endsWith(".gif"))
gifEnc.start(nomFichier+".gif");
else
gifEnc.start(nomFichier);
gifEnc.addFrame(image);
gifEnc.finish();
}
else if (extensionChoisie.equals("jpg")){
try{
if (!nomFichier.endsWith(".jpg"))
jpe = JPEGCodec.createJPEGEncoder(new FileOutputStream(nomFichier+".jpg"));
else
jpe = JPEGCodec.createJPEGEncoder(new FileOutputStream(nomFichier));
JPEGEncodeParam jpeParam = jpe.getDefaultJPEGEncodeParam(image);
jpeParam.setQuality(1.0f,false);
jpe.setJPEGEncodeParam(jpeParam);
jpe.encode(image);
OutputStream fich = jpe.getOutputStream();
fich.flush();
fich.close();
}
catch(Exception e){
System.err.println("Capture JPEG �chou�e");
}
}
}
}
/** Create an on-screen canvas to display the image
* @return a Canvas3D object
*/
private Canvas3D createCanvas(){
return createCanvas(false);
}
/** Create a canvas to display the image
* @param b Veut-on que le canvas soit on-screen ou off-screen
* @return a Canvas3D object
*/
private Canvas3D createCanvas(boolean b)
{
GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D();
gc1 = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getBestConfiguration(template);
return new Canvas3D(gc1,b);
}
/**
* Destroy applet, destroy universe
*/
public void destroy() {
universe.removeAllLocales();
if (reactualisateur!=null)
reactualisateur.arrete();
}
public static void main(String args[])
{
Visu3DkartoMNT d;
JFrame frame = new JMainFrame(d=new Visu3DkartoMNT(null,null), 800, 600);
frame.setTitle("kartoMNT V2");
}
/**
* Ajout du Terrain 3D au BranchGroup
* @param objGroup le BranchGroup auquel il faut ajouter le Terrain 3D
**/
private void addLandscape(BranchGroup objRoot)
{
try {
// MNT courant donn�
if (Variables.mntCourant){
if (landMNT==null){
JOptionPane.showMessageDialog(null,ResourceManager.get("noCurrMNT") ,ResourceManager.get("error"),JOptionPane.ERROR_MESSAGE);
SwingUtilities.windowForComponent(this).dispose();
stop();
}
L = new LandScape(landMNT);
}
// MNT fichier
else{
/*MNT mnt = new MNT();
FileInputStream fis = new FileInputStream(Variables.mntURL.substring(6));
DataInputStream dis = new DataInputStream(fis);
if(Variables.mntURL.toLowerCase().endsWith(".mnt")){
mnt.read(dis);
}
else if(Variables.mntURL.toLowerCase().endsWith(".sur")){
mnt.readSUR(dis);
}*/
MntFormat format = GestionnaireMntFormat.donneFormat(Variables.mntURL.substring(6));
if (format.support()==MntFormat.EXPORT){
throw new IOException();
}
MNT mnt = format.importMNT(Variables.mntURL.substring(6));
if (mnt==null){
throw new Exception(ResourceManager.get("errorMNT"));
}
L = new LandScape(mnt);
landMNT=mnt;
}
} catch (Exception e) {
//System.err.println("Landscape init error: "+e);
e.printStackTrace();
JOptionPane.showMessageDialog(null,ResourceManager.get("errorMNT"),ResourceManager.get("error"),JOptionPane.WARNING_MESSAGE);
SwingUtilities.windowForComponent(this).dispose();
stop();
}
try
{
// texture background
if (Variables.background){
backGroundUrl = new java.net.URL(Variables.backgroundURL);
}
else{
backGroundUrl = new java.net.URL("file:/nofile");
}
// texture MNT
switch (Variables.texture){
case DialogVisu3DkartoMNT.TEX_COURANTE:
initTextureCalibree(docKarto);
break;
case DialogVisu3DkartoMNT.TEX_CALIBREE:
DocumentKarto mydocK = KartoLoader.loadDocumentKarto(Variables.textureCalibreeURL);
initTextureCalibree(mydocK);
break;
case DialogVisu3DkartoMNT.TEX_FICHIER:
earth = new TextureLoader(new java.net.URL(Variables.textureURL), this).getTexture();
break;
case DialogVisu3DkartoMNT.NO_TEX:
default:
earth = new TextureLoader(new java.net.URL("file:/nofile"), this).getTexture();
}
}
catch (Exception e)
{
//System.out.println("Land texture init error: "+e.getMessage());
JOptionPane.showMessageDialog(null,ResourceManager.get("errorTexMNT"),ResourceManager.get("error"),JOptionPane.WARNING_MESSAGE);
SwingUtilities.windowForComponent(this).dispose();
stop();
}
// par d�faut, mode textur�
L.selectMaterial();
// initilasation texture
L.setTexture(earth);
// initialisation des multiplicateurs
if (Variables.paramAuto){
// Automatique
L.setGridScaleX(landMNT.getPasX());
L.setGridScaleY(landMNT.getPasY());
L.setHeightScale(Variables.zScale=1.0f);
}
else{
// Manuel
L.setGridScaleX(Variables.gridScaleX);
L.setGridScaleY(Variables.gridScaleY);
L.setHeightScale(Variables.zScale);
}
BranchGroup land = new BranchGroup();
land.addChild(L.LODModel());
objRoot.addChild(land);
}
/**
* Ajout de Brouillard
* (non utilis�)
* @param objRoot le BranchGroup auquel il faut rajouter le brouillard
*/
private void addFog(BranchGroup objRoot)
{
BoundingSphere boundsForFog =
new BoundingSphere(new Point3d(worldSize / 2.0, worldSize / 2.0, 0.0), worldSize * 2.0);
ExponentialFog fog = new ExponentialFog();
fog.setColor(new Color3f(0.7f, 0.1f, 0.1f));
fog.setDensity(0.002f);
fog.setCapability(Fog.ALLOW_COLOR_WRITE );
fog.setCapability(ExponentialFog.ALLOW_DENSITY_WRITE );
fog.setInfluencingBounds(boundsForFog);
objRoot.addChild(fog);
}
/**
* Ajout de la Navigation de la cam�ra
* @param objRoot le BranchGroup auquel il faut rajouter la navigation
* @param cockpitTranformGroup TransformGroup utilis� pour rajouter la croix centrale � la vue
* @param startLocation position de d�part
* @param startRotation rotation de d�part (plus utilis�)
* @param worldXBounds bornes du monde en X
* @param worldZBounds bornes du monde en Z
*/
private void addNavigation(BranchGroup objRoot, TransformGroup cockpitTranformGroup,TransformGroup repereTranformGroup, Vector3d startLocation, double startRotation,
Vector2d worldXBounds, Vector2d worldZBounds)
{
TransformGroup vpTrans = universe.getViewingPlatform().getViewPlatformTransform();
navigation = new Navigation(vpTrans, universe.getCanvas(), cockpitTranformGroup,repereTranformGroup, startLocation, startRotation,
worldXBounds, worldZBounds);
navigation.setLandscape(L);
// recentrage d�s le d�part
navigation.recentre();
BoundingSphere navBounds = new BoundingSphere(new Point3d(worldSize / 2.0, worldSize / 2.0, 0.0), worldSize * 20.0);
navigation.setSchedulingBounds(navBounds);
objRoot.addChild(navigation);
}
/**
* Permet de rajouter la Croix verte centrale
* @param objRoot le BranchGroup auquel il faut rajouter la Croix verte centrale
*/
private TransformGroup addCockpit(BranchGroup objRoot)
{
TransformGroup cockpitTransforGroup = new TransformGroup();
cockpitTransforGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
Crosshair crosshair = new Crosshair(-2.0f, 0.05f);
cockpitTransforGroup.addChild(crosshair);
cock = new BranchGroup();
cock.addChild(cockpitTransforGroup);
cock.setCapability(BranchGroup.ALLOW_DETACH);
objRoot.addChild(cock);
return cockpitTransforGroup;
}
/**
* Permet de rajouter le Rep�re en bas � gauche
* @param objRoot le TransformGroup auquel il faut rajouter le rep�re
@return le Transform Group construit pas la fonction
*/
private TransformGroup addRepere(TransformGroup objRoot)
{
//TransformGroup repereTransforGroup = new TransformGroup();
//repereTransforGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
//repereTransforGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
//Repere rep = new Repere(-0.75f,-0.8f,-2.0f,0.1f);
//Repere rep = new Repere(0,0,0,0.1f);
//repereTransforGroup.addChild(rep);
TransformGroup repereTransforGroup = new TransformGroup();
repereTransforGroup.setCapability( TransformGroup.ALLOW_TRANSFORM_READ );
repereTransforGroup.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
Color3f red = new Color3f( 1.0f, 0.0f, 0.0f );
Color3f green = new Color3f( 0.0f, 1.0f, 0.0f );
Color3f blue = new Color3f( 0.0f, 0.0f, 1.0f );
Color3f black = new Color3f( 0.0f, 0.0f, 0.0f );
Color3f white = new Color3f( 1.0f, 1.0f, 1.0f );
Material mRed = new Material(red, black, red, white, 100.0f);
Material mGreen = new Material(green, black, green, white, 100.0f);
Material mBlue = new Material(blue, black, blue, white, 100.0f);
//The arrow pointing in the +X direction:
Appearance a = new Appearance();
a.setMaterial( mGreen );
Transform3D tX = new Transform3D();
tX.rotZ( - Math.PI / 2.0 );
TransformGroup tgX = new TransformGroup( tX );
//tgX.setCapability( TransformGroup.ALLOW_CHILDREN_READ );
//tgX.setCapability( TransformGroup.ALLOW_CHILDREN_WRITE );
tgX.addChild( createArrow( a ) );
repereTransforGroup.addChild( tgX );
//The arrow pointing in the +Y direction:
Appearance b = new Appearance();
b.setMaterial( mBlue );
Transform3D tY = new Transform3D();
//tY.rotZ( - Math.PI / 2.0 ); //do not need to rotate this one; it comes pre-built
TransformGroup tgY = new TransformGroup( tY );
//tgY.setCapability( TransformGroup.ALLOW_CHILDREN_READ );
//tgY.setCapability( TransformGroup.ALLOW_CHILDREN_WRITE );
tgY.addChild( createArrow( b ) );
repereTransforGroup.addChild( tgY );
//The arrow pointing in the +Z direction:
Appearance c = new Appearance();
c.setMaterial( mRed );
Transform3D tZ = new Transform3D();
tZ.rotX( Math.PI / 2.0 );
TransformGroup tgZ = new TransformGroup( tZ );
//tgZ.setCapability( TransformGroup.ALLOW_CHILDREN_READ );
//tgZ.setCapability( TransformGroup.ALLOW_CHILDREN_WRITE );
tgZ.addChild( createArrow( c ) );
repereTransforGroup.addChild( tgZ );
objRoot.addChild(repereTransforGroup);
//return repereTransforGroup;
return repereTransforGroup;
}
private BranchGroup createArrow( Appearance a ){
Cone cone;
Cylinder cyl;
BranchGroup objRoot = new BranchGroup();
objRoot.setCapability( BranchGroup.ALLOW_CHILDREN_READ );
objRoot.setCapability( BranchGroup.ALLOW_CHILDREN_WRITE );
cone = new Cone( 0.02f, 0.05f, Cone.GENERATE_NORMALS, a);
cyl = new Cylinder( 0.01f, 0.05f, Cylinder.GENERATE_NORMALS, a);
Transform3D t = new Transform3D();
t.set( new Vector3f( 0.0f, 0.05f, 0.0f ) );
TransformGroup coneTg = new TransformGroup( t );
//coneTg.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
//coneTg.setCapability( TransformGroup.ALLOW_TRANSFORM_READ );
coneTg.addChild( cone );
TransformGroup tg = new TransformGroup( );
//tg.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
//tg.setCapability( TransformGroup.ALLOW_TRANSFORM_READ );
tg.addChild( cyl );
Transform3D base = new Transform3D();
base.set( new Vector3f( 0.0f, .025f, 0.0f ) );
TransformGroup objTrans = new TransformGroup( base );
//objTrans.setCapability( TransformGroup.ALLOW_TRANSFORM_WRITE );
//objTrans.setCapability( TransformGroup.ALLOW_TRANSFORM_READ );
objTrans.addChild( tg );
objTrans.addChild( coneTg );
objRoot.addChild( objTrans );
return objRoot;
}
/**
* Permet de rajouter le Socle du Landscape
* @param objRoot le BranchGroup auquel il faut rajouter le Socle du Landscape
*/
private void addSocle(BranchGroup objRoot){
socle=new BranchGroup();
socle.addChild(new Socle(L));
socle.setCapability(BranchGroup.ALLOW_DETACH);
objRoot.addChild(socle);
}
/**
* Permet de rajouter la Lumi�re
* @param objRoot le BranchGroup auquel il faut rajouter la Lumi�re
*/
private void addLights(BranchGroup graphRoot)
{
/* Bounds for light */
BoundingSphere boundsForLight =
new BoundingSphere(new Point3d(worldSize / 2.0, worldSize / 2.0, 0.0), worldSize * 20.0);
/* Global ambient light */
Color3f ambientColor = new Color3f(0.2f, 0.2f, 0.2f);
AmbientLight ambientLight = new AmbientLight(ambientColor);
ambientLight.setInfluencingBounds(boundsForLight);
graphRoot.addChild(ambientLight);
/* Directional light */
Color3f directionalColor = new Color3f(0.8f, 0.8f, 0.8f);
Vector3f lightDirection = new Vector3f(-1.0f, -1.0f, -1.0f);
DirectionalLight directionalLight = new DirectionalLight(directionalColor, lightDirection);
directionalLight.setInfluencingBounds(boundsForLight);
graphRoot.addChild(directionalLight);
}
/**
* Permet de rajouter le Fond
* @param objRoot le BranchGroup auquel il faut rajouter le Fond
*/
private void addBackGround(BranchGroup graphRoot, java.net.URL backGroundUrl)
{
if(backGroundUrl != null)
{
/* Bounds for backgound */
BoundingSphere boundsForBackGound =
new BoundingSphere(new Point3d(worldSize / 2.0, worldSize / 2.0, 0.0), worldSize * 20.0);
/* BackGround geometry */
Background backGround = new Background();
backGround.setApplicationBounds(boundsForBackGound);
BranchGroup backGroundGeoBranch = new BranchGroup();
Sphere sphere = new Sphere(1.0f, Sphere.GENERATE_NORMALS |
Sphere.GENERATE_NORMALS_INWARD |
Sphere.GENERATE_TEXTURE_COORDS, 20);
/* BackGround appearance */
Appearance backgroundApp = sphere.getAppearance();
TextureLoader texture = new TextureLoader(backGroundUrl, this);
if (texture != null)
backgroundApp.setTexture(texture.getTexture());
/* BackGround to the scene */
backGroundGeoBranch.addChild(sphere);
backGround.setGeometry(backGroundGeoBranch);
graphRoot.addChild(backGround);
}
}
/**
* M�thode de r�actualisation de la position courante de la cam�ra
*/
public void reactualisePos(){
Vector3d vect = navigation.getPosition();
jTFcoordX.setText(Double.toString(Math.floor(vect.x*100+0.5)/100));
jTFcoordY.setText(Double.toString(Math.floor(vect.y*100+0.5)/100));
jTFcoordZ.setText(Double.toString(Math.floor(vect.z*100+0.5)/100));
}
/**
* M�thode de r�actualisation de la position courante de la cam�ra
*/
public void reactualiseRotations(){
Vector3d vect = navigation.getRotations();
jTFangA.setText(Double.toString(Math.floor(vect.x*100+0.5)/100%360));
jTFangP.setText(Double.toString(Math.floor(vect.y*100+0.5)/100%360));
jTFangR.setText(Double.toString(Math.floor(vect.z*100+0.5)/100%360));
}
/**
* M�thode indiquant que le Slider a �t� boug�
*
* @param e Le ChangeEvent permettant d'obtenir de JSlider qui a boug�
*/
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider)e.getSource();
if (source==quality){
if (!source.getValueIsAdjusting()) {
int qual = (int)source.getValue();
switch(qual){
case 1:
L.changeQuality(Variables.quality1);
break;
case 2:
L.changeQuality(Variables.quality2);
break;
case 3:
L.changeQuality(Variables.quality3);
break;
case 4:
L.changeQuality(Variables.quality4);
break;
case 5:
L.changeQuality(Variables.quality5);
break;
case 6:
L.changeQuality(Variables.quality6);
break;
case 7:
L.changeQuality(Variables.quality7);
break;
case 8:
L.changeQuality(Variables.quality8);
break;
case 9:
L.changeQuality(Variables.quality9);
break;
case 10:
L.changeQuality(Variables.quality10);
break;
default:
break;
}
}
}
else if (source==sliderMove){
if (!source.getValueIsAdjusting()) {
int mov = (int)source.getValue();
source.setValue(mov);
Navigation.MAX_MOVE_SPEED=mov;
}
}
else if (source==sliderStrafe){
if (!source.getValueIsAdjusting()) {
int mov = (int)source.getValue();
source.setValue(mov);
Navigation.MAX_STRAFE_SPEED=mov;
}
}
else if (source==sliderRoll){
if (!source.getValueIsAdjusting()) {
int mov = (int)source.getValue();
source.setValue(mov);
Navigation.MAX_ROLL_SPEED=mov/(double)200.0;
}
}
else if (source==sliderRotation){
if (!source.getValueIsAdjusting()) {
int mov = (int)source.getValue();
source.setValue(mov);
Navigation.MAX_ROTATION_SPEED=mov/(double)200.0;
}
}
}
/**
* M�thode appel� quand on appuie sur un bouton
*
* @param ae L'ActionEvent appel� quand quelqu'un
* appuie sur un bouton
*/
public void actionPerformed(ActionEvent ae){
JButton bouton = (JButton)ae.getSource();
// bouton de capture d'�cran
if (bouton == bCaptEcran){
// v�rification de l'os
try{
// on demande � l'utilisateur quel type de capture d'�cran il d�sire
Object[] options1 = {ResourceManager.get("bCapt1"),ResourceManager.get("bCapt2")};
int value = JOptionPane.showOptionDialog(null,
ResourceManager.get("whichCapt"),
ResourceManager.get("question"),
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //don't use a custom Icon
options1, //the titles of buttons
options1[0]); //default button title
BufferedImage image = null;
// s'il d�sire une capture normale
if (value == JOptionPane.YES_OPTION) {
int width = canvas.getSize().width;
int height = canvas.getSize().height;
GraphicsContext3D ctx = canvas.getGraphicsContext3D();
Raster ras = new Raster();
ras.setType(Raster.RASTER_COLOR);
ras.setSize(width, height);
ras.setSrcOffset(0, 0);
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
ImageComponent2D image2d =
new ImageComponent2D(ImageComponent2D.FORMAT_RGB, image);
ras.setImage(image2d);
ctx.readRaster(ras);
// Now strip out the image info
ImageComponent2D img_src = ras.getImage();
image=img_src.getImage();
}
// s'il d�sire une capture grande qualit�
else{
image = offCanvas.retourneImage();
}
// on demande le type de sauvegarde d�sir�
Object[] options = {ResourceManager.get("auto")+" GIF",ResourceManager.get("auto")+" JPEG",ResourceManager.get("manual")};
value = JOptionPane.showOptionDialog(null,
ResourceManager.get("autoName"),
ResourceManager.get("question"),
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, //don't use a custom Icon
options, //the titles of buttons
options[0]); //default button title
// on sauvegarde la capture
if (value == JOptionPane.CANCEL_OPTION) {
enregistreImage(image);
}
else if (value == JOptionPane.YES_OPTION){
++capture;
gifEnc.start("capture/capt"+((capture/100)%10)+""+((capture/10)%10)+""+(capture%10)+".gif");
gifEnc.addFrame(image);
gifEnc.finish();
}
else {
++capture;
jpe = JPEGCodec.createJPEGEncoder(new FileOutputStream("capture/capt"+((capture/100)%10)+""+((capture/10)%10)+""+(capture%10)+".jpg"));
JPEGEncodeParam jpeParam = jpe.getDefaultJPEGEncodeParam(image);
jpeParam.setQuality(1.0f,false);
jpe.setJPEGEncodeParam(jpeParam);
jpe.encode(image);
OutputStream fich = jpe.getOutputStream();
fich.flush();
fich.close();
}
}
catch(Exception ex){
JOptionPane.showMessageDialog(null,ResourceManager.get("CaptNotAllow"),ResourceManager.get("error"),JOptionPane.ERROR_MESSAGE);
return;
}
}
// bouton saisie de s�quences d'image
else if (bouton == bSeq){
try{
if (bFilm.getText().equals(ResourceManager.get("start"))){
if (bSeq.getText().equals(ResourceManager.get("start"))){
// v�rification de l'os
// if (!System.getProperty("os.name").startsWith("Windows")){
// int n = JOptionPane.showConfirmDialog(
// (Component)null,
// ResourceManager.get("captOnlyWin2"),ResourceManager.get("warning"),
// JOptionPane.YES_NO_OPTION);
// if (n==JOptionPane.NO_OPTION ) return;
// }
bSeq.setText(ResourceManager.get("stop"));
// lancement du s�quenceur
seq = new Sequenceur(false,gifEnc,canvas);
}
else{
bSeq.setText(ResourceManager.get("start"));
seq.stop();
}
}
}
catch(Exception ex){
JOptionPane.showMessageDialog(null,ResourceManager.get("CaptNotAllow"),ResourceManager.get("error"),JOptionPane.ERROR_MESSAGE);
return;
}
}
// bouton saisie de film
else if (bouton == bFilm){
try{
if (bSeq.getText().equals(ResourceManager.get("start"))){
if (bFilm.getText().equals(ResourceManager.get("start"))){
// v�rification de l'os
// if (!System.getProperty("os.name").startsWith("Windows")){
// int n = JOptionPane.showConfirmDialog(
// (Component)null,
// ResourceManager.get("captOnlyWin2"),ResourceManager.get("warning"),
// JOptionPane.YES_NO_OPTION);
// if (n==JOptionPane.NO_OPTION ) return;
// }
// lancement du s�quenceur
seq = new Sequenceur(true,gifEnc,canvas);
bFilm.setText(ResourceManager.get("stop"));
}
else{
bFilm.setText(ResourceManager.get("start"));
seq.stop();
}
}
}
catch(Exception ex){
JOptionPane.showMessageDialog(null,ResourceManager.get("CaptNotAllow"),ResourceManager.get("error"),JOptionPane.ERROR_MESSAGE);
return;
}
}
// bouton Changement de Position
else if (bouton == bChPos){
if (!jTFcoordX.isEditable()){
jTFcoordX.setEditable(true);
jTFcoordY.setEditable(true);
jTFcoordZ.setEditable(true);
}
else{
jTFcoordX.setEditable(false);
jTFcoordY.setEditable(false);
jTFcoordZ.setEditable(false);
double posX,posY,posZ;
// r�cup�ration de la position sur le MNT
try{
posX = Double.parseDouble(jTFcoordX.getText());
posY = Double.parseDouble(jTFcoordY.getText());
posZ = Double.parseDouble(jTFcoordZ.getText());
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null,ResourceManager.get("posInc")
,ResourceManager.get("error"),JOptionPane.ERROR_MESSAGE);
return;
}
// calcul de la position dans la monde 3D
// posX += L.getXSize()-1;
// posX -= L.getMNT().getX1();
//posX *= Variables.gridScaleX;
posX -= L.getXSize()-1;
posX -= L.getMNT().getX1();
posX *= -Variables.gridScaleX;
posY -= L.getMNT().getY1();
posY *= -Variables.gridScaleY;
//posY =-posY;
posZ *= Variables.zScale;
double temp;
temp=posY;
posY=posZ;
posZ=temp;
navigation.translate(new Vector3d(posX,posY,posZ));
}
}
// bouton Changement d'Angles
else if (bouton == bChDir){
if (!jTFangA.isEditable()){
jTFangA.setEditable(true);
jTFangP.setEditable(true);
jTFangR.setEditable(true);
} else{
jTFangA.setEditable(false);
jTFangP.setEditable(false);
jTFangR.setEditable(false);
double angA,angP,angR;
// r�cup�ration de la position sur le MNT
try{
angA = Double.parseDouble(jTFangA.getText());
angP = Double.parseDouble(jTFangP.getText());
angR = Double.parseDouble(jTFangR.getText());
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null,ResourceManager.get("angInc")
,ResourceManager.get("error"),JOptionPane.ERROR_MESSAGE);
return;
}
navigation.setRotations(angA,angP,angR);
}
}
// bouton Stop
else if (bouton == bStop){
navigation.stoppe();
}
// autre bouton de navigation
else if (bouton == bHaut){
navigation.addCurrentYStrafe(Navigation.MAX_STRAFE_SPEED);
}
else if (bouton == bRG){
navigation.addCurrentRoll(-Navigation.MAX_ROLL_SPEED);
}
else if (bouton == bAvant){
navigation.setAccelerateForward(true);
}
else if (bouton == bRD){
navigation.addCurrentRoll(Navigation.MAX_ROLL_SPEED);
}
else if (bouton == bGauche){
navigation.addCurrentXStrafe(-Navigation.MAX_STRAFE_SPEED);
}
else if (bouton == bArriere){
navigation.setAccelerateBackward(true);
}
else if (bouton == bDroite){
navigation.addCurrentXStrafe(Navigation.MAX_STRAFE_SPEED);
}
else if (bouton == bBas){
navigation.addCurrentYStrafe(-Navigation.MAX_STRAFE_SPEED);
}
// bouton de recentrage
else if (bouton == bRec){
navigation.recentre();
}
// bouton de rotation autour du MNT
else if (bouton == bRot){
if (bouton.getActionCommand().equals("Activ�")){
bouton.setActionCommand("D�sactiv�");
navigation.setRotationAutourDuMNT(true);
bRot.setToolTipText(ResourceManager.get("desRot"));
bouton.setIcon(new ImageIcon("icones/translation.gif"));
}
else{
bouton.setActionCommand("Activ�");
navigation.setRotationAutourDuMNT(false);
bRot.setToolTipText(ResourceManager.get("actRot"));
bouton.setIcon(new ImageIcon("icones/rotation.gif"));
}
}
// bouton de remise � l'horizontale
else if (bouton == bHor){
navigation.horizon();
}
// bouton de changement de mode
else if (bouton == bMode){
if (bouton.getActionCommand().equals("Texture")){
bouton.setActionCommand("Fil de Fer");
bMode.setToolTipText(ResourceManager.get("texMod"));
bouton.setIcon(new ImageIcon("icones/texture.gif"));
}
else{
bouton.setActionCommand("Texture");
bMode.setToolTipText(ResourceManager.get("FdFmod"));
bouton.setIcon(new ImageIcon("icones/fildefer.gif"));
}
L.switchMode();
}
// bouton titre
else if (bouton == titre){
JOptionPane.showMessageDialog(null,ResourceManager.get("author")
,"kartoMNT V2",JOptionPane.INFORMATION_MESSAGE);
}
}
/** Listens to the check boxes. */
public void itemStateChanged(ItemEvent e) {
JCheckBox choix = (JCheckBox)e.getSource();
if (choix==jcbCC){
if (contentBranchGroup.indexOfChild(cock)==-1){
contentBranchGroup.addChild(cock);
}
else{
contentBranchGroup.removeChild(cock);
}
}else if (choix==jcbS){
if (contentBranchGroup.indexOfChild(socle)==-1){
contentBranchGroup.addChild(socle);
} else{
contentBranchGroup.removeChild(socle);
}
}
}
}