Frage

I am trying to parallelize the raytracer im currently working on for university, but i cant quite seem to get it to work. Ive tried multiple implementations, but the problem stays the same.rendering stops after a few milliseconds and at most a small chunk of the picture is rendered.

    final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    long start = System.currentTimeMillis();
    for (int i = 0; i < image.getWidth(); i++) {
        final int ii =i;
        executor.execute(new Runnable() {
            public void run() {
                for (int j = 0; j < image.getHeight(); j++) {
                    raster.setDataElements(ii, image.getHeight()-j-1, model.getDataElements(
                            getPixelColor(width,height,ii,j,world,pcameras2),0, null));
                }
            }
        });
    }
    g.drawImage(this.image, 0, 0, this);
    System.out.println("Rednering finished in: " + (System.currentTimeMillis()-start)/1000.0 + " seconds");
}
public static float[] getPixelColor(final int width,final int height,
        final int x,final int y,final World world,final Camera camera){
    final Hit hit = world.hit(camera.rayFor(width,height, x, y));
    if(hit != null){
        return new float[]{(float) hit.geo.material.ColorFor(hit,world).r,
                (float) hit.geo.material.ColorFor(hit,world).g,(float) hit.geo.material.ColorFor(hit,world).b, 1};
    } else {
        return new float[]{(float) world.backgroundColor.r, (float) world.backgroundColor.g, (float) world.backgroundColor.b, 1};
    }
}

I found out, that if i exlude the world.hit() method it works just fine, but as this contains most of the computation, thats not an option.

War es hilfreich?

Lösung

As explained here, you want to call shutdown to tell the Exector to shutdown after all currently queued tasks have been finished, and then awaitTermination to wait until they are all done.

executor.shutdown();
try {
    executor.awaitTermination(100, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
    // what should happen if timeout was hit
}

// image is complete here (if InterruptedException was not thrown)
g.drawImage(this.image, 0, 0, this);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top