001package armyc2.c5isr.renderer.utilities;
002
003import android.graphics.Bitmap;
004import android.graphics.Canvas;
005import android.graphics.Paint;
006import android.graphics.Paint.Style;
007import android.graphics.Path;
008import android.graphics.Point;
009import android.graphics.Rect;
010import android.graphics.RectF;
011import android.os.Build;
012import android.util.Base64;
013import android.util.SparseArray;
014
015import com.caverock.androidsvg.SVG;
016import com.caverock.androidsvg.SVGParseException;
017
018import java.io.ByteArrayOutputStream;
019import java.util.Map;
020import java.util.TreeSet;
021import java.util.logging.Level;
022import java.util.regex.Matcher;
023import java.util.regex.Pattern;
024
025public class RendererUtilities {
026
027    private static final float OUTLINE_SCALING_FACTOR = 2.5f;
028        private static SparseArray<Color> pastIdealOutlineColors = new SparseArray<Color>();
029
030    public static String imgToBase64String(Bitmap bitmap) {
031        final int COMPRESSION_QUALITY = 100;
032        String encodedImage;
033        ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
034        bitmap.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY,
035                byteArrayBitmapStream);
036        byte[] b = byteArrayBitmapStream.toByteArray();
037        encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
038        return "data:image/png;base64," + encodedImage;
039    }
040
041        /**
042     * 
043     * @param color {String} color like "#FFFFFF"
044     * @return {String}
045     */
046    public static Color getIdealOutlineColor(Color color){
047        Color idealColor = Color.white;
048        
049        if(color != null && pastIdealOutlineColors.indexOfKey(color.toInt())>=0)
050        {
051            return pastIdealOutlineColors.get(color.toInt());
052        }//*/
053        
054        if(color != null)
055        {
056                
057                int threshold = RendererSettings.getInstance().getTextBackgroundAutoColorThreshold();
058                        
059            int r = color.getRed();
060            int g = color.getGreen();
061            int b = color.getBlue();
062        
063            float delta = ((r * 0.299f) + (g * 0.587f) + (b * 0.114f));
064            
065            if((255 - delta < threshold))
066            {
067                idealColor = Color.black;
068            }
069            else
070            {
071                idealColor = Color.white;
072            }
073        }
074        
075        if(color != null)
076                pastIdealOutlineColors.put(color.toInt(),idealColor);
077        
078        return idealColor;
079    }
080    
081    public static void renderSymbolCharacter(Canvas ctx, String symbol, int x, int y, Paint paint, Color color, int outlineWidth)
082    {
083        int tbm = RendererSettings.getInstance().getTextBackgroundMethod();
084
085        Color outlineColor = RendererUtilities.getIdealOutlineColor(color);
086
087        //if(tbm == RendererSettings.TextBackgroundMethod_OUTLINE_QUICK)
088        //{    
089            //draw symbol outline
090                paint.setStyle(Style.FILL);
091
092                paint.setColor(outlineColor.toInt());
093            if(outlineWidth > 0)
094            {
095                for(int i = 1; i <= outlineWidth; i++)
096                {
097                        if(i % 2 == 1)
098                        {
099                                ctx.drawText(symbol, x - i, y, paint);
100                        ctx.drawText(symbol, x + i, y, paint);
101                        ctx.drawText(symbol, x, y + i, paint);
102                        ctx.drawText(symbol, x, y - i, paint);
103                        }
104                        else
105                        {
106                                ctx.drawText(symbol, x - i, y - i, paint);
107                        ctx.drawText(symbol, x + i, y - i, paint);
108                        ctx.drawText(symbol, x - i, y + i, paint);
109                        ctx.drawText(symbol, x + i, y + i, paint);
110                        }
111                        
112                }
113                
114            }
115            //draw symbol
116            paint.setColor(color.toInt());
117            
118                ctx.drawText(symbol, x, y, paint);
119            
120        /*}
121        else
122        {
123            //draw text outline
124                paint.setStyle(Style.STROKE);
125                paint.setStrokeWidth(RendererSettings.getInstance().getTextOutlineWidth());
126                paint.setColor(outlineColor.toInt());
127            if(outlineWidth > 0)
128            {
129                
130                ctx.drawText(symbol, x, y, paint);
131                
132            }
133            //draw text
134            paint.setColor(color.toInt());
135            paint.setStyle(Style.FILL);
136            
137                ctx.drawText(symbol, x, y, paint);
138        }//*/     
139    }
140
141    /**
142     * Create a copy of the {@Color} object with the passed alpha value.
143     * @param color {@Color} object used for RGB values
144     * @param alpha {@float} value between 0 and 1
145     * @return
146     */
147    public static Color setColorAlpha(Color color, float alpha) {
148        if (color != null)
149        {
150            if(alpha >= 0 && alpha <= 1)
151                return new Color(color.getRed(),color.getGreen(),color.getBlue(),(int)(alpha*255f));
152            else
153                return color;
154        }
155        else
156            return null;
157    }
158    public static String colorToHexString(Color color, Boolean withAlpha)
159    {
160        if(color != null)
161        {
162            String hex = color.toHexString();
163            hex = hex.toUpperCase();
164            if(withAlpha)
165                return "#" + hex;
166            else
167                return "#" + hex.substring(2);
168        }
169        return null;
170    }
171
172    /**
173     *
174     * @param hexValue - String representing hex value (formatted "0xRRGGBB"
175     * i.e. "0xFFFFFF") OR formatted "0xAARRGGBB" i.e. "0x00FFFFFF" for a color
176     * with an alpha value I will also put up with "RRGGBB" and "AARRGGBB"
177     * without the starting "0x"
178     * @return
179     */
180    public static Color getColorFromHexString(String hexValue)
181    {
182        try
183        {
184            if(hexValue==null || hexValue.isEmpty())
185                return null;
186            String hexOriginal = hexValue;
187
188            String hexAlphabet = "0123456789ABCDEF";
189
190            if (hexValue.charAt(0) == '#')
191            {
192                hexValue = hexValue.substring(1);
193            }
194            if (hexValue.substring(0, 2).equals("0x") || hexValue.substring(0, 2).equals("0X"))
195            {
196                hexValue = hexValue.substring(2);
197            }
198
199            hexValue = hexValue.toUpperCase();
200
201            int count = hexValue.length();
202            int[] value = null;
203            int k = 0;
204            int int1 = 0;
205            int int2 = 0;
206
207            if (count == 8 || count == 6)
208            {
209                value = new int[(count / 2)];
210                for (int i = 0; i < count; i += 2)
211                {
212                    int1 = hexAlphabet.indexOf(hexValue.charAt(i));
213                    int2 = hexAlphabet.indexOf(hexValue.charAt(i + 1));
214
215                    if(int1 == -1 || int2 == -1)
216                    {
217                        ErrorLogger.LogMessage("RendererUtilities", "getColorFromHexString", "Bad hex value: " + hexOriginal, Level.WARNING);
218                        return null;
219                    }
220
221                    value[k] = (int1 * 16) + int2;
222                    k++;
223                }
224
225                if (count == 8)
226                {
227                    return new Color(value[1], value[2], value[3], value[0]);
228                }
229                else if (count == 6)
230                {
231                    return new Color(value[0], value[1], value[2]);
232                }
233            }
234            else
235            {
236                ErrorLogger.LogMessage("RendererUtilities", "getColorFromHexString", "Bad hex value: " + hexOriginal, Level.WARNING);
237            }
238            return null;
239        }
240        catch (Exception exc)
241        {
242            ErrorLogger.LogException("RendererUtilities", "getColorFromHexString", exc);
243            return null;
244        }
245    }
246
247    /**
248     * For Renderer Use Only
249     * Assumes a fresh SVG String from the SVGLookup with its default values
250     * @param symbolID
251     * @param svg
252     * @param strokeColor hex value like "#FF0000";
253     * @param fillColor hex value like "#FF0000";
254     * @return SVG String
255     */
256    public static String setSVGFrameColors(String symbolID, String svg, Color strokeColor, Color fillColor)
257    {
258        String returnSVG = null;
259        String hexStrokeColor = null;
260        String hexFillColor = null;
261        float strokeAlpha = 1;
262        float fillAlpha = 1;
263        String strokeOpacity = "";
264        String fillOpacity = "";
265
266        int ss = SymbolID.getSymbolSet(symbolID);
267        int ver = SymbolID.getVersion(symbolID);
268        int affiliation = SymbolID.getAffiliation(symbolID);
269        String defaultFillColor = null;
270        returnSVG = svg;
271        if(strokeColor != null)
272        {
273            if(strokeColor.getAlpha() != 255)
274            {
275                strokeAlpha = strokeColor.getAlpha() / 255.0f;
276                strokeOpacity =  " stroke-opacity=\"" + String.valueOf(strokeAlpha) + "\"";
277                fillOpacity =  " fill-opacity=\"" + String.valueOf(strokeAlpha) + "\"";
278            }
279
280            hexStrokeColor = colorToHexString(strokeColor,false);
281            returnSVG = svg.replaceAll("stroke=\"#000000\"", "stroke=\"" + hexStrokeColor + "\"" + strokeOpacity);
282            returnSVG = returnSVG.replaceAll("fill=\"#000000\"", "fill=\"" + hexStrokeColor + "\"" + fillOpacity);
283
284            if(ss == SymbolID.SymbolSet_LandInstallation ||
285                    ss == SymbolID.SymbolSet_Space ||
286                    ss == SymbolID.SymbolSet_CyberSpace ||
287                    ss == SymbolID.SymbolSet_Activities)
288            {//add group fill so the extra shapes in these frames have the new frame color
289                String svgStart =  "<g id=\"" + SVGLookup.getFrameID(symbolID) + "\">";
290                String svgStartReplace = svgStart.substring(0,svgStart.length()-1) + " fill=\"" + hexStrokeColor + "\"" + fillOpacity + ">";
291                returnSVG = returnSVG.replace(svgStart,svgStartReplace);
292            }
293
294            if((SymbolID.getSymbolSet(symbolID)==SymbolID.SymbolSet_LandInstallation && SymbolID.getFrameShape(symbolID)=='0') ||
295                    SymbolID.getFrameShape(symbolID)==SymbolID.FrameShape_LandInstallation)
296            {
297                int i1 = findInstIndIndex(returnSVG)+5;
298                //make sure installation indicator matches line color
299                returnSVG = returnSVG.substring(0,i1) + " fill=\"" + hexStrokeColor + "\"" + returnSVG.substring(i1);
300            }
301
302        }
303        else if((SymbolID.getSymbolSet(symbolID)==SymbolID.SymbolSet_LandInstallation && SymbolID.getFrameShape(symbolID)=='0') ||
304                SymbolID.getFrameShape(symbolID)==SymbolID.FrameShape_LandInstallation)
305        {
306            int i1 = findInstIndIndex(returnSVG)+5;
307            //No line color change so make sure installation indicator stays black
308            returnSVG = returnSVG.substring(0,i1) + " fill=\"#000000\"" + returnSVG.substring(i1);
309        }
310
311        if(fillColor != null)
312        {
313            if(fillColor.getAlpha() != 255)
314            {
315                fillAlpha = fillColor.getAlpha() / 255.0f;
316                fillOpacity =  " fill-opacity=\"" + String.valueOf(fillAlpha) + "\"";
317            }
318
319            hexFillColor = colorToHexString(fillColor,false);
320            switch(affiliation)
321            {
322                case SymbolID.StandardIdentity_Affiliation_Friend:
323                case SymbolID.StandardIdentity_Affiliation_AssumedFriend:
324                    defaultFillColor = "fill=\"#80E0FF\"";//friendly frame fill
325                    break;
326                case SymbolID.StandardIdentity_Affiliation_Hostile_Faker:
327                    defaultFillColor = "fill=\"#FF8080\"";//hostile frame fill
328                    break;
329                case SymbolID.StandardIdentity_Affiliation_Suspect_Joker:
330                    if(SymbolID.getVersion(symbolID) >= SymbolID.Version_2525E)
331                        defaultFillColor = "fill=\"#FFE599\"";//suspect frame fill
332                    else
333                        defaultFillColor = "fill=\"#FF8080\"";//hostile frame fill
334                    break;
335                case SymbolID.StandardIdentity_Affiliation_Unknown:
336                case SymbolID.StandardIdentity_Affiliation_Pending:
337                    defaultFillColor = "fill=\"#FFFF80\"";//unknown frame fill
338                    break;
339                case SymbolID.StandardIdentity_Affiliation_Neutral:
340                    defaultFillColor = "fill=\"#AAFFAA\"";//neutral frame fill
341                    break;
342                default:
343                    defaultFillColor = "fill=\"#80E0FF\"";//friendly frame fill
344                    break;
345            }
346
347            int fillIndex = returnSVG.lastIndexOf(defaultFillColor);
348            if(fillIndex != -1)
349                returnSVG = returnSVG.substring(0,fillIndex) + "fill=\"" + hexFillColor + "\"" + fillOpacity + returnSVG.substring(fillIndex + defaultFillColor.length());
350
351            //returnSVG = returnSVG.replaceFirst(defaultFillColor, "fill=\"" + hexFillColor + "\"" + fillOpacity);
352        }
353
354        if(returnSVG != null)
355            return returnSVG;
356        else
357            return svg;
358    }
359
360    /**
361     * For Renderer Use Only
362     * Changes colors for single point control measures
363     * @param symbolID
364     * @param svg
365     * @param strokeColor hex value like "#FF0000";
366     * @param fillColor hex value like "#FF0000";
367     * @param isOutline true if this represents a thicker outline to render first beneath the normal symbol (the function must be called twice)
368     * @return SVG String
369     */
370    public static String setSVGSPCMColors(String symbolID, String svg, Color strokeColor, Color fillColor, boolean isOutline, RectF bounds, int pixelSize, int outlineWidth)
371    {
372        String returnSVG = svg;
373        String hexStrokeColor = null;
374        String hexFillColor = null;
375        float strokeAlpha = 1;
376        float fillAlpha = 1;
377        String strokeOpacity = "";
378        String fillOpacity = "";
379        String strokeCapSquare = " stroke-linecap=\"square\"";
380        String strokeCapButt = " stroke-linecap=\"butt\"";
381        String strokeCapRound = " stroke-linecap=\"round\"";
382        int outlineSize = 15;
383
384        int affiliation = SymbolID.getAffiliation(symbolID);
385        String defaultFillColor = null;
386        if(strokeColor != null)
387        {
388            if(strokeColor.getAlpha() != 255)
389            {
390                strokeAlpha = strokeColor.getAlpha() / 255.0f;
391                strokeOpacity =  " stroke-opacity=\"" + strokeAlpha + "\"";
392                fillOpacity =  " fill-opacity=\"" + strokeAlpha + "\"";
393            }
394
395            hexStrokeColor = colorToHexString(strokeColor,false);
396            String defaultStrokeColor = "#000000";
397            if(symbolID.length()==5)
398            {
399                int mod = Integer.valueOf(symbolID.substring(2,4));
400                if(mod >= 13)
401                    defaultStrokeColor = "#00A651";
402
403            }
404
405            if(symbolID.length() >= 20)
406            {
407                if(SymbolUtilities.getBasicSymbolID(symbolID).equals("25132100") && //key terrain
408                        SymbolID.getVersion(symbolID) >= SymbolID.Version_2525E)
409                    defaultStrokeColor = "#800080";
410                else if(isOutline && SymbolUtilities.getBasicSymbolID(symbolID).startsWith("2535"))//space debris doesn't change color
411                    defaultStrokeColor = "black";
412            }
413            returnSVG = returnSVG.replaceAll("stroke=\"" + defaultStrokeColor + "\"", "stroke=\"" + hexStrokeColor + "\"" + strokeOpacity);
414            returnSVG = returnSVG.replaceAll("fill=\"" + defaultStrokeColor + "\"", "fill=\"" + hexStrokeColor + "\"" + fillOpacity);
415        }
416        else
417        {
418            strokeColor = Color.BLACK;
419        }
420
421        if (isOutline && bounds != null)
422        {
423            float p = pixelSize;
424            double h = bounds.height();
425            double w = bounds.width();
426            double ratio = Math.min((p / h), (p / w));
427
428            outlineSize = (int)Math.round(outlineWidth / ratio);
429            //increase stroke-width so the white outline shows around the symbol
430            returnSVG = increaseStrokeWidth(returnSVG,outlineSize);
431            //set the stroke color for the group so filled shapes without stokes get outlined as well.
432            returnSVG = returnSVG.replaceFirst("<g", "<g stroke=\"" + hexStrokeColor + "\" " + strokeOpacity + " stroke-linecap=\"square\"");
433
434        }
435        else
436        {
437            String replacement = " fill=\"" + colorToHexString(strokeColor,false) + "\" ";
438            returnSVG = returnSVG.replace("fill=\"#000000\"",replacement);//only replace black fills, leave white fills alone.
439
440            //In case there are lines that don't have stroke defined, apply stroke color to the top level group.
441            String topGroupTag = "<g id=\"" + SymbolUtilities.getBasicSymbolID(symbolID) + "\">";//<g id="25212902">
442            String newGroupTag = "<g id=\"" + SymbolUtilities.getBasicSymbolID(symbolID) + "\" stroke=\"" + hexStrokeColor + "\"" + strokeOpacity + " " + replacement + ">";
443            returnSVG = returnSVG.replace(topGroupTag,newGroupTag);
444        }
445
446        if(fillColor != null)
447        {
448            if(fillColor.getAlpha() != 255)
449            {
450                fillAlpha = fillColor.getAlpha() / 255.0f;
451                fillOpacity =  " fill-opacity=\"" + fillAlpha + "\"";
452            }
453
454            hexFillColor = colorToHexString(fillColor,false);
455            defaultFillColor = "fill=\"#000000\"";
456
457            returnSVG = returnSVG.replaceAll(defaultFillColor, "fill=\"" + hexFillColor + "\"" + fillOpacity);
458        }
459
460        return returnSVG;
461    }
462
463    /**
464     * Sets SVG stroke-dasharray when action points are in planned status
465     * @param symbolID
466     * @param siIcon
467     * @return
468     */
469    public static SVGInfo setAffiliationDashArray(String symbolID, SVGInfo siIcon)
470    {
471        String svg = siIcon.getSVG();
472        int status = SymbolID.getStatus(symbolID);
473        int aff = SymbolID.getAffiliation(symbolID);
474        SVGInfo returnVal = siIcon;
475        if(status == SymbolID.Status_Planned_Anticipated_Suspect)
476        {
477            if(SymbolUtilities.isActionPoint(symbolID))
478            {
479                svg = svg.replaceFirst("<rect ","<rect stroke-dasharray=\"20 19\" ");
480                svg = svg.replaceFirst("<polygon ","<polygon stroke-dasharray=\"20 20\" ");
481                returnVal = new SVGInfo(siIcon.getID(),siIcon.getBbox(), svg);
482            }
483        }
484        /*else if(aff == SymbolID.StandardIdentity_Affiliation_Pending ||
485                aff == SymbolID.StandardIdentity_Affiliation_AssumedFriend ||
486                aff == SymbolID.StandardIdentity_Affiliation_Suspect_Joker)
487        {
488            //Dot pattern if Control Measures use it?
489        }//*/
490
491        return returnVal;
492    }
493    public static float findWidestStrokeWidth(String svg) {
494        Pattern pattern = Pattern.compile("(stroke-width=\")(\\d+\\.?\\d*)\"");
495        Matcher m = pattern.matcher(svg);
496        TreeSet<Float> strokeWidths = new TreeSet<>();
497        while (m.find()) {
498            // Log.d("found stroke width", m.group(0));
499            strokeWidths.add(Float.valueOf(m.group(2)));
500        }
501
502        float largest = 4.0f;
503        if (!strokeWidths.isEmpty()) {
504            largest = strokeWidths.descendingSet().first();
505        }
506        return largest * OUTLINE_SCALING_FACTOR;
507    }
508
509    public static int findInstIndIndex(String svg)
510    {
511        int start = -1;
512        int stop = -1;
513
514        start = svg.indexOf("<rect");
515        stop = svg.indexOf(">",start);
516
517        String rect = svg.substring(start,stop+1);
518        if(!rect.contains("fill"))//no set fill so it's the indicator
519        {
520            return start;
521        }
522        else //it's the next rect
523        {
524            start = svg.indexOf("<rect",stop);
525        }
526
527        return start;
528    }
529
530    public static SVGInfo scaleIcon(String symbolID, SVGInfo icon)
531    {
532        SVGInfo retVal= icon;
533        //safe square inside octagon:  <rect x="220" y="310" width="170" height="170"/>
534        double maxSize = 170;
535        RectF bbox = null;
536        if(icon != null)
537            bbox = icon.getBbox();
538        double length = 0;
539        if(bbox != null)
540        {
541            length = Math.max(bbox.width(), bbox.height());
542            //adjust max size for narrow, tall icons
543            if(bbox.width() < 60 && bbox.height() > 90)
544                maxSize = 200;
545
546            if(SVGLookup.getMainIconID(symbolID).length() == 8 && length < 145 && length > 0 &&
547                    bbox.height() < 105 &&
548                    SymbolID.getCommonModifier1(symbolID)==0 &&
549                    SymbolID.getCommonModifier2(symbolID)==0 &&
550                    SymbolID.getModifier1(symbolID)==0 &&
551                    SymbolID.getModifier2(symbolID)==0)//if largest side smaller than 145 and there are no section mods, make it bigger
552            {
553                double ratio = maxSize / length;
554                double transx = ((bbox.left + (bbox.width()/2)) * ratio) - (bbox.left + (bbox.width()/2));
555                double transy = ((bbox.top + (bbox.height()/2)) * ratio) - (bbox.top + (bbox.height()/2));
556                String transform = " transform=\"translate(-" + transx + ",-" + transy + ") scale(" + ratio + " " + ratio + ")\">";
557                String svg = icon.getSVG();
558                svg = svg.replaceFirst(">",transform);
559                RectF newBbox = RectUtilities.makeRectF((float)(bbox.left - transx),(float)(bbox.top - transy),(float)(bbox.width() * ratio), (float) (bbox.height() * ratio));
560                //retVal = new SVGInfo(icon.getID(),newBbox,svg);
561
562                //Adjust stroke widths so they remain the same and don't scale up.
563                int decimals = 3;
564                Pattern pattern = Pattern.compile("stroke-width=\"([\\d.]+)\"");
565                Matcher matcher = pattern.matcher(svg);
566                StringBuffer sb = new StringBuffer();
567                while (matcher.find()) {
568                    double original = Double.parseDouble(matcher.group(1));
569                    double adjusted = original * 1.5 / ratio;//multiply by 1.5 to reduce but not eliminate scaling
570                    String replacement = String.format("stroke-width=\"%." + decimals + "f\"", adjusted);
571                    matcher.appendReplacement(sb, replacement);
572                }
573                matcher.appendTail(sb);
574                svg = sb.toString();//*/
575
576                retVal = new SVGInfo(icon.getID(),newBbox,svg);
577            }
578        }
579
580        return retVal;
581    }
582
583    /**
584     * Takes an SVG string and increases all stroke-width values by the increaseBy value.
585     * @param svgString The raw SVG content.
586     * @param increaseBy the number to add to the current stroke value
587     * @return The modified SVG content.
588     */
589    public static String increaseStrokeWidth(String svgString, int increaseBy) {
590        Pattern pattern = Pattern.compile("stroke-width=\"([^\"]+)\"");
591        Matcher matcher = pattern.matcher(svgString);
592        StringBuilder sb = new StringBuilder();
593        int lastEnd = 0;
594
595        while (matcher.find()) {
596            // 1. Append everything from the last match up to the current match
597            sb.append(svgString.substring(lastEnd, matcher.start()));
598
599            String replacement;
600            try {
601                // 2. Calculate the new value
602                double currentValue = Double.parseDouble(matcher.group(1));
603                double newValue = currentValue + increaseBy;
604                String formattedValue = (newValue == (long) newValue)
605                        ? String.valueOf((long) newValue)
606                        : String.valueOf(newValue);
607
608                replacement = "stroke-width=\"" + formattedValue + "\"";
609            } catch (NumberFormatException e) {
610                // Fallback to original text if not a number
611                replacement = matcher.group(0);
612            }
613
614            // 3. Append the replacement and update our position
615            sb.append(replacement);
616            lastEnd = matcher.end();
617        }
618
619        // 4. Append any remaining text after the last match
620        sb.append(svgString.substring(lastEnd));
621        int firstGroup = sb.indexOf("<g");
622        sb.replace(firstGroup, firstGroup+2,"<g stroke-width=\"" + increaseBy + "\" ");
623        return sb.toString();
624    }
625
626    public static int getDistanceBetweenPoints(Point pt1, Point pt2)
627    {
628        int distance = (int)(Math.sqrt(Math.pow((pt2.x - pt1.x) ,2) + Math.pow((pt2.y - pt1.y) ,2)));
629        return distance;
630    }
631
632    public static int calculateOutlineWidth()
633    {
634        return RendererSettings.getInstance().getDeviceDPI()>240 ? (RendererSettings.getInstance().getDeviceDPI()/240 * 2) + 1 : 3;
635    }
636
637    /**
638     * Safely computes and returns the bounds of an Android Path.
639     * Uses the modern, high-precision getBounds() API on Android 14+ (API 34)
640     * and falls back gracefully on older devices.
641     *
642     * @param path The path to evaluate.
643     * @return A RectF containing the exact bounding box of the path.
644     */
645    public static RectF getPathBounds(Path path) {
646        if (path == null) {
647            return new RectF();
648        }
649
650        // Android 14 (UPSIDE_DOWN_CAKE) introduced the API 34+ path iterator bounds
651        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
652            return path.getBounds();
653        } else {//*/
654            // Fallback for older devices (API 33 and below)
655            RectF bounds = new RectF();
656
657            @SuppressWarnings("deprecation")
658            boolean exact = true; // Use control points to calculate bounds
659            path.computeBounds(bounds, exact);
660
661            return bounds;
662       // }
663    }
664
665    /**
666     * A starting point for calculating map scale.
667     * The User may prefer a different calculation depending on how their maps works.
668     * @param mapPixelWidth Width of your map in pixels
669     * @param eastLon East Longitude of your map
670     * @param westLon West Longitude of your map
671     * @return Map scale value to use in the RenderSymbol function {@link armyc2.c5isr.web.render.WebRenderer#RenderSymbol(String, String, String, String, String, String, double, String, Map, Map, int)}
672     */
673    public static double calculateMapScale(int mapPixelWidth, double eastLon, double westLon)
674    {
675        return calculateMapScale(mapPixelWidth,eastLon,westLon,RendererSettings.getInstance().getDeviceDPI());
676    }
677
678    /**
679     * A starting point for calculating map scale.
680     * The User may prefer a different calculation depending on how their maps works.
681     * @param mapPixelWidth Width of your map in pixels
682     * @param eastLon East Longitude of your map
683     * @param westLon West Longitude of your map
684     * @param dpi Dots Per Inch of your device
685     * @return Map scale value to use in the RenderSymbol function {@link armyc2.c5isr.web.render.WebRenderer#RenderSymbol(String, String, String, String, String, String, double, String, Map, Map, int)}
686     */
687    public static double calculateMapScale(int mapPixelWidth, double eastLon, double westLon, int dpi)
688    {
689        double INCHES_PER_METER = 39.3700787;
690        double METERS_PER_DEG = 40075017.0 / 360.0; // Earth's circumference in meters / 360 degrees
691
692        try
693        {
694            double sizeSquare = Math.abs(eastLon - westLon);
695            if (sizeSquare > 180)
696                sizeSquare = 360 - sizeSquare;
697
698            // physical screen length (in meters) = pixels in screen / pixels per inch / inch per meter
699            double screenLength = mapPixelWidth / dpi / INCHES_PER_METER;
700            // meters on screen = degrees on screen * meters per degree
701            double metersOnScreen = sizeSquare * METERS_PER_DEG;
702
703            double scale = metersOnScreen/screenLength;
704            return scale;
705        }
706        catch(Exception exc)
707        {
708            ErrorLogger.LogException("RendererUtilities","calculateMapScale",exc,Level.WARNING);
709        }
710        return 0;
711    }
712
713    // Overloaded method to return non-outline symbols as normal.
714    public static String setSVGSPCMColors(String symbolID, String svg, Color strokeColor, Color fillColor) {
715        return setSVGSPCMColors(symbolID, svg, strokeColor, fillColor, false,null,0,0);
716    }
717
718    public static Bitmap renderSVG(Rect bounds, String svg)
719    {
720        Bitmap bmp = null;
721        SVG mySVG = null;
722        try {
723            bmp = Bitmap.createBitmap(bounds.width(),bounds.height(), Bitmap.Config.ARGB_8888);
724            mySVG = SVG.getFromString(svg);
725            mySVG.setDocumentViewBox(bounds.left, bounds.top, bounds.width(), bounds.height());
726            Canvas canvas = new Canvas(bmp);
727            mySVG.renderToCanvas(canvas);
728        }
729        catch(Exception exc)
730        {
731            ErrorLogger.LogException("SinglePointRenderer", "RenderUnit", exc);
732        }
733        return bmp;
734    }
735}