PolygonColorMapper.java 2.49 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package de.hft.stuttgart.citygml.viewer.parser;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import javax.swing.JOptionPane;

public class PolygonColorMapper {
	
	private static final String IGNORING_ALL_POLYGON_COLOR_MAPPINGS = "\nIgnoring all polygon color mappings";
17
18
	private Function<String, Color> producer;
	private Map<String, Color> colorMap;
19
20
	

21
	private void loadColorMap(Path path) {
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
		Path colorMappingPath = Path.of("colorMappings.csv");
		if (!Files.exists(colorMappingPath)) {
			producer = s -> null;
			return;
		}
		try (BufferedReader reader = Files.newBufferedReader(colorMappingPath)) {
			colorMap = new HashMap<>();
			String line = null;
			while ((line = reader.readLine()) != null) {
				if (line.startsWith("#")) {
					// skip comments
					continue;
				}
				String[] mappingStrings = line.split(",");
				String polygonId = mappingStrings[0];
				int r = Integer.parseInt(mappingStrings[1]);
				if (r < 0 || r > 255) {
					JOptionPane.showMessageDialog(null, "Wrong red value " + r + " for polygon: " + polygonId + IGNORING_ALL_POLYGON_COLOR_MAPPINGS, "Warning", JOptionPane.WARNING_MESSAGE);
					colorMap = null;
					producer = s -> null;
					return;
				}
				int g = Integer.parseInt(mappingStrings[2]);
				if (g < 0 || g > 255) {
					JOptionPane.showMessageDialog(null, "Wrong green value " + g + " for polygon: " + polygonId + IGNORING_ALL_POLYGON_COLOR_MAPPINGS, "Warning", JOptionPane.WARNING_MESSAGE);
					colorMap = null;
					producer = s -> null;
					return;
				}
				int b = Integer.parseInt(mappingStrings[3]);
				if (b < 0 || b > 255) {
					JOptionPane.showMessageDialog(null, "Wrong green value " + b + " for polygon: " + polygonId + IGNORING_ALL_POLYGON_COLOR_MAPPINGS, "Warning", JOptionPane.WARNING_MESSAGE);
					colorMap = null;
					producer = s -> null;
					return;
				}
				Color color = new Color(r, g, b);
				colorMap.put(polygonId, color);
			}
			if (colorMap.isEmpty()) {
				producer = s -> null;
			} else {
				producer = s -> colorMap.get(s);
			}
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Could not read mapping csv file, ignoring: " + e.getMessage(), "Warning", JOptionPane.WARNING_MESSAGE);
		}
	}
	
	
72
	public Color getColorForPolygon(String polygonId) {
73
74
75
		return producer.apply(polygonId);
	}
	
76
77
	public PolygonColorMapper(Path path) {
		loadColorMap(path);
78
79
80
	}

}