Draws a Horizontal line using the z-buffer algorithm - Java 2D Graphics

Java examples for 2D Graphics:Line

Description

Draws a Horizontal line using the z-buffer algorithm

Demo Code


//package com.java2s;
import java.awt.*;

public class Main {
    /**/*from w w  w.j a v a 2  s .  c om*/
     * Draws a line using the z-buffer algorithm
     * @param gr graphic object
     * @param y y coordinate
     * @param x1 x coordinate of the first vertex
     * @param z1 z coordinate of the first vertex
     * @param x2 x coordinate of the second vertex
     * @param z2 z coordinate of the second vertex
     * @param zbuffer z depth buffer
     */
    public static void drawHorizontalLine(Graphics gr, int y, int x1,
            int z1, int x2, int z2, int[][] zbuffer) {
        int dimX = zbuffer.length;
        int dimY = zbuffer[0].length;
        int difX, difZ;
        int px, pz;

        if (x1 > 0 && x1 < dimX && y > 0 && y < dimY
                && zbuffer[x1][y] >= z1) {
            zbuffer[x1][y] = z1;
            gr.fillRect(x1, y, 1, 1);
        }
        difX = x2 - x1;
        difZ = z2 - z1;

        if (x1 > x2) {
            for (px = x2 + 1; px < x1; px++) {
                pz = z1 + ((px - x1) * difZ / difX);
                if (px > 0 && px < dimX && y > 0 && y < dimY
                        && zbuffer[px][y] >= pz) {
                    zbuffer[px][y] = pz;
                    gr.fillRect(px, y, 1, 1);
                }
            }
        } else {
            for (px = x1 + 1; px < x2; px++) {
                pz = z1 + ((px - x1) * difZ / difX);
                if (px > 0 && px < dimX && y > 0 && y < dimY
                        && zbuffer[px][y] >= pz) {
                    zbuffer[px][y] = pz;
                    gr.fillRect(px, y, 1, 1);
                }
            }
        }

        if (x2 > 0 && x2 < dimX && y > 0 && y < dimY
                && zbuffer[x2][y] >= z2) {
            zbuffer[x2][y] = z2;
            gr.fillRect(x2, y, 1, 1);
        }
    }
}

Related Tutorials