trying to make anaglyph - how to composite

I’m trying to give my game an anaglyph render mode. I’ve created two buffers (one left one right, both as Image) and drawn different things on them, but I can’t find out how to composite them onto a single graphics objects.

I need to draw only the red channel of the left buffer, then draw the blue and green channels of the right buffer on top of that. I’ve searched and searched, but I can only find compositing with AlphaComposite, which doesn’t work per-channel.

Who can help me with my original rendering? ::slight_smile:

so i’ve found a solution, but it’s what you could call “manual work” and slow as ***

                    final BufferedImage leftImg = bufferLeft.getImage();
                    final BufferedImage rightImg = bufferRight.getImage();
                    final BufferedImage comboImg = bufferCombo.getImage();

                    final int[] pxLeft = leftImg.getRGB(0, 0, getWidth(), getHeight(), null, 0, getWidth());
                    final int[] pxRight = rightImg.getRGB(0, 0, getWidth(), getHeight(), null, 0, getWidth());
                    final int[] combo = new int[pxLeft.length];

                    for (int p = 0; p < getWidth() * getHeight(); p++) {
                        combo[p] = (pxLeft[p] & 0xFFFF0000) | (pxRight[p] & 0xFF00FFFF); 
                    }

                    comboImg.setRGB(0, 0, getWidth(), getHeight(), combo, 0, getWidth());
                    graphics.drawImage(bufferCombo, new Point(0, 0));

it also doesn’t quite work, i can see bits of the right image with my left eye, but that’s probably because of my bad 3d glasses

I believe the intended way of doing this would be to define your own Composite.

/docs/api/java/awt/Composite.html

You then perform the pixel composition though the Raster & WritableRaster instances passed to you.

It might be faster than your above implementation, but it certainly won’t be fast.

If you want a lightning fast and simple solution, use OpenGL (using glColorMask).

an interesting note, i’ve done some benchmarking and most time is swallowed by getRGB and secondly by setRGB

anyway, i’ll try those options

It may be faster to access the pixels directly using something like the following.

BufferedImage image = ...;
WritableRaster raster = image.getRaster();
int pixels[] = ((DataBufferInt)(raster.getDataBuffer())).getData();
// now modify the pixels

The array of pixels should be in a similar format to what you’ve got in your example code (but the exact format may depend on how the BufferedImage was created, so be warned!).

Once you’ve modified an image in this way, it won’t be hardware accelerated (unless you copy it to a fresh BufferedImage). I don’t know whether the Composite approach (as Abuse suggests) has the same drawback.

Simon