Search in sources :

Example 1 with SectionVector

use of facetmodeller.sections.SectionVector in project facetmodeller by pglelievre.

the class ModelManager method readSessionInformation.

@Override
public String readSessionInformation(BufferedReader reader, boolean merge) {
    // I need to construct new objects as I read the file:
    PLC plc2 = new PLC();
    SectionVector sections2 = new SectionVector();
    GroupVector groups2 = new GroupVector();
    // Read the number of dimensions, nodes, facets, regions, samples and groups:
    String textLine = FileUtils.readLine(reader);
    if (textLine == null) {
        return "Reading number of dimensions, etc.";
    }
    int ndim, nnodes, nregions, nfacets, nsections, ngroups;
    textLine = textLine.trim();
    String[] ss = textLine.split("[ ]+");
    if (ss.length < 6) {
        return "Not enough values on number of dimensions etc. line.";
    }
    try {
        // converts to integer
        ndim = Integer.parseInt(ss[0].trim());
        // converts to integer
        nnodes = Integer.parseInt(ss[1].trim());
        // converts to integer
        nfacets = Integer.parseInt(ss[2].trim());
        // converts to integer
        nregions = Integer.parseInt(ss[3].trim());
        // converts to integer
        nsections = Integer.parseInt(ss[4].trim());
        // converts to integer
        ngroups = Integer.parseInt(ss[5].trim());
    } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
        return "Parsing number of dimensions, etc.";
    }
    // Check ndim:
    if (ndim != numberOfDimensions()) {
        return "Incorrect number of dimensions.";
    }
    // ---------- IN THE FIRST PASS I READ ALL INFORMATION OTHER THAN ID'S AND CREATE NEW OBJECTS ----------
    // Skip the commented start of node definitions:
    textLine = FileUtils.readLine(reader);
    if (textLine == null) {
        return "Skipping start of node definitions.";
    }
    // Loop over each node:
    for (int i = 0; i < nnodes; i++) {
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            return "Reading node ID etc. line.";
        }
        textLine = textLine.trim();
        ss = textLine.split("[ ]+");
        if (ss.length < 2) {
            return "Not enough values on node ID etc. line.";
        }
        int nodeType;
        boolean bmarker = false;
        try {
            int nodeID = Integer.parseInt(ss[0].trim());
            if (nodeID != i) {
                return "Unmatched node ID";
            }
            nodeType = Integer.parseInt(ss[1].trim());
            if (ss.length > 2) {
                bmarker = Boolean.parseBoolean(ss[2].trim());
            }
        } catch (NumberFormatException e) {
            return "Parsing node ID etc.";
        }
        Node node;
        switch(nodeType) {
            case Node.NODE_ON_SECTION:
                node = new NodeOnSection();
                break;
            case Node.NODE_OFF_SECTION:
                node = new NodeOffSection();
                break;
            default:
                return "Unmatched node type.";
        }
        if (node == null) {
            return "Unexpected empty new Node created.";
        }
        // Set the node boundary marker:
        node.setBoundaryMarker(bmarker);
        // Read the additional information for the node (depends on the node type):
        String msg = node.readSessionInformation(reader, merge);
        if (msg != null) {
            return "Reading information for node " + i + "." + System.lineSeparator() + msg.trim();
        }
        plc2.addNode(node);
    }
    // Loop over each facet:
    for (int i = 0; i < nfacets; i++) {
        // Add a new empty facet to the plc (these facets are filled later):
        plc2.addFacet(new Facet());
    }
    // Skip the commented start of region definitions:
    textLine = FileUtils.readLine(reader);
    if (textLine == null) {
        return "Skipping start of region definitions.";
    }
    // Loop over each region:
    for (int i = 0; i < nregions; i++) {
        // Make a new region object:
        Region region = new Region();
        // Read the region information:
        region.readSessionInformation(reader, merge);
        // Add the region to the plc:
        // section and group membership will be added later
        plc2.addRegion(region);
    }
    // Skip the commented start of section definitions:
    textLine = FileUtils.readLine(reader);
    if (textLine == null) {
        return "Skipping start of section definitions.";
    }
    for (int i = 0; i < nsections; i++) {
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            return "Skipping start of ith section definition.";
        }
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            return "Reading section type.";
        }
        textLine = textLine.trim();
        int sectionType;
        try {
            sectionType = Integer.parseInt(textLine);
        } catch (NumberFormatException e) {
            return "Parsing section type.";
        }
        Section section;
        switch(sectionType) {
            case Section.SECTION_IMAGE_CROSS:
                section = new ImageCrossSection();
                break;
            case Section.SECTION_IMAGE_DEPTH:
                section = new ImageDepthSection();
                break;
            case Section.SECTION_NOIMAGE_CROSS:
                section = new NoImageCrossSection();
                break;
            case Section.SECTION_NOIMAGE_DEPTH:
                section = new NoImageDepthSection();
                break;
            case Section.SECTION_SNAPSHOT:
                section = new SnapshotSection();
                break;
            case Section.SECTION_TOPO:
                // replacement for obsolete TopoSection (.node and .ele file will be read later)
                section = new NoImageDepthSection(true);
                break;
            default:
                return "Unmatched section type.";
        }
        if (section == null) {
            return "Unexpected empty new Section created.";
        }
        String msg = section.readSessionInformation(reader, merge);
        if (msg != null) {
            return "Reading information for section " + i + "." + System.lineSeparator() + msg.trim();
        }
        sections2.add(section);
    }
    // Skip the commented start of group definitions:
    textLine = FileUtils.readLine(reader);
    if (textLine == null) {
        return "Skipping start of group definitions.";
    }
    // Loop over each group:
    for (int i = 0; i < ngroups; i++) {
        // Create a new group object:
        Group group = new Group();
        // Read the group information:
        String msg = group.readSessionInformation(reader, merge);
        if (msg != null) {
            return "Reading information for group" + i + "." + System.lineSeparator() + msg.trim();
        }
        // Add the group to the list of groups:
        groups2.add(group);
    }
    // ---------- IN THE SECOND PASS I READ THE ID'S AND SET THE CROSS-LINKAGES ----------
    // Skip the commented start of node linkages:
    textLine = FileUtils.readLine(reader);
    if (textLine == null) {
        return "Skipping start of node linkages.";
    }
    // Loop over each node:
    for (int i = 0; i < nnodes; i++) {
        Node node = plc2.getNode(i);
        // The node gets linked to the facets in the loop over each facet below.
        // Read the section id and group id:
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            return "Reading node section and group IDs line.";
        }
        textLine = textLine.trim();
        ss = textLine.split("[ ]+");
        if (ss.length < 2) {
            return "Not enough values on node section and group IDs line.";
        }
        // section and group id
        int sid, gid;
        try {
            // converts to integer
            sid = Integer.parseInt(ss[0].trim());
            // converts to integer
            gid = Integer.parseInt(ss[1].trim());
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
            return "Parsing node section and group IDs.";
        }
        // Cross-link the node and section:
        node.setSection(sections2.get(sid));
        sections2.get(sid).addNode(node);
        // Cross-link the node and group:
        node.setGroup(groups2.get(gid));
        groups2.get(gid).addNode(node);
    }
    // Skip the commented start of facet linkages:
    textLine = FileUtils.readLine(reader);
    if (textLine == null) {
        return "Skipping start of facet linkages.";
    }
    // Loop over each facet:
    for (int i = 0; i < nfacets; i++) {
        Facet facet = plc2.getFacet(i);
        // Read the node id's and link those nodes to the facet:
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            return "Reading facet node IDs line.";
        }
        textLine = textLine.trim();
        ss = textLine.split("[ ]+");
        if (ss.length < 1) {
            return "No values on facet node IDs line.";
        }
        // number of nodes
        int n;
        try {
            // converts to integer
            n = Integer.parseInt(ss[0].trim());
        } catch (NumberFormatException e) {
            return "Parsing facet node length.";
        }
        if (ss.length < n + 1) {
            return "Not enough values on facet node IDs line.";
        }
        for (int j = 0; j < n; j++) {
            // node id
            int id;
            try {
                // converts to integer
                id = Integer.parseInt(ss[j + 1].trim());
            } catch (NumberFormatException e) {
                return "Parsing facet node ID.";
            }
            // Cross-link the facet and node:
            facet.addNode(plc2.getNode(id));
            plc2.getNode(id).addFacet(facet);
        }
        // Read the section id's:
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            return "Reading facet section ID line.";
        }
        /*
            textLine = textLine.trim();
            ss = textLine.split("[ ]+");
            if (ss.length<1) { return "No values on facet section ID line."; }
            try {
                n = Integer.parseInt(ss[0].trim()); // converts to integer
            } catch (NumberFormatException e) { return "Parsing facet section length."; }
            if ( ss.length < n+1 ) { return "Not enough values on facet section ID line."; }
            for (int j=0 ; j<n ; j++ ) {
                int id;
                try {
                    id = Integer.parseInt(ss[j+1].trim()); // converts to integer
                } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { return "Parsing facet section ID."; }
                // Cross-link the facet and section:
//                    facet.addSection( sections.get(id) ); // no longer necessary because facet sections defined by the facet nodes
                sections2.get(id).addFacet(facet);
            }
            */
        // Read the group id and boundary marker:
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            return "Reading facet group ID and boundary marker line.";
        }
        textLine = textLine.trim();
        ss = textLine.split("[ ]+");
        if (ss.length < 1) {
            return "No values on facet group ID and boundary marker line.";
        }
        int id;
        boolean bmarker = false;
        try {
            // converts to integer
            id = Integer.parseInt(ss[0].trim());
            if (ss.length > 1) {
                bmarker = Boolean.parseBoolean(ss[1].trim());
            }
        } catch (NumberFormatException e) {
            return "Parsing facet group ID and boundary marker line.";
        }
        // Set the facet boundary marker:
        facet.setBoundaryMarker(bmarker);
        // Cross-link the facet and group:
        facet.setGroup(groups2.get(id));
        groups2.get(id).addFacet(facet);
    }
    // Skip the commented start of region linkages:
    textLine = FileUtils.readLine(reader);
    if (textLine == null) {
        return "Skipping start of region linkages.";
    }
    // Loop over each region:
    for (int i = 0; i < nregions; i++) {
        Region region = plc2.getRegion(i);
        // Read the section id:
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            return "Reading region section ID line.";
        }
        textLine = textLine.trim();
        ss = textLine.split("[ ]+");
        if (ss.length < 1) {
            return "No values on region section ID line.";
        }
        int id;
        try {
            // converts to integer
            id = Integer.parseInt(ss[0].trim());
        } catch (NumberFormatException e) {
            return "Parsing region section ID.";
        }
        // Cross-link the region and section:
        region.setSection(sections2.get(id));
        sections2.get(id).addRegion(region);
        // Read the group id and link that group to the node:
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            return "Reading region group ID line.";
        }
        textLine = textLine.trim();
        ss = textLine.split("[ ]+");
        if (ss.length < 1) {
            return "No values on region group ID line.";
        }
        try {
            // converts to integer
            id = Integer.parseInt(ss[0].trim());
        } catch (NumberFormatException e) {
            return "Parsing region group ID.";
        }
        // Cross-link the region and group:
        region.setGroup(groups2.get(id));
        // groups.get(id).setRegion(region);
        groups2.get(id).addRegion(region);
    }
    // ---------- Read the VOI information: ----------
    // Skip the commented start of the VOI information:
    textLine = FileUtils.readLine(reader);
    if (textLine == null) {
        return "Skipping start of VOI information.";
    }
    // Read the VOI:
    VOI voi2 = new VOI();
    String msg = voi2.readSessionInformation(reader, merge);
    if (msg != null) {
        if (msg.startsWith("Null")) {
            // Assume encountered line with "null" in it:
            voi2 = null;
        } else {
            return msg;
        }
    }
    // If overwriting then set existing information to new information, otherwise combine the information:
    if (merge) {
        // Don't change the VOI!
        plc.addAll(plc2);
        groups.addAll(groups2);
    } else {
        // these aren't necessary because the garbage collection should deal with them
        plc.clear();
        groups.clear();
        voi = voi2;
        plc = plc2;
        groups = groups2;
    }
    if (merge && ndim == 3) {
        sections.addAll(sections2);
    } else {
        sections.clear();
        sections = sections2;
    }
    // Return successfully:
    return null;
}
Also used : SectionVector(facetmodeller.sections.SectionVector) Group(facetmodeller.groups.Group) NoImageDepthSection(facetmodeller.sections.NoImageDepthSection) PLC(facetmodeller.plc.PLC) Node(facetmodeller.plc.Node) NodeOffSection(facetmodeller.plc.NodeOffSection) NodeOnSection(facetmodeller.plc.NodeOnSection) NoImageCrossSection(facetmodeller.sections.NoImageCrossSection) NodeOffSection(facetmodeller.plc.NodeOffSection) NoImageDepthSection(facetmodeller.sections.NoImageDepthSection) Section(facetmodeller.sections.Section) ImageCrossSection(facetmodeller.sections.ImageCrossSection) SnapshotSection(facetmodeller.sections.SnapshotSection) NodeOnSection(facetmodeller.plc.NodeOnSection) ImageDepthSection(facetmodeller.sections.ImageDepthSection) NoImageDepthSection(facetmodeller.sections.NoImageDepthSection) ImageDepthSection(facetmodeller.sections.ImageDepthSection) GroupVector(facetmodeller.groups.GroupVector) NoImageCrossSection(facetmodeller.sections.NoImageCrossSection) ImageCrossSection(facetmodeller.sections.ImageCrossSection) Region(facetmodeller.plc.Region) NoImageCrossSection(facetmodeller.sections.NoImageCrossSection) SnapshotSection(facetmodeller.sections.SnapshotSection) Facet(facetmodeller.plc.Facet)

Example 2 with SectionVector

use of facetmodeller.sections.SectionVector in project facetmodeller by pglelievre.

the class ModelManager method writeSessionInformation.

@Override
public boolean writeSessionInformation(BufferedWriter writer) {
    // Write the number of dimensions, nodes, facets, regions, sections and groups:
    int ndim = numberOfDimensions();
    int nnodes = numberOfNodes();
    int nfacets = numberOfFacets();
    int nregions = numberOfRegions();
    int nsections = numberOfSections();
    int ngroups = numberOfGroups();
    String textLine = ndim + " " + nnodes + " " + nfacets + " " + nregions + " " + nsections + " " + ngroups;
    if (!FileUtils.writeLine(writer, textLine)) {
        return false;
    }
    // Comment start of node definitions:
    if (!FileUtils.writeLine(writer, "# NODES")) {
        return false;
    }
    // Loop over each node:
    for (int i = 0; i < nnodes; i++) {
        Node node = getNode(i);
        // Write node ID, indication of ith node type and boundary marker (the latter is a later addition):
        textLine = node.getID() + " " + node.getType() + " " + node.getBoundaryMarker();
        if (!FileUtils.writeLine(writer, textLine)) {
            return false;
        }
        // Write the node information:
        if (!node.writeSessionInformation(writer)) {
            return false;
        }
    }
    // Comment start of region definitions:
    if (!FileUtils.writeLine(writer, "# REGIONS")) {
        return false;
    }
    // Loop over each region:
    for (int i = 0; i < nregions; i++) {
        Region region = getRegion(i);
        // Write the region information information:
        if (!region.writeSessionInformation(writer)) {
            return false;
        }
    }
    // Comment start of section definitions:
    if (!FileUtils.writeLine(writer, "# SECTIONS")) {
        return false;
    }
    // Loop over each section:
    for (int i = 0; i < nsections; i++) {
        Section section = getSection(i);
        // Comment start of ith section definition:
        textLine = "# Section " + section.getID();
        if (!FileUtils.writeLine(writer, textLine)) {
            return false;
        }
        // Write indication of the type of section:
        textLine = Integer.toString(section.getType());
        if (!FileUtils.writeLine(writer, textLine)) {
            return false;
        }
        // Write the section information:
        if (!section.writeSessionInformation(writer)) {
            return false;
        }
    }
    // Comment start of group definitions:
    if (!FileUtils.writeLine(writer, "# GROUPS")) {
        return false;
    }
    // Loop over each group:
    for (int i = 0; i < ngroups; i++) {
        Group group = getGroup(i);
        // Write the group information:
        if (!group.writeSessionInformation(writer)) {
            return false;
        }
    }
    // Comment start of node linkages:
    if (!FileUtils.writeLine(writer, "# NODE LINKS")) {
        return false;
    }
    // Loop over each node:
    for (int i = 0; i < nnodes; i++) {
        Node node = getNode(i);
        // FacetVector facets = node.getFacets();
        /* I don't need to write the facet id's here because
             * the same information is written below in the loop over each facet. */
        // Write the section id and group id:
        textLine = node.getSection().getID() + " " + node.getGroup().getID();
        if (!FileUtils.writeLine(writer, textLine)) {
            return false;
        }
    }
    // Comment start of node linkages:
    if (!FileUtils.writeLine(writer, "# FACET LINKS")) {
        return false;
    }
    // Loop over each facet:
    for (int i = 0; i < nfacets; i++) {
        Facet facet = getFacet(i);
        NodeVector nodes = facet.getNodes();
        SectionVector facetSections = facet.getSections();
        // Write the node id's:
        int n = nodes.size();
        textLine = Integer.toString(n);
        for (int j = 0; j < n; j++) {
            textLine = textLine + " " + nodes.get(j).getID();
        }
        if (!FileUtils.writeLine(writer, textLine)) {
            return false;
        }
        // Write the section id's:
        n = facetSections.size();
        textLine = Integer.toString(n);
        for (int j = 0; j < n; j++) {
            textLine = textLine + " " + facetSections.get(j).getID();
        }
        if (!FileUtils.writeLine(writer, textLine)) {
            return false;
        }
        // Write the group id and boundary marker (the latter is a later addition):
        textLine = facet.getGroup().getID() + " " + facet.getBoundaryMarker();
        if (!FileUtils.writeLine(writer, textLine)) {
            return false;
        }
    }
    // Comment start of node linkages:
    if (!FileUtils.writeLine(writer, "# REGION LINKS")) {
        return false;
    }
    // Loop over each region:
    for (int i = 0; i < nregions; i++) {
        Region region = getRegion(i);
        // Write the section id:
        textLine = Integer.toString(region.getSection().getID());
        if (!FileUtils.writeLine(writer, textLine)) {
            return false;
        }
        // Write the group id:
        textLine = Integer.toString(region.getGroup().getID());
        if (!FileUtils.writeLine(writer, textLine)) {
            return false;
        }
    }
    // Comment start of VOI information:
    if (!FileUtils.writeLine(writer, "# VOI")) {
        return false;
    }
    // Write the VOI:
    if (hasVOI()) {
        if (!getVOI().writeSessionInformation(writer)) {
            return false;
        }
    } else {
        if (!FileUtils.writeLine(writer, "null")) {
            return false;
        }
    }
    // Return true:
    return true;
}
Also used : Group(facetmodeller.groups.Group) SectionVector(facetmodeller.sections.SectionVector) NodeVector(facetmodeller.plc.NodeVector) Node(facetmodeller.plc.Node) Region(facetmodeller.plc.Region) NoImageCrossSection(facetmodeller.sections.NoImageCrossSection) NodeOffSection(facetmodeller.plc.NodeOffSection) NoImageDepthSection(facetmodeller.sections.NoImageDepthSection) Section(facetmodeller.sections.Section) ImageCrossSection(facetmodeller.sections.ImageCrossSection) SnapshotSection(facetmodeller.sections.SnapshotSection) NodeOnSection(facetmodeller.plc.NodeOnSection) ImageDepthSection(facetmodeller.sections.ImageDepthSection) Facet(facetmodeller.plc.Facet)

Example 3 with SectionVector

use of facetmodeller.sections.SectionVector in project facetmodeller by pglelievre.

the class SessionLoader method loadSessionAscii2.

private static boolean loadSessionAscii2(FacetModeller controller, File file, boolean merge) {
    int loadVersion = 2;
    // We will be constructing some new objects as we read the file:
    PLC plc = new PLC();
    SectionVector sections = new SectionVector();
    GroupVector groups = new GroupVector();
    // We will be saving some information to set later:
    int ndim;
    // these colours will be overwritten
    Color calibrationColor = Color.CYAN;
    Color edgeColor = Color.BLACK;
    Color defineFacetEdgeColor = Color.WHITE;
    int pointWidth = 5;
    int lineWidth = 1;
    // Open the file for reading:
    BufferedReader reader = FileUtils.openForReading(file);
    if (reader == null) {
        return false;
    }
    // Put everything below in an infinite loop that we can break out of when something goes wrong:
    boolean ok = true;
    while (true) {
        // Read the floored version number:
        String textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            ok = false;
            break;
        }
        textLine = textLine.trim();
        String[] ss = textLine.split("[ ]+", 2);
        int version;
        try {
            // converts to integer
            version = Integer.parseInt(ss[0].trim());
        } catch (NumberFormatException e) {
            ok = false;
            break;
        }
        if (!ok) {
            break;
        }
        // Check the version number:
        if (version != loadVersion) {
            // Close the file:
            FileUtils.close(reader);
            // Return unsuccessfully:
            return false;
        }
        // Read the number of dimensions, nodes, facets, regions, samples and groups:
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            ok = false;
            break;
        }
        int nnodes, nregions, nfacets, nsections, ngroups;
        textLine = textLine.trim();
        ss = textLine.split("[ ]+", 7);
        try {
            // converts to integer
            ndim = Integer.parseInt(ss[0].trim());
            // converts to integer
            nnodes = Integer.parseInt(ss[1].trim());
            // converts to integer
            nfacets = Integer.parseInt(ss[2].trim());
            // converts to integer
            nregions = Integer.parseInt(ss[3].trim());
            // converts to integer
            nsections = Integer.parseInt(ss[4].trim());
            // converts to integer
            ngroups = Integer.parseInt(ss[5].trim());
        } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
            ok = false;
            break;
        }
        if (!ok) {
            break;
        }
        // Check ndim:
        if (ndim != controller.numberOfDimensions()) {
            ok = false;
            break;
        }
        // Loop over each node:
        for (int i = 0; i < nnodes; i++) {
            // Read the coordinates of the ith node:
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            boolean isTopo;
            // initialization of z is needed to avoid compiler warning
            double x, y, z = 0.0;
            textLine = textLine.trim();
            ss = textLine.split("[ ]+", 4);
            try {
                isTopo = Boolean.parseBoolean(ss[0].trim());
                // converts to Double
                x = Double.parseDouble(ss[1].trim());
                // converts to Double
                y = Double.parseDouble(ss[2].trim());
                if (isTopo) {
                    z = Double.parseDouble(ss[3].trim());
                }
            } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                ok = false;
                break;
            }
            if (!ok) {
                break;
            }
            // Add a new node to the plc:
            if (isTopo) {
                plc.addNode(new NodeOffSection(x, y, z));
            } else {
                plc.addNode(new NodeOnSection(x, y));
            }
        // section and group membership will be added later
        }
        if (!ok) {
            break;
        }
        // Loop over each facet:
        for (int i = 0; i < nfacets; i++) {
            // Add a new empty facet to the plc (these facets are filled later):
            plc.addFacet(new Facet());
        }
        // Loop over each region:
        for (int i = 0; i < nregions; i++) {
            // Read the coordinates of the ith region and the isControl information:
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            double x, y;
            boolean isCon;
            textLine = textLine.trim();
            ss = textLine.split("[ ]+", 4);
            // Try parsing coordinates (must be able to do this):
            try {
                // converts to Double
                x = Double.parseDouble(ss[0].trim());
                // converts to Double
                y = Double.parseDouble(ss[1].trim());
            } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                ok = false;
                break;
            }
            if (!ok) {
                break;
            }
            // Check for iscontrol information:
            if (ss.length < 3) {
                isCon = false;
            } else {
                if (ss[2].trim().isEmpty()) {
                    // missing from file (old version of session saver was used)
                    isCon = false;
                } else {
                    // converts to Boolean
                    isCon = Boolean.parseBoolean(ss[2].trim());
                }
            }
            // Add a new region to the plc:
            // section and group membership will be added later
            plc.addRegion(new Region(isCon, x, y));
        }
        if (!ok) {
            break;
        }
        for (int i = 0; i < nsections; i++) {
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            int sectionType;
            try {
                sectionType = Integer.parseInt(textLine);
            } catch (NumberFormatException e) {
                ok = false;
                break;
            }
            if (!ok) {
                break;
            }
            Section section = null;
            switch(sectionType) {
                case 1:
                    // Read the file name:
                    textLine = FileUtils.readLine(reader);
                    if (textLine == null) {
                        ok = false;
                        break;
                    }
                    textLine = textLine.trim();
                    File imageFile;
                    if (textLine.startsWith("null")) {
                        imageFile = null;
                    } else {
                        try {
                            URI uri = new URI(textLine);
                            // image file or .node file
                            imageFile = new File(uri);
                        } catch (URISyntaxException e) {
                            ok = false;
                            break;
                        }
                    }
                    // Make a new HasImage object associated with the file:
                    section = new ImageCrossSection(imageFile);
                    break;
                case 3:
                    // Read the section name:
                    textLine = FileUtils.readLine(reader);
                    if (textLine == null) {
                        ok = false;
                        break;
                    }
                    String name = textLine.trim();
                    // Read the image height:
                    textLine = FileUtils.readLine(reader);
                    if (textLine == null) {
                        ok = false;
                        break;
                    }
                    textLine = textLine.trim();
                    int height;
                    try {
                        height = Integer.parseInt(textLine);
                    } catch (NumberFormatException e) {
                        ok = false;
                        break;
                    }
                    // Read the image color:
                    Color color;
                    try {
                        // parse from RGB string
                        color = new Color(Integer.parseInt(textLine.trim()));
                    } catch (NumberFormatException e) {
                        ok = false;
                        break;
                    }
                    section = new NoImageCrossSection(name, color);
                    break;
                case 2:
                    File nodeFile = null;
                    File eleFile = null;
                    // Read the node file name:
                    textLine = FileUtils.readLine(reader);
                    if (textLine == null) {
                        ok = false;
                        break;
                    }
                    textLine = textLine.trim();
                    if (textLine.startsWith("null")) {
                        nodeFile = null;
                    } else {
                        URI uri = null;
                        try {
                            uri = new URI(textLine);
                        } catch (URISyntaxException e) {
                            ok = false;
                        }
                        if (!ok) {
                            break;
                        }
                        try {
                            // image file or .node file
                            nodeFile = new File(uri);
                        } catch (IllegalArgumentException e) {
                            ok = false;
                        }
                    }
                    if (!ok) {
                        break;
                    }
                    // Read the ele file name:
                    textLine = FileUtils.readLine(reader);
                    if (textLine == null) {
                        ok = false;
                        break;
                    }
                    textLine = textLine.trim();
                    if (textLine.startsWith("null")) {
                        eleFile = null;
                    } else {
                        try {
                            URI uri = new URI(textLine);
                            // image file or .node file
                            eleFile = new File(uri);
                        } catch (URISyntaxException e) {
                            ok = false;
                        }
                    }
                    if (!ok) {
                        break;
                    }
                    // formerly a TopoSection
                    section = new NoImageDepthSection(nodeFile, eleFile);
                    break;
                default:
                    ok = false;
                    break;
            }
            if (!ok) {
                break;
            }
            if (section == null) {
                ok = false;
                break;
            }
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            ss = textLine.split("[ ]+", 2);
            Dir3D sliceDirection;
            try {
                // converts to integer
                int idir = Integer.parseInt(ss[0].trim());
                sliceDirection = Dir3D.fromInt(idir);
            } catch (NumberFormatException e) {
                ok = false;
                break;
            }
            if (!ok) {
                break;
            }
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            ss = textLine.split("[ ]+", 2);
            double loc;
            try {
                // converts to Double
                loc = Double.parseDouble(ss[0].trim());
            } catch (NumberFormatException e) {
                ok = false;
                break;
            }
            if (!ok) {
                break;
            }
            double x, y;
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            if (!textLine.startsWith("null")) {
                ss = textLine.split("[ ]+", 3);
                try {
                    // converts to Double
                    x = Double.parseDouble(ss[0].trim());
                    // converts to Double
                    y = Double.parseDouble(ss[1].trim());
                } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                    ok = false;
                    break;
                }
                if (!ok) {
                    break;
                }
                section.setTyped1(new MyPoint3D(x, y, sliceDirection, loc));
            }
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            if (!textLine.startsWith("null")) {
                ss = textLine.split("[ ]+", 3);
                try {
                    // converts to Double
                    x = Double.parseDouble(ss[0].trim());
                    // converts to Double
                    y = Double.parseDouble(ss[1].trim());
                } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                    ok = false;
                    break;
                }
                if (!ok) {
                    break;
                }
                section.setTyped2(new MyPoint3D(x, y, sliceDirection, loc));
            }
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            if (!textLine.startsWith("null")) {
                ss = textLine.split("[ ]+", 3);
                try {
                    // converts to Double
                    x = Double.parseDouble(ss[0].trim());
                    // converts to Double
                    y = Double.parseDouble(ss[1].trim());
                } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                    ok = false;
                    break;
                }
                if (!ok) {
                    break;
                }
                section.setClicked1(new MyPoint2D(x, y));
            }
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            if (!textLine.startsWith("null")) {
                ss = textLine.split("[ ]+", 3);
                try {
                    // converts to Double
                    x = Double.parseDouble(ss[0].trim());
                    // converts to Double
                    y = Double.parseDouble(ss[1].trim());
                } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                    ok = false;
                    break;
                }
                if (!ok) {
                    break;
                }
                section.setClicked2(new MyPoint2D(x, y));
            }
            sections.add(section);
        }
        if (!ok) {
            break;
        }
        // Loop over each group:
        for (int i = 0; i < ngroups; i++) {
            // Create the group object:
            Group group = new Group();
            // Read the group name:
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            group.setName(textLine.trim());
            // Read the group colours:
            Color col;
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            try {
                // parse from RGB string
                col = new Color(Integer.parseInt(textLine.trim()));
            } catch (NumberFormatException e) {
                ok = false;
                break;
            }
            group.setNodeColor(col);
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            try {
                // parse from RGB string
                col = new Color(Integer.parseInt(textLine.trim()));
            } catch (NumberFormatException e) {
                ok = false;
                break;
            }
            group.setFacetColor(col);
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            try {
                // parse from RGB string
                col = new Color(Integer.parseInt(textLine.trim()));
            } catch (NumberFormatException e) {
                ok = false;
                break;
            }
            group.setRegionColor(col);
            // Add the group to the list of groups:
            groups.add(group);
        }
        if (!ok) {
            break;
        }
        // Loop over each node:
        for (int i = 0; i < nnodes; i++) {
            Node node = plc.getNode(i);
            // The node gets linked to the facets in the loop over each facet below.
            // Read the section id and group id:
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            ss = textLine.split("[ ]+", 3);
            // section and group id
            int sid, gid;
            try {
                // converts to integer
                sid = Integer.parseInt(ss[0].trim());
                // converts to integer
                gid = Integer.parseInt(ss[1].trim());
            } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                ok = false;
                break;
            }
            // Cross-link the node and section:
            node.setSection(sections.get(sid));
            sections.get(sid).addNode(node);
            // Cross-link the node and group:
            node.setGroup(groups.get(gid));
            groups.get(gid).addNode(node);
        }
        if (!ok) {
            break;
        }
        // Loop over each facet:
        for (int i = 0; i < nfacets; i++) {
            Facet facet = plc.getFacet(i);
            // Read the node id's and link those nodes to the facet:
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            ss = textLine.split("[ ]+");
            // number of nodes
            int n;
            try {
                // converts to integer
                n = Integer.parseInt(ss[0].trim());
            } catch (NumberFormatException e) {
                ok = false;
                break;
            }
            if (!ok) {
                break;
            }
            for (int j = 0; j < n; j++) {
                // node id
                int id;
                try {
                    // converts to integer
                    id = Integer.parseInt(ss[j + 1].trim());
                } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
                    ok = false;
                    break;
                }
                // Cross-link the facet and node:
                facet.addNode(plc.getNode(id));
                plc.getNode(id).addFacet(facet);
            }
            // Read the section id's:
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            /*
                textLine = textLine.trim();
                ss = textLine.split("[ ]+");
                try {
                    n = Integer.parseInt(ss[0].trim()); // converts to integer
                } catch (NumberFormatException e) { ok=false; break; }
                if (!ok) { break; }
                for (int j=0 ; j<n ; j++ ) {
                    int id;
                    try {
                        id = Integer.parseInt(ss[j+1].trim()); // converts to integer
                    } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { ok=false; break; }
                    // Cross-link the facet and section:
//                    facet.addSection( sections.get(id) ); // no longer necessary because facet sections defined by the facet nodes
                    sections.get(id).addFacet(facet);
                }
                */
            // Read the group id:
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            ss = textLine.split("[ ]+", 2);
            int id;
            try {
                // converts to integer
                id = Integer.parseInt(ss[0].trim());
            } catch (NumberFormatException e) {
                ok = false;
                break;
            }
            // Cross-link the facet and group:
            facet.setGroup(groups.get(id));
            groups.get(id).addFacet(facet);
        }
        if (!ok) {
            break;
        }
        // Loop over each region:
        for (int i = 0; i < nregions; i++) {
            Region region = plc.getRegion(i);
            // Read the section id:
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            ss = textLine.split("[ ]+", 2);
            int id;
            try {
                // converts to integer
                id = Integer.parseInt(ss[0].trim());
            } catch (NumberFormatException e) {
                ok = false;
                break;
            }
            // Cross-link the region and section:
            region.setSection(sections.get(id));
            sections.get(id).addRegion(region);
            // Read the group id and link that group to the node:
            textLine = FileUtils.readLine(reader);
            if (textLine == null) {
                ok = false;
                break;
            }
            textLine = textLine.trim();
            ss = textLine.split("[ ]+", 2);
            try {
                // converts to integer
                id = Integer.parseInt(ss[0].trim());
            } catch (NumberFormatException e) {
                ok = false;
                break;
            }
            // Cross-link the region and group:
            region.setGroup(groups.get(id));
            // groups.get(id).setRegion(region);
            groups.get(id).addRegion(region);
        }
        if (!ok) {
            break;
        }
        // ---------- Finish with the rest of the information: ----------
        // Read painting colours, etc.:
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            ok = false;
            break;
        }
        try {
            // parse from RGB string
            calibrationColor = new Color(Integer.parseInt(textLine.trim()));
        } catch (NumberFormatException e) {
            ok = false;
            break;
        }
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            ok = false;
            break;
        }
        try {
            // parse from RGB string
            edgeColor = new Color(Integer.parseInt(textLine.trim()));
        } catch (NumberFormatException e) {
            ok = false;
            break;
        }
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            ok = false;
            break;
        }
        try {
            // parse from RGB string
            defineFacetEdgeColor = new Color(Integer.parseInt(textLine.trim()));
        } catch (NumberFormatException e) {
            ok = false;
            break;
        }
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            ok = false;
            break;
        }
        try {
            pointWidth = Integer.parseInt(textLine.trim());
        } catch (NumberFormatException e) {
            ok = false;
            break;
        }
        textLine = FileUtils.readLine(reader);
        if (textLine == null) {
            ok = false;
            break;
        }
        try {
            lineWidth = Integer.parseInt(textLine.trim());
        } catch (NumberFormatException e) {
            ok = false;
            break;
        }
        // Always break from while here:
        break;
    }
    // Close the file:
    FileUtils.close(reader);
    // Check for a problem:
    if (!ok) {
        return false;
    }
    // Reset the FacetModeller plc, section lists and group lists:
    controller.resetPLC(plc, merge);
    controller.resetSectionVector(sections, merge);
    controller.resetGroupVector(groups, merge);
    // If it is a large model then don't display anything:
    if (plc.numberOfNodes() >= LARGE_MODEL) {
        controller.clearGroupSelections();
    }
    // Reset some other information:
    if (!merge) {
        controller.setCalibrationColor(calibrationColor);
        controller.setEdgeColor(edgeColor);
        controller.setDefineFacetEdgeColor(defineFacetEdgeColor);
        controller.setPointWidth(pointWidth);
        controller.setLineWidth(lineWidth);
    }
    // Return successfully:
    return true;
}
Also used : SectionVector(facetmodeller.sections.SectionVector) Group(facetmodeller.groups.Group) NoImageDepthSection(facetmodeller.sections.NoImageDepthSection) PLC(facetmodeller.plc.PLC) Node(facetmodeller.plc.Node) URISyntaxException(java.net.URISyntaxException) NodeOnSection(facetmodeller.plc.NodeOnSection) URI(java.net.URI) MyPoint3D(geometry.MyPoint3D) NoImageCrossSection(facetmodeller.sections.NoImageCrossSection) Facet(facetmodeller.plc.Facet) Color(java.awt.Color) NodeOffSection(facetmodeller.plc.NodeOffSection) Section(facetmodeller.sections.Section) NoImageCrossSection(facetmodeller.sections.NoImageCrossSection) ImageCrossSection(facetmodeller.sections.ImageCrossSection) NodeOffSection(facetmodeller.plc.NodeOffSection) NodeOnSection(facetmodeller.plc.NodeOnSection) NoImageDepthSection(facetmodeller.sections.NoImageDepthSection) MyPoint2D(geometry.MyPoint2D) Dir3D(geometry.Dir3D) GroupVector(facetmodeller.groups.GroupVector) NoImageCrossSection(facetmodeller.sections.NoImageCrossSection) ImageCrossSection(facetmodeller.sections.ImageCrossSection) BufferedReader(java.io.BufferedReader) Region(facetmodeller.plc.Region) File(java.io.File)

Example 4 with SectionVector

use of facetmodeller.sections.SectionVector in project facetmodeller by pglelievre.

the class View3DPanel method paintComponent.

// -------------------- Overridden Methods --------------------
/**
 * Paints graphics on the panel.
 * @param g Graphics context in which to draw.
 */
@Override
public void paintComponent(Graphics g) {
    // Only draw 3D if panel is open and ndim==3:
    if (!controller.is3D() || !controller.getShowView3DPanel()) {
        return;
    }
    // Remove image from the panel:
    // removeAll();
    // updateUI();
    // Make sure the drawn flag is false:
    drawn = false;
    // Paint background:
    super.paintComponent(g);
    // Clear the list of projected nodes:
    projectedPoints = null;
    // Calculate the properties required for projection:
    SceneInfo info = controller.getSceneInfo3D();
    // no voi or no nodes in plc
    if (info == null) {
        return;
    }
    if (info.getScaling() == 0.0) {
        return;
    }
    MyPoint3D spaceOrigin = info.getOrigin();
    projector.setSpaceOrigin(spaceOrigin);
    if (spaceOrigin == null) {
        return;
    }
    // panel width
    int w = getWidth();
    // panel height
    int h = getHeight();
    double x = w;
    double y = h;
    // smallest panel dimension
    double imageSizeScaling = Math.min(x, y);
    // half panel width
    x /= 2.0;
    // half panel height
    y /= 2.0;
    // radius of circle surrounding the panel
    double r = Math.sqrt(x * x + y * y);
    MyPoint3D imageOrigin = new MyPoint3D(x, y, 0.0);
    // imageOrigin.plus(controller.getPanX3D(),controller.getPanY3D(),0); // this does the panning via pan buttons
    // this does the panning via dragging
    imageOrigin.plus(getPanX(), getPanY(), 0);
    projector.setImageOrigin(imageOrigin);
    double sceneAndZoomScaling = info.getScaling() * zoomer.getScaling();
    if (sceneAndZoomScaling == 0.0) {
        return;
    }
    if (imageSizeScaling == 0.0) {
        return;
    }
    projector.setSceneAndZoomScaling(sceneAndZoomScaling);
    projector.setImageSizeScaling(imageSizeScaling);
    dragSphere = new Circle(0, 0, r);
    // Project all the nodes and reset the node IDs:
    ModelManager model = controller.getModelManager();
    int n = model.numberOfNodes();
    projectedPoints = new MyPoint3D[n];
    for (int i = 0; i < n; i++) {
        // loop over each node
        Node node = model.getNode(i);
        // Set the node ID equal to i so I can use the ID's as indices into the projectedPoints array:
        node.setID(i);
        // Transform the point to image coordinates:
        MyPoint3D p3 = node.getPoint3D();
        MyPoint3D p;
        if (p3 == null) {
            // section not calibrated
            p = null;
        } else {
            // p is a deep copy of node.getPoint3D()
            p = spaceToImage(p3);
        }
        // Save the transformed point in the list:
        projectedPoints[i] = p;
    }
    // If rotating then I'll only draw minimal information using 2D graphics,
    // otherwise I'll draw everything using a zbuffer. I'll deal with this below
    // by checking the status of the pt1 variable. I'll need some common information first:
    // boolean showOther = controller.getShowOther(); // if true then draws outlines around other sections
    // if true then draws outlines around other sections
    boolean showOutlines = controller.getShowSectionOutlines();
    // if false then only show nodes/facets associated with selected section(s)
    boolean showAll = controller.getShowAllSections();
    // Get drawing styles for overlays:
    final int edgeWidth = controller.getLineWidth();
    final int nodeWidth = controller.getPointWidth();
    // final int centroidWidth = (int)Math.ceil(nodeWidth/2.0); // centroids drawn half the node width
    final double normalLength = controller.getNormalLength();
    final Color normalCol = controller.getNormalColor();
    boolean normalThick = controller.getNormalThick();
    boolean edgeThick = controller.getEdgeThick();
    final int normalWidth;
    if (normalThick) {
        normalWidth = 8;
    } else {
        normalWidth = 4;
    }
    // Initialize the zbuffer or Graphics2D object:
    Graphics2D g2 = (Graphics2D) g;
    MyPoint3D pt1 = getPt1();
    if (pt1 == null) {
        zbuf = new ZBuffer3D(w, h, -Double.MAX_VALUE, getBackground());
    } else {
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // g2.setStroke(new BasicStroke(edgeWidth)); // line style for facet edges
        w = nodeWidth;
    }
    // Get the other section(s) being displayed (if any exist):
    Section currentSection = controller.getSelectedCurrentSection();
    SectionVector otherSections;
    // if ( showOther || showAll ) {
    if (showOutlines || showAll) {
        otherSections = controller.getSelectedOtherSections();
    } else {
        otherSections = null;
    }
    // Get the drawing options for colouring the nodes and facets:
    int nodeColorBy = controller.getNodeColorBy();
    int facetColorBy = controller.getFacetColorBy();
    // Add facets to the scene: (this should be done first so that
    // z-buffering can't draw a facet edge over a node)
    boolean showFaces = controller.getShowFaces();
    boolean showNormals = controller.getShowNormals();
    boolean showNormalTails = controller.getShowNormalTails();
    boolean showNormalHeads = controller.getShowNormalHeads();
    if (pt1 == null) {
        GroupVector facetGroups = controller.getSelectedFacetGroups();
        if (facetGroups != null) {
            for (int i = 0; i < facetGroups.size(); i++) {
                // loop over each group of facets to display
                Group group = facetGroups.get(i);
                FacetVector facets = group.getFacets();
                for (int j = 0; j < facets.size(); j++) {
                    // loop over each facet in the group
                    Facet facet = facets.get(j);
                    // Make sure that all the nodes in the facet are calibrated:
                    NodeVector nodes = facet.getNodes();
                    int nn = nodes.size();
                    // only 3D facets are drawn
                    if (nn < 3) {
                        continue;
                    }
                    boolean ok = true;
                    for (int k = 0; k < nn; k++) {
                        // loop over each node in the facet
                        Node node = nodes.get(k);
                        MyPoint3D p = node.getPoint3D();
                        // if the node's section is not calibrated
                        if (p == null) {
                            ok = false;
                            break;
                        }
                        if (!showAll) {
                            // Make sure the facet belongs to no other sections than those selected:
                            Section s = node.getSection();
                            // shouldn't be possible
                            if (s == null) {
                                ok = false;
                                break;
                            }
                            if (!s.equals(currentSection) && otherSections != null && !otherSections.contains(s)) {
                                ok = false;
                                break;
                            }
                        }
                    }
                    if (!ok) {
                        continue;
                    }
                    // Place the required transformed points into a new object:
                    n = facet.size();
                    MyPoint3D[] pts = new MyPoint3D[n];
                    for (int k = 0; k < n; k++) {
                        // loop over each node in the facet
                        // index into projectedPoints
                        int id = facet.getNode(k).getID();
                        pts[k] = projectedPoints[id];
                        if (pts[k] == null) {
                            // node is behind camera, or its section is not calibrated, so don't paint the facet
                            ok = false;
                            break;
                        }
                    }
                    if (!ok) {
                        continue;
                    }
                    // Calculate the shading:
                    MyPoint3D v = facet.getNormal();
                    if (v == null) {
                        continue;
                    }
                    // normalized
                    v = v.deepCopy();
                    if (v == null) {
                        continue;
                    }
                    // rotated into projected coordinates
                    v.rotate(projector.getRotationMatrix());
                    // dotted with the z axis (direction not important)
                    double d = Math.abs(v.getZ());
                    // too dark otherwise
                    d = 1.0 - (1.0 - d) * 0.8;
                    // Determine the painting colour for the facet:
                    Color col = getFacetPaintingColor(facetColorBy, facet);
                    // Apply the shading to the painting colour:
                    float[] hsb = new float[3];
                    Color.RGBtoHSB(col.getRed(), col.getGreen(), col.getBlue(), hsb);
                    // d is on [0,1]
                    hsb[2] *= (float) d;
                    col = Color.getHSBColor(hsb[0], hsb[1], hsb[2]);
                    // Process the facet through the zbuffer:
                    Color faceCol = null;
                    Color edgeCol;
                    if (showFaces) {
                        // Paint facet face as a coloured patch and paint edges as user requests:
                        faceCol = col;
                        edgeCol = controller.getEdgeColor();
                    } else {
                        // Paint edges of facet only, using facet colour:
                        // faceColor = null;
                        edgeCol = col;
                    }
                    zbuf.putFacet(pts, faceCol, edgeCol, edgeThick);
                    // Draw the facet normals:
                    if (showNormals) {
                        // Set up the points on either end of the normal vector line:
                        // facet centroid (point at start of normal vector line)
                        MyPoint3D p0 = facet.getCentroid().deepCopy();
                        if (p0 == null) {
                            continue;
                        }
                        // normalized normal vector (length of one)
                        MyPoint3D p1 = facet.getNormal().deepCopy();
                        if (p1 == null) {
                            continue;
                        }
                        // normal vector of spatial length normalLength
                        p1.times(normalLength);
                        // point at end of normal vector line
                        p1.plus(p0);
                        // Transform the points to image coordinates:
                        p0 = spaceToImage(p0);
                        p1 = spaceToImage(p1);
                        if (p0 == null) {
                            continue;
                        }
                        if (p1 == null) {
                            continue;
                        }
                        // Draw normal vectors as line objects:
                        if (pt1 == null) {
                            zbuf.putEdge(p0, p1, normalCol, normalThick);
                            // point at normal tail
                            if (showNormalTails) {
                                zbuf.putNode(p0, normalCol, normalWidth);
                            }
                            // point at normal head
                            if (showNormalHeads) {
                                zbuf.putNode(p1, normalCol, normalWidth);
                            }
                        } else {
                            g2.setPaint(normalCol);
                            g2.drawLine((int) p0.getX(), (int) p0.getY(), (int) p1.getX(), (int) p1.getY());
                            // circle at normal tail
                            if (showNormalTails) {
                                g2.fillOval((int) p0.getX() - normalWidth / 2, (int) p0.getY() - normalWidth / 2, normalWidth, normalWidth);
                            }
                            // circle at normal head
                            if (showNormalHeads) {
                                g2.fillOval((int) p1.getX() - normalWidth / 2, (int) p1.getY() - normalWidth / 2, normalWidth, normalWidth);
                            }
                        }
                    }
                }
            // for j
            }
        // for i
        }
    // if (facetGroups!=null)
    }
    // if (pt1==null) // not rotating
    // Add nodes to the scene:
    Composite defaultComposite = g2.getComposite();
    if (pt1 != null) {
        float alpha = (float) 0.5;
        int type = AlphaComposite.SRC_OVER;
        AlphaComposite composite = AlphaComposite.getInstance(type, alpha);
        g2.setComposite(composite);
    }
    GroupVector nodeGroups = controller.getSelectedNodeGroups();
    if (nodeGroups != null) {
        for (int i = 0; i < nodeGroups.size(); i++) {
            // loop over each group of nodes to display
            Group group = nodeGroups.get(i);
            NodeVector nodes = group.getNodes();
            for (int j = 0; j < nodes.size(); j++) {
                // loop over each node in the group
                Node node = nodes.get(j);
                Section s = node.getSection();
                // shouldn't be possible
                if (s == null) {
                    continue;
                }
                // not possible but I check for it anyway
                if (!s.isCalibrated()) {
                    continue;
                }
                if (!showAll && !s.equals(currentSection) && otherSections != null && !otherSections.contains(s)) {
                    continue;
                }
                // index into projectedPoints
                int id = node.getID();
                // Determine the painting colour for the node:
                Color col = getNodePaintingColor(nodeColorBy, node);
                // Paint the node:
                if (pt1 == null) {
                    if (projectedPoints[id] != null) {
                        // only paint if node is in front of the camera, and if its section is calibrated
                        zbuf.putNode(projectedPoints[id], col, controller.getPointWidth());
                    }
                } else {
                    MyPoint3D p = spaceToImage(node.getPoint3D());
                    // to next iteration of for j
                    if (p == null) {
                        continue;
                    }
                    g2.setPaint(col);
                    g2.fillOval((int) p.getX() - w / 2, (int) p.getY() - w / 2, w, w);
                }
            }
        // for j
        }
    // for i
    }
    // Add regions to the scene:
    if (pt1 == null) {
        if (controller.getShowRegions()) {
            for (int i = 0; i < model.numberOfRegions(); i++) {
                Region region = model.getRegion(i);
                Section s = region.getSection();
                // shouldn't be possible
                if (s == null) {
                    continue;
                }
                // not possible but I check for it anyway
                if (!s.isCalibrated()) {
                    continue;
                }
                if (!showAll && !s.equals(currentSection) && otherSections != null && !otherSections.contains(s)) {
                    continue;
                }
                // Project the region point:
                MyPoint3D p = spaceToImage(region.getPoint3D());
                // region is behind camera
                if (p == null) {
                    continue;
                }
                // Process the region through the zbuffer:
                zbuf.putNode(p, region.getColor(), controller.getPointWidth());
            }
        }
    }
    // Draw the outlines of the selected sections:
    if (pt1 == null) {
        SectionVector sections = controller.getSelectedOtherSections();
        // if ( showOther && sections!=null ) {
        if (showOutlines && sections != null) {
            for (int i = 0; i < sections.size(); i++) {
                // loop over each section to display
                Section section = sections.get(i);
                // Construct the section outline in section image pixel coordinates:
                // 4 corners
                n = 4;
                MyPoint2D[] pts2D = new MyPoint2D[n];
                w = section.getWidth();
                h = section.getHeight();
                if (w <= 0 || h <= 0) {
                    continue;
                }
                w--;
                h--;
                pts2D[0] = new MyPoint2D(0, 0);
                pts2D[1] = new MyPoint2D(w, 0);
                pts2D[2] = new MyPoint2D(w, h);
                pts2D[3] = new MyPoint2D(0, h);
                // Transform the outline from 2D image pixels to space coordinates:
                MyPoint3D[] pts3D = new MyPoint3D[n];
                boolean ok = true;
                for (int j = 0; j < n; j++) {
                    MyPoint3D p = section.imageCornerToSpace(pts2D[j]);
                    // null if section not calibrated
                    if (p == null) {
                        ok = false;
                        break;
                    }
                    pts3D[j] = p;
                }
                if (!ok) {
                    continue;
                }
                // Project the outline (from space to plotting pixel coordinates):
                for (int j = 0; j < n; j++) {
                    MyPoint3D p = spaceToImage(pts3D[j]);
                    // point is behind camera
                    if (p == null) {
                        ok = false;
                        break;
                    }
                    pts3D[j] = p;
                }
                // for j
                if (!ok) {
                    continue;
                }
                // Draw as black line objects:
                for (int j = 0; j < n; j++) {
                    int j2 = j + 1;
                    if (j2 == n) {
                        j2 = 0;
                    }
                    zbuf.putEdge(pts3D[j], pts3D[j2], Color.BLACK);
                }
            }
        // for i
        }
    }
    // Draw the VOI:
    if (pt1 != null) {
        g2.setPaint(Color.BLACK);
        g2.setComposite(defaultComposite);
    }
    if (controller.getShowVOI()) {
        if (controller.hasVOI()) {
            MyPoint3D[][] edges = controller.getVOIEdges();
            for (int i = 0; i < VOI.N_EDGES; i++) {
                MyPoint3D p1 = spaceToImage(edges[i][0]);
                MyPoint3D p2 = spaceToImage(edges[i][1]);
                // point(s) behind camera
                if (p1 == null || p2 == null) {
                    continue;
                }
                if (pt1 == null) {
                    zbuf.putEdge(p1, p2, Color.BLACK);
                } else {
                    g2.drawLine((int) p1.getX(), (int) p1.getY(), (int) p2.getX(), (int) p2.getY());
                }
            }
        // for i
        }
    }
    // Draw the axes:
    if (showAxes) {
        // Set up axis points:
        // origin
        MyPoint3D po = spaceOrigin.deepCopy();
        // x axis
        MyPoint3D px = MyPoint3D.plus(po, new MyPoint3D(AXIS_LENGTH, 0, 0));
        // y axis
        MyPoint3D py = MyPoint3D.plus(po, new MyPoint3D(0, AXIS_LENGTH, 0));
        // z axis
        MyPoint3D pz = MyPoint3D.plus(po, new MyPoint3D(0, 0, AXIS_LENGTH));
        // Project with no scaling:
        po = spaceToImage(po, 1.0);
        px = spaceToImage(px, 1.0);
        py = spaceToImage(py, 1.0);
        pz = spaceToImage(pz, 1.0);
        // Move to bottom left corner if desired:
        if (!centreAxes) {
            po.minus(imageOrigin);
            px.minus(imageOrigin);
            py.minus(imageOrigin);
            pz.minus(imageOrigin);
            MyPoint3D p = new MyPoint3D(AXIS_LENGTH + 5, getHeight() - AXIS_LENGTH - 5, 0.0);
            po.plus(p);
            px.plus(p);
            py.plus(p);
            pz.plus(p);
        }
        // Draw axes as coloured line objects:
        if (pt1 == null) {
            zbuf.putEdge(po, px, Color.RED);
            zbuf.putEdge(po, py, Color.YELLOW);
            zbuf.putEdge(po, pz, Color.GREEN);
        } else {
            g2.setPaint(Color.RED);
            g2.drawLine((int) po.getX(), (int) po.getY(), (int) px.getX(), (int) px.getY());
            g2.setPaint(Color.YELLOW);
            g2.drawLine((int) po.getX(), (int) po.getY(), (int) py.getX(), (int) py.getY());
            g2.setPaint(Color.GREEN);
            g2.drawLine((int) po.getX(), (int) po.getY(), (int) pz.getX(), (int) pz.getY());
        }
    }
    // There is nothing more to draw if rotating:
    if (pt1 != null) {
        drawn = true;
        return;
    }
    // Get the zbuffer image:
    BufferedImage image = zbuf.getImage();
    // Return if no image exists:
    if (image == null) {
        return;
    }
    // Tightly fit the image inside the panel (a very simple fitting since they are the same size!):
    tightFitImage(g, image);
    // Return if no sections exist:
    if (!model.hasSections()) {
        drawn = true;
        return;
    }
    // Return if no current section exists:
    if (currentSection == null) {
        return;
    }
    // Figure out where the cursor is:
    boolean mouseInside2D = controller.getMouseInside2D();
    // Get mouse click mode:
    int mode = controller.getClickMode();
    // Redefine w for use below:
    w = 2 * nodeWidth;
    // Set stroke for facet edge overlays:
    BasicStroke dashedStroke = new BasicStroke(edgeWidth + 1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, (float) 10.0, new float[] { 2f, 16f }, (float) 0.0);
    g2.setStroke(dashedStroke);
    g2.setPaint(controller.getDefineFacetEdgeColor());
    // Paint the edges of the current facet being defined:
    Facet currentFacet = controller.getCurrentFacet();
    if (currentFacet != null) {
        // Create a path around the node coordinates:
        if (currentFacet.size() > 1) {
            GeneralPath path = addFacetToPath(currentFacet);
            if (path != null) {
                // May want to close the path:
                if (mode == ClickModeManager.MODE_DEFINE_TRI_FACETS || mode == ClickModeManager.MODE_ADD_NODES_IN_FACETS) {
                    path.closePath();
                }
                // Draw the path:
                g2.draw(path);
            }
        }
    }
    // Paint the edges of the facet closest to the cursor position:
    if (mouseInside2D && currentFacet == null) {
        Facet facet = controller.getClosestFacet();
        if (facet != null) {
            // Create a path around the node coordinates:
            if (facet.size() > 1) {
                GeneralPath path = addFacetToPath(facet);
                if (path != null) {
                    // Close the path:
                    path.closePath();
                    // Draw the path:
                    g2.draw(path);
                }
            }
        }
    }
    // Set stroke for node overlays:
    g2.setStroke(new BasicStroke(edgeWidth));
    // Paint circles around the nodes of the current facet being defined:
    if (currentFacet != null) {
        if (mode == ClickModeManager.MODE_DEFINE_TRI_FACETS) {
            g2.setPaint(Color.WHITE);
        } else {
            g2.setPaint(Color.BLACK);
        }
        for (int i = 0; i < currentFacet.size(); i++) {
            Node node = currentFacet.getNode(i);
            // Only paint the node if it is in the current or other sections:
            Section section = node.getSection();
            if (section.equals(currentSection) || (otherSections != null && otherSections.contains(section))) {
                MyPoint3D p = spaceToImage(node.getPoint3D());
                if (p == null) {
                    continue;
                }
                g2.drawOval((int) p.getX() - w / 2, (int) p.getY() - w / 2, w, w);
            }
        }
    // for i
    }
    // Paint circles around the nodes of the facet closest to the cursor position:
    if (mouseInside2D && currentFacet == null) {
        Facet facet = controller.getClosestFacet();
        if (facet != null) {
            // Paint circles around the node coordinates:
            g2.setPaint(Color.WHITE);
            for (int i = 0; i < facet.size(); i++) {
                Node node = facet.getNode(i);
                MyPoint3D p = spaceToImage(node.getPoint3D());
                if (p == null) {
                    continue;
                }
                g2.drawOval((int) p.getX() - w / 2, (int) p.getY() - w / 2, w, w);
            }
        // for i
        }
    }
    // Paint a white circle around the current node:
    Node node = controller.getCurrentNode();
    if (node != null) {
        MyPoint3D p = spaceToImage(node.getPoint3D());
        if (p != null) {
            g2.setPaint(Color.WHITE);
            g2.drawOval((int) p.getX() - w / 2, (int) p.getY() - w / 2, w, w);
        }
    }
    // Paint a white circle around the node closest to the cursor position:
    node = controller.getClosestNode();
    if (mouseInside2D && node != null) {
        MyPoint3D p = spaceToImage(node.getPoint3D());
        if (p != null) {
            g2.setPaint(Color.WHITE);
            g2.drawOval((int) p.getX() - w / 2, (int) p.getY() - w / 2, w, w);
        }
    }
    // Redefine w for use below:
    w = nodeWidth;
    // Paint a cursor location indicator at the position of the candidate node:
    node = controller.getCandidateNode();
    if (node != null) {
        MyPoint3D p = spaceToImage(node.getPoint3D());
        if (p != null) {
            g2.setPaint(Color.WHITE);
            int ix = (int) p.getX();
            int iy = (int) p.getY();
            g2.drawOval(ix - w / 2, iy - w / 2, w, w);
            g2.drawLine(ix - w / 2, iy, ix + w / 2, iy);
            g2.drawLine(ix, iy - w / 2, ix, iy + w / 2);
        }
    }
    // Set drawn flag to true:
    drawn = true;
}
Also used : BasicStroke(java.awt.BasicStroke) SectionVector(facetmodeller.sections.SectionVector) Group(facetmodeller.groups.Group) GeneralPath(java.awt.geom.GeneralPath) FacetVector(facetmodeller.plc.FacetVector) Node(facetmodeller.plc.Node) MyPoint3D(geometry.MyPoint3D) BufferedImage(java.awt.image.BufferedImage) NodeVector(facetmodeller.plc.NodeVector) ZBuffer3D(facetmodeller.gui.ZBuffer3D) Facet(facetmodeller.plc.Facet) Circle(geometry.Circle) AlphaComposite(java.awt.AlphaComposite) Composite(java.awt.Composite) AlphaComposite(java.awt.AlphaComposite) Color(java.awt.Color) ModelManager(facetmodeller.ModelManager) Section(facetmodeller.sections.Section) MyPoint2D(geometry.MyPoint2D) Graphics2D(java.awt.Graphics2D) GroupVector(facetmodeller.groups.GroupVector) Region(facetmodeller.plc.Region) SceneInfo(facetmodeller.gui.SceneInfo)

Example 5 with SectionVector

use of facetmodeller.sections.SectionVector in project facetmodeller by pglelievre.

the class SectionImagePanel method paintComponent.

/**
 * Paints graphics on the panel.
 * @param g Graphics context in which to draw.
 */
@Override
public void paintComponent(Graphics g) {
    // Paint background:
    super.paintComponent(g);
    // Clear the lists of painted nodes, node points, etc.:
    paintedNodes.clear();
    paintedNodePoints.clear();
    paintedFacets.clear();
    paintedFacetCentroids.clear();
    paintedRegions.clear();
    paintedRegionPoints.clear();
    // Return if no sections exist:
    if (!controller.hasSections()) {
        return;
    }
    // Return if no current section exists:
    Section currentSection = controller.getSelectedCurrentSection();
    if (currentSection == null) {
        return;
    }
    // Set some local variables:
    int shiftX = controller.getShiftingX();
    int shiftY = controller.getShiftingY();
    int mode = controller.getClickMode();
    boolean showImage = controller.getShowImage();
    boolean showImageOutline = controller.getShowImageOutline();
    // Get the other sections being displayed (if any exist):
    SectionVector otherSections;
    // if (controller.getShowOther()) {
    otherSections = controller.getSelectedOtherSections();
    // } else {
    // otherSections = null;
    // }
    // Determine the facets to paint:
    FacetVector facetsToPaint = new FacetVector();
    GroupVector groups = controller.getSelectedFacetGroups();
    if (groups != null) {
        // for (int i=0 ; i<groups.size(); i++ ) { // loop over every selected facet group
        for (int i = (groups.size() - 1); i >= 0; i--) {
            // loop over every selected facet group in reverse order
            FacetVector facets = groups.get(i).getFacets();
            for (int j = 0; j < facets.size(); j++) {
                // loop over every facet in the ith group
                Facet facet = facets.get(j);
                // Make sure there is more than one node in the facet:
                // number of nodes in the facet
                int nn = facet.size();
                if (nn <= 1) {
                    continue;
                }
                // Make sure the facet belongs to no other sections than those selected:
                boolean ok = true;
                for (int k = 0; k < nn; k++) {
                    // loop over each node in the facet
                    // Check if the kth node in the facet should be plotted: it must be either
                    // 1) in the current section, which must be calibrated if its the topo section; OR
                    // 2) in one of the other selected sections, which must be calibrated:
                    // kth node in the facet
                    Node node = facet.getNode(k);
                    // section for the kth node
                    Section s = node.getSection();
                    if (s.equals(currentSection)) {
                        // node is in current section
                        if (node.getPoint2D() == null) {
                            // node not paintable
                            ok = false;
                            break;
                        }
                    } else {
                        // node not in current section
                        if (otherSections == null || !otherSections.contains(s) || !s.isCalibrated()) {
                            // (calibration required for projection)
                            ok = false;
                            break;
                        }
                        if (node.getPoint3D() == null) {
                            // node not paintable
                            ok = false;
                            break;
                        }
                    }
                }
                if (!ok) {
                    continue;
                }
                // Add the facet to the list of facets to paint:
                facetsToPaint.add(facet);
            }
        }
    }
    /*
        // Determine the nodes to paint in the current section:
        NodeVector nodesToPaintCurrent = new NodeVector();
        NodeVector nodes = currentSection.getNodes();
        for (int i=0 ; i<nodes.size() ; i++ ) {
            Node node = nodes.get(i);
            // Make sure the node is in one of the selected groups to paint:
            if (!controller.isSelectedNodeGroup(node.getGroup())) { continue; } // cycle to next node
            // Make sure the node is paintable:
            if (node.getPoint2D()==null) { continue; } // cycle to next node
            // Add the node to the list of nodes to paint:
            nodesToPaintCurrent.add(node);
        }
        
        // Determine the nodes to paint in the other sections:
        NodeVector nodesToPaintOther = new NodeVector();
        if (otherSections!=null) {
            if (!otherSections.isEmpty()) {
                for (int j=0 ; j<otherSections.size() ; j++ ) {
                    // Skip the section if it is the current section:
                    Section s = otherSections.get(j);
                    if (s.equals(currentSection)) { continue; }
                    // Skip the section if it is not calibrated (calibration is required for projection):
                    if (!s.isCalibrated()) { continue; }
                    // Loop over the nodes:
                    nodes = s.getNodes();
                    for (int i=0 ; i<nodes.size() ; i++ ) {
                        Node node = nodes.get(i);
                        // Make sure the node is in one of the selected groups to paint:
                        if (!controller.isSelectedNodeGroup(node.getGroup())) { continue; } // cycle to next node
                        // Make sure the node is paintable:
                        if (node.getPoint3D()==null) { continue; } // cycle to next node
                        // Add the node to the list of nodes to paint:
                        nodesToPaintOther.add(node);
                    }
                }
            }
        }
        */
    // Determine the nodes to paint in the current and other sections:
    NodeVector nodesToPaint = new NodeVector();
    groups = controller.getSelectedNodeGroups();
    if (groups != null) {
        for (int i = (groups.size() - 1); i >= 0; i--) {
            // loop over every selected node group in reverse order
            NodeVector nodes = groups.get(i).getNodes();
            for (int j = 0; j < nodes.size(); j++) {
                // loop over every node in the ith group
                Node node = nodes.get(j);
                // Check if the node is in the current section:
                if (node.getSection() == currentSection) {
                    // cycle to next node
                    if (node.getPoint2D() == null) {
                        continue;
                    }
                    // Add the node to the list of nodes to paint and cycle to the next node:
                    nodesToPaint.add(node);
                    continue;
                }
                // Check if there are any other sections selected:
                if (otherSections == null) {
                    continue;
                }
                if (otherSections.isEmpty()) {
                    continue;
                }
                // Check if the node is in one of the other sections selected:
                Section s = node.getSection();
                if (!otherSections.contains(s)) {
                    continue;
                }
                // Skip the node if it's section is not calibrated (calibration is required for projection):
                if (!s.isCalibrated()) {
                    continue;
                }
                // cycle to next node
                if (node.getPoint3D() == null) {
                    continue;
                }
                // Add the node to the list of nodes to paint:
                nodesToPaint.add(node);
            }
        }
    }
    // Calculate the range, in image panel units, across which we'll need to plot:
    // will hold minimum coordinate values
    MyPoint2D p1 = MyPoint2D.zero();
    // will hold maximum coordinate values
    MyPoint2D p2 = new MyPoint2D(currentSection.getWidth(), currentSection.getHeight());
    RegionVector regions = currentSection.getRegions();
    if (!(currentSection instanceof SnapshotSection)) {
        for (int i = 0; i < facetsToPaint.size(); i++) {
            // loop over facets
            Facet facet = facetsToPaint.get(i);
            for (int j = 0; j < facet.size(); j++) {
                Node node = facet.getNode(j);
                MyPoint2D p = shiftNode(node, currentSection, shiftX, shiftY);
                if (p == null) {
                    // shouldn't happen, but I'll check for it anyway
                    facetsToPaint.remove(facet);
                    continue;
                }
                p1.min(p);
                p2.max(p);
            }
        }
        /*
            for (int i=0 ; i<nodesToPaintCurrent.size() ; i++ ) { // loop over nodes for current section
                Node node = nodesToPaintCurrent.get(i);
                MyPoint2D p = shiftNode(node,currentSection,shiftX,shiftY);
                if (p==null) { // shouldn't happen, but I'll check for it anyway
                    nodesToPaintCurrent.remove(node);
                    continue;
                }
                p1.min(p);
                p2.max(p);
            }
            for (int i=0 ; i<nodesToPaintOther.size() ; i++ ) { // loop over nodes for other section
                Node node = nodesToPaintOther.get(i);
                MyPoint2D p = shiftNode(node,currentSection,shiftX,shiftY);
                if (p==null) {  // shouldn't happen, but I'll check for it anyway
                    nodesToPaintOther.remove(node);
                    continue;
                }
                p1.min(p);
                p2.max(p);
            }
            */
        for (int i = 0; i < nodesToPaint.size(); i++) {
            // loop over nodes for other section
            Node node = nodesToPaint.get(i);
            MyPoint2D p = shiftNode(node, currentSection, shiftX, shiftY);
            if (p == null) {
                // shouldn't happen, but I'll check for it anyway
                nodesToPaint.remove(node);
                continue;
            }
            p1.min(p);
            p2.max(p);
        }
        if (controller.getShowRegions()) {
            for (int i = 0; i < regions.size(); i++) {
                // loop over regions
                Region region = regions.get(i);
                MyPoint2D p = region.getPoint2D();
                p1.min(p);
                p2.max(p);
            }
        }
    }
    // coordinate ranges
    MyPoint2D dp = MyPoint2D.minus(p2, p1);
    if (dp.min() <= 0.0) {
        return;
    }
    // Tightly fit the plot inside the panel but maintain aspect ratio:
    calculateTightFitTransform(p1, dp);
    boolean hasImage = currentSection.hasImage();
    if (hasImage && showImage) {
        // Get the current section image:
        BufferedImage image = currentSection.getImage();
        // Check the image exists:
        if (image != null) {
            // this may happen if the image file specified in a session file is not found
            // Calculate the tight fit transform:
            tightFitImage(g, image);
        }
    }
    // Get drawing styles for overlays:
    final int nodeWidth = controller.getPointWidth();
    final int edgeWidth = controller.getLineWidth();
    // centroids drawn half the node width
    final int centroidWidth = (int) Math.ceil(nodeWidth / 2.0);
    final float transparency = (float) controller.getTransparency();
    // transparency factor
    AlphaComposite composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency);
    // final boolean showPickingRadius = controller.getShowPickingRadius();
    // final int pickingRadius = (int)( controller.getPickingRadius() * scaling ); // panel pixel width
    // The space-to-image transform may not be equidistance (may have different scalings for horizontal and vertical panel directions)
    // so, without knowing how best to show a picking radius in spatial units (it used to be in image pixel units but that caused some issues)
    // I have just gotten rid of the plotting of the picking radius.
    // Use Java2D graphics for overlays:
    Graphics2D g2 = (Graphics2D) g;
    g2.setComposite(composite);
    if (!hasImage || !showImage) {
        // section does not have an image or user does not want image shown
        double imageWidth = currentSection.getWidth();
        double imageHeight = currentSection.getHeight();
        double scaledWidth = scaling * imageWidth;
        double scaledHeight = scaling * imageHeight;
        Color col = currentSection.getColor();
        boolean ok = false;
        if (col == null) {
            col = getBackground();
        }
        // Plot a coloured rectangle:
        if (!hasImage && showImage) {
            // section does not have an image and user wants image shown
            g2.setColor(col);
            g2.fillRect((int) translation.getX(), (int) translation.getY(), (int) scaledWidth, (int) scaledHeight);
            ok = true;
        }
        // Plot outline of image:
        if (showImageOutline) {
            g2.setColor(Color.black);
            g2.drawRect((int) translation.getX(), (int) translation.getY(), (int) scaledWidth, (int) scaledHeight);
            ok = true;
        }
        // Make sure something is plotted:
        if (!ok) {
            col = getBackground();
            g2.setColor(col);
            g2.drawRect((int) translation.getX(), (int) translation.getY(), (int) scaledWidth, (int) scaledHeight);
        }
    }
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // line style
    g2.setStroke(new BasicStroke(edgeWidth));
    // Get number of dimensions:
    int ndim = controller.numberOfDimensions();
    // Get the drawing options for colouring the nodes and facets:
    int nodeColorBy = controller.getNodeColorBy();
    int facetColorBy = controller.getFacetColorBy();
    // Paint the patches, edges and centroids of the facets:
    for (int i = 0; i < facetsToPaint.size(); i++) {
        // loop over every facet that needs to be painted
        Facet facet = facetsToPaint.get(i);
        // Create a path around possibly shifted node coordinates:
        HasPathAndCentroid tmp = addFacetToPath(facet, currentSection, shiftX, shiftY);
        // shouldn't happen, but I'll check for it anyway
        if (tmp == null) {
            continue;
        }
        // Close the path:
        tmp.path.closePath();
        // Transform the path from section to panel coordinates:
        tmp.path.transform(imageToPanel);
        // Determine the painting colour for the facet:
        Color col = getFacetPaintingColor(facetColorBy, facet);
        // Greate a filled, semi-transparent polygonal patch:
        if (facet.size() > 2) {
            // (no patch exists for edge-element facets)
            g2.setPaint(col);
            g2.fill(tmp.path);
        }
        // Draw the path (i.e. the facet edges):
        if (ndim == 3) {
            col = controller.getEdgeColor();
        }
        // else {
        // color = facet.getColor();
        // }
        g2.setPaint(col);
        g2.draw(tmp.path);
        // Draw a small point at the facet centroid:
        if (ndim == 2) {
            col = controller.getEdgeColor();
        }
        g2.setPaint(col);
        // filled
        PaintingUtils.paintPoint(g2, imageToPanel, tmp.centroid, centroidWidth, true);
        // Add to the list of painted facets and centroids:
        paintedFacets.add(facet);
        paintedFacetCentroids.add(tmp.centroid);
    }
    // Paint the edges of the current facet being defined:
    BasicStroke dashedStroke = new BasicStroke(edgeWidth + 1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER, (float) 10.0, new float[] { 2f, 16f }, (float) 0.0);
    Facet currentFacet = controller.getCurrentFacet();
    if (currentFacet != null) {
        // Create a path around the node coordinates:
        if (currentFacet.size() > 1) {
            HasPathAndCentroid tmp = addFacetToPath(currentFacet, currentSection, shiftX, shiftY);
            if (tmp != null) {
                // May want to close the path:
                if (mode == ClickModeManager.MODE_DEFINE_TRI_FACETS || mode == ClickModeManager.MODE_ADD_NODES_IN_FACETS) {
                    tmp.path.closePath();
                }
                // Transform the path from section to panel coordinates:
                tmp.path.transform(imageToPanel);
                // Draw the path:
                // line style changed
                g2.setStroke(dashedStroke);
                g2.setPaint(controller.getDefineFacetEdgeColor());
                g2.draw(tmp.path);
                // line style reset
                g2.setStroke(new BasicStroke(edgeWidth));
            }
        }
    }
    // Paint the edges of the facet closest to the cursor position:
    if (mouseInside && currentFacet == null) {
        Facet facet = controller.getClosestFacet();
        if (facet != null) {
            // Create a path around the node coordinates:
            if (facet.size() > 1) {
                HasPathAndCentroid tmp = addFacetToPath(facet, currentSection, shiftX, shiftY);
                if (tmp != null) {
                    // null shouldn't happen, but I'll check for it anyway
                    // Close the path:
                    tmp.path.closePath();
                    // Transform the path from section to panel coordinates:
                    tmp.path.transform(imageToPanel);
                    // Draw the path:
                    // line style changed
                    g2.setStroke(dashedStroke);
                    g2.setPaint(controller.getDefineFacetEdgeColor());
                    g2.draw(tmp.path);
                    // line style reset
                    g2.setStroke(new BasicStroke(edgeWidth));
                }
            }
        }
    }
    // Paint the nodes for the current and other sections:
    for (int i = 0; i < nodesToPaint.size(); i++) {
        Node node = nodesToPaint.get(i);
        // Check if the node is on the current section:
        MyPoint2D p;
        boolean filled;
        if (node.getSection() == currentSection) {
            // node on current section
            p = node.getPoint2D();
            // nodes on current section are painted filled
            filled = true;
        } else {
            // node is on another section so it may be shifted
            p = shiftNode(node, currentSection, shiftX, shiftY);
            // nodes on other sections are painted unfilled
            filled = false;
        }
        // shouldn't happen, but I'll check for it anyway
        if (p == null) {
            continue;
        }
        // Determine the painting colour for the node:
        Color col = getNodePaintingColor(nodeColorBy, node);
        // Paint the node:
        g2.setPaint(col);
        PaintingUtils.paintPoint(g2, imageToPanel, p, nodeWidth, filled);
        // Add to the list of painted nodes and node points:
        paintedNodes.add(node);
        paintedNodePoints.add(p);
    }
    // Paint the region points for the current section:
    if (controller.getShowRegions()) {
        for (int i = 0; i < regions.size(); i++) {
            Region region = regions.get(i);
            MyPoint2D p = region.getPoint2D();
            // shouldn't happen, but I'll check for it anyway
            if (p == null) {
                continue;
            }
            g2.setPaint(region.getColor());
            PaintingUtils.paintPoint(g2, imageToPanel, p, nodeWidth, true);
            // Add to the list of painted regions and region points:
            paintedRegions.add(region);
            paintedRegionPoints.add(p);
        }
    }
    // Paint circles around the nodes of the current facet being defined:
    if (currentFacet != null) {
        if (mode == ClickModeManager.MODE_DEFINE_TRI_FACETS) {
            g2.setPaint(Color.WHITE);
        } else {
            g2.setPaint(Color.BLACK);
        }
        for (int i = 0; i < currentFacet.size(); i++) {
            Node node = currentFacet.getNode(i);
            // Only paint the node if it is in the current or other sections:
            Section s = node.getSection();
            if (s.equals(currentSection) || (otherSections != null && otherSections.contains(s))) {
                MyPoint2D p = shiftNode(node, currentSection, shiftX, shiftY);
                if (p == null) {
                    continue;
                }
                PaintingUtils.paintPoint(g2, imageToPanel, p, 2 * nodeWidth, false);
            }
        }
    }
    // Paint circles around the nodes of the facet closest to the cursor position:
    if (mouseInside && currentFacet == null) {
        Facet facet = controller.getClosestFacet();
        if (facet != null) {
            // Paint circles around the node coordinates:
            g2.setPaint(Color.WHITE);
            for (int i = 0; i < facet.size(); i++) {
                Node node = facet.getNode(i);
                MyPoint2D p = shiftNode(node, currentSection, shiftX, shiftY);
                if (p == null) {
                    continue;
                }
                PaintingUtils.paintPoint(g2, imageToPanel, p, 2 * nodeWidth, false);
            }
            // If in MODE_INFO or MODE_REVERSE_FACETS then paint a thicker circle around the first and possibly second node:
            if (mode == ClickModeManager.MODE_INFO || mode == ClickModeManager.MODE_REVERSE_FACETS) {
                Node node = facet.getNode(0);
                MyPoint2D p = shiftNode(node, currentSection, shiftX, shiftY);
                if (p != null) {
                    g2.setStroke(new BasicStroke(ndim * edgeWidth));
                    PaintingUtils.paintPoint(g2, imageToPanel, p, 2 * nodeWidth, false);
                    // line style reset
                    g2.setStroke(new BasicStroke(edgeWidth));
                }
                if (ndim == 3) {
                    node = facet.getNode(1);
                    p = shiftNode(node, currentSection, shiftX, shiftY);
                    if (p != null) {
                        g2.setStroke(new BasicStroke(2 * edgeWidth));
                        PaintingUtils.paintPoint(g2, imageToPanel, p, 2 * nodeWidth, false);
                        // line style reset
                        g2.setStroke(new BasicStroke(edgeWidth));
                    }
                }
            }
        // // Paint a white circle around the centroid:
        // if (showPickingRadius) {
        // HasPathAndCentroid tmp = addFacetToPath(facet,currentSection,shiftX,shiftY);
        // if (tmp!=null) { // shouldn't happen, but I'll check for it anyway
        // tmp.path.closePath();
        // tmp.path.transform(imageToPanel);
        // PaintingUtils.paintPoint(g2,imageToPanel,tmp.centroid,2*centroidWidth,false); // not filled
        // g2.setPaint(Color.BLACK);
        // PaintingUtils.paintPoint(g2,imageToPanel,tmp.centroid,2*pickingRadius,false); // not filled
        // }
        // }
        }
    }
    // boolean isTopo = currentSection.isTopo();
    if (hasImage && currentSection.isCalibrated()) {
        g2.setPaint(controller.getCalibrationColor());
        PaintingUtils.paintPoint(g2, imageToPanel, currentSection.getClicked1(), nodeWidth, false);
        PaintingUtils.paintPoint(g2, imageToPanel, currentSection.getClicked2(), nodeWidth, false);
    }
    // // If calibrating then draw large cross-hairs across the image:
    // if ( controller.getMode() == FacetModeller.MODE_CALIBRATE ) {
    // p = new MyPoint2D(getMousePosition());
    // g2.setColor(Color.white);
    // g2.setStroke(new BasicStroke(1)); // line style reset
    // double x = p.getX();
    // double y = p.getY();
    // double w = getWidth()/2.0;
    // g2.drawLine((int)(x-w),(int)y,(int)(x+w),(int)y);
    // g2.drawLine((int)x,(int)(y-w),(int)x,(int)(y+w));
    // }
    // Paint a large circle around the origin node of the same colour as the node if it is present in those painted:
    Node originNode = controller.getOriginNode3D();
    if (originNode != null) {
        int i = paintedNodes.indexOf(originNode);
        if (i >= 0) {
            MyPoint2D p = shiftNode(originNode, currentSection, shiftX, shiftY);
            if (p != null) {
                // shouldn't happen, but I'll check for it anyway
                // Determine the painting colour for the origin node:
                Color col = getNodePaintingColor(nodeColorBy, originNode);
                // Paint the origin node:
                g2.setPaint(col);
                // g2.setStroke(new BasicStroke(2*edgeWidth));
                PaintingUtils.paintPoint(g2, imageToPanel, p, 2 * nodeWidth, false);
            // g2.setStroke(new BasicStroke(edgeWidth)); // line style reset
            }
        }
    }
    // Paint a white circle around the current node (e.g. being moved or first in an edge being flipped):
    Node currentNode = controller.getCurrentNode();
    if (currentNode != null) {
        MyPoint2D p = shiftNode(currentNode, currentSection, shiftX, shiftY);
        if (p != null) {
            g2.setPaint(Color.WHITE);
            // not filled
            PaintingUtils.paintPoint(g2, imageToPanel, p, 2 * nodeWidth, false);
        }
    }
    // Paint a white circle around the node closest to the cursor position (e.g. or that being moved):
    MyPoint2D p = controller.getClosestNodePoint();
    if (mouseInside && p != null) {
        g2.setPaint(Color.WHITE);
        // not filled
        PaintingUtils.paintPoint(g2, imageToPanel, p, 2 * nodeWidth, false);
    // if (showPickingRadius) {
    // g2.setPaint(Color.BLACK);
    // PaintingUtils.paintPoint(g2,imageToPanel,p,2*pickingRadius,false); // not filled
    // }
    }
    // Paint a white circle around the region closest to the cursor position:
    p = controller.getClosestRegionPoint();
    if (mouseInside && p != null) {
        g2.setPaint(Color.WHITE);
        // not filled
        PaintingUtils.paintPoint(g2, imageToPanel, p, 2 * nodeWidth, false);
    // if (showPickingRadius) {
    // g2.setPaint(Color.BLACK);
    // PaintingUtils.paintPoint(g2,imageToPanel,p,2*pickingRadius,false); // not filled
    // }
    }
}
Also used : SectionVector(facetmodeller.sections.SectionVector) FacetVector(facetmodeller.plc.FacetVector) Node(facetmodeller.plc.Node) Section(facetmodeller.sections.Section) SnapshotSection(facetmodeller.sections.SnapshotSection) MyPoint2D(geometry.MyPoint2D) GroupVector(facetmodeller.groups.GroupVector) NodeVector(facetmodeller.plc.NodeVector) RegionVector(facetmodeller.plc.RegionVector) Region(facetmodeller.plc.Region) SnapshotSection(facetmodeller.sections.SnapshotSection) Facet(facetmodeller.plc.Facet)

Aggregations

Section (facetmodeller.sections.Section)10 SectionVector (facetmodeller.sections.SectionVector)10 Facet (facetmodeller.plc.Facet)6 Node (facetmodeller.plc.Node)6 Region (facetmodeller.plc.Region)6 Group (facetmodeller.groups.Group)5 GroupVector (facetmodeller.groups.GroupVector)5 NodeOffSection (facetmodeller.plc.NodeOffSection)4 NodeOnSection (facetmodeller.plc.NodeOnSection)4 NodeVector (facetmodeller.plc.NodeVector)4 ImageCrossSection (facetmodeller.sections.ImageCrossSection)4 NoImageCrossSection (facetmodeller.sections.NoImageCrossSection)4 NoImageDepthSection (facetmodeller.sections.NoImageDepthSection)4 SnapshotSection (facetmodeller.sections.SnapshotSection)4 MyPoint2D (geometry.MyPoint2D)4 PLC (facetmodeller.plc.PLC)3 MyPoint3D (geometry.MyPoint3D)3 Color (java.awt.Color)3 ModelManager (facetmodeller.ModelManager)2 FacetVector (facetmodeller.plc.FacetVector)2