使用线程渲染图像会产生嘈杂的图片

时间:2019-06-26 10:48:23

标签: java multithreading task threadpool runnable

我已经建立了自己的基本光线跟踪器。 我试图优化其性能,所以我考虑使用线程。 当我不使用线程进行渲染时-一切看起来都不错,但是当我尝试使用线程时-我的画面上有一个带有黑色条纹的嘈杂图片。

这是代码。对于每行像素,我创建了一个新的执行程序来计算该行中的像素颜色:

public void renderImage(){
        Camera camera = _scene.get_camera();

        for (int i = 0; i < _imageWriter.getWidth(); ++i){
            final int iFinal = i;

            ExecutorService executor = Executors.newSingleThreadExecutor();
            executor.submit(() -> {
                for (int j = 0; j < _imageWriter.getHeight(); ++j){
                    ArrayList<Ray> rays = camera.constructRaysThroughPixel(
                            _imageWriter.getNx(), _imageWriter.getNy(),
                            iFinal, j, _scene.get_screenDistance(),
                            _imageWriter.getWidth(), _imageWriter.getHeight()
                    );

                    Color color = new Color();
                    for (Ray ray: rays) {

                        ArrayList<GeoPoint> intersectionPoints = _scene.get_geometries().findIntersections(ray);

                        if (intersectionPoints.isEmpty() == true) {
                            color = color.add(_scene.get_background());
                        }
                        else {
                            GeoPoint closestPoint = getClosestPoint(intersectionPoints);

                            color = color.add(new Color(calcColor(closestPoint, new Ray(camera.get_origin(), closestPoint.point.subtract(camera.get_origin())))));
                        }
                    }

                    int length = rays.size();
                    color = color.scale(1.0/length);

                    _imageWriter.writePixel(iFinal, j, color.getColor());

                }
            });
        }
    }

这是我使用线程时得到的: enter image description here

这是我不使用线程时得到的: enter image description here

0 个答案:

没有答案
相关问题