Java-Gaming.org    
Featured games (79)
games approved by the League of Dukes
Games in Showcase (477)
Games in Android Showcase (109)
games submitted by our members
Games in WIP (536)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  FSEM and layout manager issue  (Read 1495 times)
0 Members and 1 Guest are viewing this topic.
Offline nsigma
« Posted 2010-09-16 11:00:16 »

Hi,

I've got a project where I'm using a BufferStrategy on a Canvas of a fixed dimension.  I want the option to show this Canvas either in a standard decorated Frame or centred within a full screen (black) window.  I'm using (roughly) the following code.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
Dimension dim = new Dimension(width, height);
Frame frame = new Frame();
frame.setLayout(new GridBagLayout());
frame.setBackground(Color.BLACK);
canvas = new Canvas();
canvas.setMinimumSize(dim);
canvas.setPreferredSize(dim);
frame.add(canvas);
if (fullScreen) {
    frame.setUndecorated(true);
    GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    gd.setFullScreenWindow(frame);
} else {
    frame.pack();
    frame.setVisible(true);
}


This works great on Linux.  I tried it on Windows (7) the other day, and the canvas is rendered in the top left.

Is there something obviously wrong with this approach?
Should I be setting the size of the window explicitly before using FSEM?  I was under the impression that setFullScreenWindow() sets the bounds of the window anyway?

I couldn't find any specific examples of achieving this, so thought I'd ask here - surely someone's done this before.  Tweaks to above code, or ideas for a completely different strategy to make this work cross-platform greatly appreciated.

Thanks in advance, Neil

Praxis LIVE - open-source intermedia toolkit and live interactive visual editor
Digital Prisoners - interactive spaces and projections
Offline nsigma
« Reply #1 - Posted 2010-09-24 13:23:45 »

Sorry to bump this persecutioncomplex

Have also changed title to make it more obvious what I'm trying to do.  Surely someone's done this before - what daft mistake am I making???

Praxis LIVE - open-source intermedia toolkit and live interactive visual editor
Digital Prisoners - interactive spaces and projections
Offline bobjob

JGO Knight


Medals: 10
Projects: 4


David Aaron Muhar


« Reply #2 - Posted 2010-09-24 13:33:56 »

On this thread I posted some example code on how work with a canvas in fullscreen.

http://www.java-gaming.org/topics/java-sound-api-java-full-screen-exclusive-mode-api-amp-linux/22661/view.html

you might want to consider making the canvas fullscreen, setting up a bufferstrategy, rendering to a volitile image, then rendering that image in the center of the screen.
or do the extra math and add offset values to each of your calls to draw.
In regards to your layout also make sure to call validate() on the frame.

My Projects
Games, Webcam chat, Video screencast, PDF tools.

Javagaming.org with chat room
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline nsigma
« Reply #3 - Posted 2010-09-24 14:22:46 »

I just started replying to you, and then noticed you'd added extra information.  Smiley

Firstly, thanks for responding.

I have seen that thread you linked to.  In fact, I posted on it!  (Incidentally, the fake full screen code you posted doesn't work reliably cross-platform for the reasons I posted there.)

I had another look at the rest of the code you posted and realised that you're using a canvas set to screen size, and realise that I could try the solution you suggest and just render an image into the centre.  At the moment I've got my code set so that it ignores repaints on the Canvas but not on the Frame to not have the extra (probably minimal) overhead of clearing the area outside the image.

Your comment about validate() may have hit the nail on the head though.  I was under the impression that setBounds() automatically revalidated everything.  Googling this suggests that there may be a bug that this works differently on Linux and Windows.  Will try manually setting the frame size and validating prior to FSEM and see if that works first.

Thanks for your input.  I only have an IDE set up on Linux atm so makes tweaking things to test on Windows a bit awkward.

Best wishes,  Neil

Praxis LIVE - open-source intermedia toolkit and live interactive visual editor
Digital Prisoners - interactive spaces and projections
Offline bobjob

JGO Knight


Medals: 10
Projects: 4


David Aaron Muhar


« Reply #4 - Posted 2010-09-24 20:01:03 »

yeah the code posted there isnt fullscreen exclusive mode, but it wouldnt take much to add it that way.

modified version for fullscreen exclusive mode. and centered the rendering

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
308  
309  
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import javax.swing.JFrame;

import java.awt.DisplayMode;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.MemoryImageSource;
import java.awt.image.VolatileImage;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Component;
public class FakeFullscreen implements Runnable {
   
   //SHOULD BE SET TO TRUE FOR NORMAL GAME LOGIC
  final static boolean FRAME_SYNC = true;
   final static int FRAME_RATE = 61;
   
   final static boolean STRETCH = false;
   final static boolean HIGH_QUALITY = true;
   final static boolean FULLSCREEN = true;
   
   boolean isRunning;
   CustomTimer timer;
   FPSCounter fpsCounter;
   
   
   JFrame    frame;
   VolatileImage offScreen = null;
   BufferStrategy buffer;
   Component drawArea;
   Dimension screenSize;
   Dimension gameSize;
   Rectangle gameArea;
   Graphics2D offScreenGraphics;
   Graphics2D graphics;
   
   public FakeFullscreen() {
     
      frame = new JFrame() {
          public void paint(Graphics g) {
             
          }
           public void update(Graphics g) {
             
          }
           
      };
      timer = new CustomTimer();
      fpsCounter = new FPSCounter(timer);
      final Toolkit toolkit = Toolkit.getDefaultToolkit();

      final int[] pixels = new int[16 * 16];
      final Image image = toolkit.createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
      final Cursor invisibleCursor = toolkit.createCustomCursor(image, new Point(0, 0), "invisibleCursor");

      gameSize = new Dimension(640, 480);
      screenSize = toolkit.getScreenSize();
      gameArea = new Rectangle(0, 80, 640, 400);

      frame.setAlwaysOnTop(true);
      frame.setCursor(invisibleCursor);
      frame.setIgnoreRepaint(true);
      frame.setLocation(0, 0);
      frame.setResizable(false);



      frame.addKeyListener(new KeyAdapter() {
         @Override
         public void keyPressed(KeyEvent event) {
            if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
               isRunning = false;
            }
         }
      });
     
     
      frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
      frame.addWindowListener(new WindowAdapter() {
         @Override
            public void windowClosing(WindowEvent e) {
                isRunning = false;
            }
        });


     
     
      if (FULLSCREEN) {
         try {
           
            GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
             GraphicsDevice device = env.getDefaultScreenDevice();

             GraphicsConfiguration gc = device.getDefaultConfiguration();
             
             //DisplayMode displayMode = device.getDisplayMode();
            //if (device.isDisplayChangeSupported()) {
               //GraphicsDevice[] devices = env.getScreenDevices();
               //for (int i = 0; i < devices.length; i++) {
               //   DisplayMode dms[] = devices[i].getDisplayModes();
               //   for (int j = 0; j < dms.length; j++) {
               //      System.out.println("Device      : " + (i+1));
               //       System.out.println("Width       : " + dms[j].getWidth());
               //       System.out.println("Height      : " + dms[j].getHeight());
               //        System.out.println("Refresh Rate: " + dms[j].getRefreshRate());
               //       System.out.println("Bit Depth   : " + dms[j].getBitDepth());
               //       System.out.println("");
               //   }
               //}
               //device.setDisplayMode(displayMode);

              // }
            frame.setUndecorated(true);
             
             device.setFullScreenWindow(frame);
             frame.setSize(screenSize);
             frame.setVisible(true);
             drawArea = frame.getContentPane();
             frame.toFront();
             frame.createBufferStrategy(2);
             buffer = frame.getBufferStrategy();

             offScreen = gc.createCompatibleVolatileImage(gameSize.width, gameSize.height);
             //canvas.setSize(screenSize);
        } catch (Exception e) {
            e.printStackTrace();
         }
      } else {
         final Canvas canvas = new Canvas();
         canvas.setIgnoreRepaint(true);
         drawArea = canvas;
         canvas.setSize(gameSize);
         if (STRETCH) frame.setResizable(true);
         frame.add(canvas);
         
         frame.pack();
         frame.setVisible(true);
         frame.toFront();
         frame.validate();
         
         canvas.createBufferStrategy(2);
         buffer = canvas.getBufferStrategy();
         offScreen = canvas.createVolatileImage(gameSize.width, gameSize.height);
      }


     

      isRunning = true;
     
     
      new Thread(this).start();
   }

   public void run() {
     
     
      int ballWidth = 8;
      int ballHeight = 8;
      int ballX = gameArea.width / 2 - ballWidth / 2;
      int ballY = gameArea.y + (gameArea.height / 2 - ballHeight / 2);
      int ballDx = 1;
      int ballDy = 1;
      while (isRunning) {
         if (!FRAME_SYNC || timer.update(FRAME_RATE)) {
            fpsCounter.update();
            ballX += ballDx;
            ballY += ballDy;

            if (ballX <= gameArea.x) {
               ballX = gameArea.x;
               ballDx = -ballDx;
            } else if (ballX >= gameArea.width - ballWidth) {
               ballX = gameArea.width - ballWidth;
               ballDx = -ballDx;
            }

            if (ballY <= gameArea.y) {
               ballY = gameArea.y;
               ballDy = -ballDy;
            } else if (ballY >= gameArea.y + gameArea.height - ballHeight) {
               ballY = gameArea.y + gameArea.height - ballHeight;
               ballDy = -ballDy;
            }
            try {
               offScreenGraphics = offScreen.createGraphics();
               offScreenGraphics.setColor(Color.BLACK);
               offScreenGraphics.fillRect(0, 0, screenSize.width, screenSize.height);
               offScreenGraphics.setColor(Color.WHITE);
               offScreenGraphics.drawString(String.format("FPS: %s", fpsCounter.getFPS()), 20, 20);

               int renderX = (int) (ballX + ballDx);
               int renderY = (int) (ballY + ballDy);

               offScreenGraphics.drawLine(gameArea.x, gameArea.y - ballHeight, gameArea.width, gameArea.y - ballHeight);
               offScreenGraphics.fillRect(renderX, renderY, ballWidth, ballHeight);
               
               
               graphics = (Graphics2D) buffer.getDrawGraphics();
                  if (STRETCH) {
                     if (HIGH_QUALITY) {
                        graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                     }
                     graphics.drawImage(offScreen, 0, 0, drawArea.getWidth(), drawArea.getHeight(), 0, 0, gameSize.width, gameSize.height, null);  
                  } else {
                     graphics.setColor(Color.BLACK);
                     graphics.fillRect(0, 0, drawArea.getWidth(), drawArea.getHeight());
                     int offXFactor = offScreen.getWidth()/2;
                     int offYFactor = offScreen.getHeight()/2;
                     int midX = drawArea.getWidth()/2;
                     int midY = drawArea.getHeight()/2;
                     graphics.drawImage(offScreen, midX - offXFactor, midY - offYFactor, null);
                  }
                 

               //if (!buffer.contentsLost()) {
                 buffer.show();
               //}
           } finally {
               if (offScreenGraphics != null) {
                  offScreenGraphics.dispose();
               }

               if (graphics != null) {
                  graphics.dispose();
               }
            }
         }
         Thread.yield();
      }
      frame.setVisible(false);
      System.exit(0);
   }
   public static void main(String[] args) {
      new FakeFullscreen();
   }
}

class CustomTimer {
   private long timeThen;
   public CustomTimer() {
      timeThen = System.nanoTime();
   }
   public boolean update(int fps) {

      long gapTo = 1000000000L / fps + timeThen;
      long timeNow = System.nanoTime();
      if (gapTo > timeNow) return false;
      timeThen = timeNow;

      return true;
   }

   public long getTime() {
      return System.nanoTime();
   }
   public long getTimerResolution() {
      return 1000000000L;
   }
}
class FPSCounter {
   private CustomTimer timer;
   private float FPS = 0, fc = 0;

    private long
                 currentTime,
                 elapsedTime,
                 lastTime;
   
    public FPSCounter(CustomTimer timer) {
       this.timer = timer;
        currentTime     = 0;
        elapsedTime = lastTime = timer.getTime();
    }
    public boolean update() {
      currentTime = timer.getTime();

         fc++;
         long updateFrequency = timer.getTimerResolution()>>1;
         if((elapsedTime = currentTime - lastTime) >= updateFrequency){
           FPS         = (fc/elapsedTime)*updateFrequency*2;
           fc         = 0;
           lastTime    = currentTime;
           elapsedTime = 0;
           return true;
         }
         return false;
    }
    public float getFPS() {
       return FPS;
    }
}


btw. I tested it on win7

My Projects
Games, Webcam chat, Video screencast, PDF tools.

Javagaming.org with chat room
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CogWheelz (18 views)
2014-07-30 21:08:39

Riven (26 views)
2014-07-29 18:09:19

Riven (15 views)
2014-07-29 18:08:52

Dwinin (13 views)
2014-07-29 10:59:34

E.R. Fleming (34 views)
2014-07-29 03:07:13

E.R. Fleming (12 views)
2014-07-29 03:06:25

pw (43 views)
2014-07-24 01:59:36

Riven (44 views)
2014-07-23 21:16:32

Riven (30 views)
2014-07-23 21:07:15

Riven (31 views)
2014-07-23 20:56:16
List of Learning Resources
by SilverTiger
2014-07-31 18:29:50

List of Learning Resources
by SilverTiger
2014-07-31 18:26:06

List of Learning Resources
by SilverTiger
2014-07-31 13:54:12

HotSpot Options
by dleskov
2014-07-08 03:59:08

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:58:24

Java and Game Development Tutorials
by SwordsMiner
2014-06-14 00:47:22

How do I start Java Game Development?
by ra4king
2014-05-17 11:13:37

HotSpot Options
by Roquen
2014-05-15 09:59:54
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!