001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.imagery.vectortile.mapbox;
003
004import java.io.ByteArrayOutputStream;
005import java.io.IOException;
006import java.text.NumberFormat;
007import java.util.ArrayList;
008import java.util.List;
009import java.util.Locale;
010
011import org.openstreetmap.josm.data.osm.TagMap;
012import org.openstreetmap.josm.data.protobuf.ProtobufPacked;
013import org.openstreetmap.josm.data.protobuf.ProtobufParser;
014import org.openstreetmap.josm.data.protobuf.ProtobufRecord;
015import org.openstreetmap.josm.tools.Utils;
016
017/**
018 * A Feature for a {@link Layer}
019 *
020 * @author Taylor Smock
021 * @since 17862
022 */
023public class Feature {
024    private static final byte ID_FIELD = 1;
025    private static final byte TAG_FIELD = 2;
026    private static final byte GEOMETRY_TYPE_FIELD = 3;
027    private static final byte GEOMETRY_FIELD = 4;
028    /**
029     * The number format instance to use (using a static instance gets rid of quite o few allocations)
030     * Doing this reduced the allocations of {@link #parseTagValue(String, Layer, int, List)} from 22.79% of parent to
031     * 12.2% of parent.
032     */
033    private static final NumberFormat NUMBER_FORMAT = NumberFormat.getNumberInstance(Locale.ROOT);
034    private static final String[] EMPTY_STRING_ARRAY = new String[0];
035    /**
036     * The geometry of the feature. Required.
037     */
038    private final List<CommandInteger> geometry = new ArrayList<>();
039
040    /**
041     * The geometry type of the feature. Required.
042     */
043    private final GeometryTypes geometryType;
044    /**
045     * The id of the feature. Optional.
046     */
047    // Technically, uint64
048    private final long id;
049    /**
050     * The tags of the feature. Optional.
051     */
052    private final TagMap tags;
053    private Geometry geometryObject;
054
055    /**
056     * Create a new Feature
057     *
058     * @param layer  The layer the feature is part of (required for tags)
059     * @param protobufRecord The record to create the feature from
060     * @throws IOException - if an IO error occurs
061     */
062    public Feature(Layer layer, ProtobufRecord protobufRecord) throws IOException {
063        long tId = 0;
064        GeometryTypes geometryTypeTemp = GeometryTypes.UNKNOWN;
065        String key = null;
066        // Use a list where we can grow capacity easily (TagMap will do an array copy every time a tag is added)
067        // This lets us avoid most array copies (i.e., this should only happen if some software decided it would be
068        // a good idea to have multiple tag fields).
069        // By avoiding array copies in TagMap, Feature#init goes from 339 MB to 188 MB.
070        ArrayList<String> tagList = null;
071        try (ProtobufParser parser = new ProtobufParser(protobufRecord.getBytes())) {
072            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(4);
073            while (parser.hasNext()) {
074                try (ProtobufRecord next = new ProtobufRecord(byteArrayOutputStream, parser)) {
075                    if (next.getField() == TAG_FIELD) {
076                        // This is packed in v1 and v2
077                        ProtobufPacked packed = new ProtobufPacked(next.getBytes());
078                        if (tagList == null) {
079                            tagList = new ArrayList<>(packed.getArray().length);
080                        } else {
081                            tagList.ensureCapacity(tagList.size() + packed.getArray().length);
082                        }
083                        for (long number : packed.getArray()) {
084                            key = parseTagValue(key, layer, (int) number, tagList);
085                        }
086                    } else if (next.getField() == GEOMETRY_FIELD) {
087                        // This is packed in v1 and v2
088                        ProtobufPacked packed = new ProtobufPacked(next.getBytes());
089                        CommandInteger currentCommand = null;
090                        for (long number : packed.getArray()) {
091                            if (currentCommand != null && currentCommand.hasAllExpectedParameters()) {
092                                currentCommand = null;
093                            }
094                            if (currentCommand == null) {
095                                currentCommand = new CommandInteger(Math.toIntExact(number));
096                                this.geometry.add(currentCommand);
097                            } else {
098                                currentCommand.addParameter(ProtobufParser.decodeZigZag(number));
099                            }
100                        }
101                        // TODO fallback to non-packed
102                    } else if (next.getField() == GEOMETRY_TYPE_FIELD) {
103                        // by using getAllValues, we avoid 12.4 MB allocations
104                        geometryTypeTemp = GeometryTypes.getAllValues()[next.asUnsignedVarInt().intValue()];
105                    } else if (next.getField() == ID_FIELD) {
106                        tId = next.asUnsignedVarInt().longValue();
107                    }
108                }
109            }
110        }
111        this.id = tId;
112        this.geometryType = geometryTypeTemp;
113        protobufRecord.close();
114        if (tagList != null && !tagList.isEmpty()) {
115            this.tags = new TagMap(tagList.toArray(EMPTY_STRING_ARRAY));
116        } else {
117            this.tags = null;
118        }
119    }
120
121    /**
122     * Parse a tag value
123     *
124     * @param key    The current key (or {@code null}, if {@code null}, the returned value will be the new key)
125     * @param layer  The layer with key/value information
126     * @param number The number to get the value from
127     * @param tagList The list to add the new value to
128     * @return The new key (if {@code null}, then a value was parsed and added to tags)
129     */
130    private static String parseTagValue(String key, Layer layer, int number, List<String> tagList) {
131        if (key == null) {
132            key = layer.getKey(number);
133        } else {
134            tagList.add(key);
135            Object value = layer.getValue(number);
136            if (value instanceof Double || value instanceof Float) {
137                // reset grouping if the instance is a singleton
138
139                final boolean grouping = NUMBER_FORMAT.isGroupingUsed();
140                try {
141                    NUMBER_FORMAT.setGroupingUsed(false);
142                    tagList.add(Utils.intern(NUMBER_FORMAT.format(value)));
143                } finally {
144                    NUMBER_FORMAT.setGroupingUsed(grouping);
145                }
146            } else {
147                tagList.add(Utils.intern(value.toString()));
148            }
149            key = null;
150        }
151        return key;
152    }
153
154    /**
155     * Get the geometry instructions
156     *
157     * @return The geometry
158     */
159    public List<CommandInteger> getGeometry() {
160        return this.geometry;
161    }
162
163    /**
164     * Get the geometry type
165     *
166     * @return The {@link GeometryTypes}
167     */
168    public GeometryTypes getGeometryType() {
169        return this.geometryType;
170    }
171
172    /**
173     * Get the id of the object
174     *
175     * @return The unique id in the layer, or 0.
176     */
177    public long getId() {
178        return this.id;
179    }
180
181    /**
182     * Get the tags
183     *
184     * @return A tag map
185     */
186    public TagMap getTags() {
187        return this.tags;
188    }
189
190    /**
191     * Get the an object with shapes for the geometry
192     * @return An object with usable geometry information
193     * @throws IllegalArgumentException if the geometry object cannot be created because arguments are not understood
194     *                                  or the shoelace formula returns 0 for a polygon ring.
195     */
196    public Geometry getGeometryObject() {
197        if (this.geometryObject == null) {
198            this.geometryObject = new Geometry(this.getGeometryType(), this.getGeometry());
199        }
200        return this.geometryObject;
201    }
202
203    @Override
204    public String toString() {
205        return "Feature [geometry=" + geometry + ", "
206                + "geometryType=" + geometryType + ", id=" + id + ", "
207                + (tags != null ? "tags=" + tags + ", " : "")
208                + (geometryObject != null ? "geometryObject=" + geometryObject : "") + ']';
209    }
210}