Projekt

Obecné

Profil

Stáhnout (7.6 KB) Statistiky
| Větev: | Tag: | Revize:
1
using System;
2
using System.Collections;
3
using System.Collections.Generic;
4
using UnityEngine;
5
using UnityEngine.UI;
6

    
7
public class MapRenderer : MonoBehaviour
8
{
9
    [SerializeField]
10
    public SceneManager sceneManager;
11

    
12
    [SerializeField]
13
    private SpriteRenderer underlayTemplate;
14

    
15
    [SerializeField]
16
    private SpriteRenderer overlayTemplate;
17

    
18
    [SerializeField]
19
    public bool interactable = true;
20

    
21
    public Color minColor;
22

    
23
    public Color maxColor;
24

    
25

    
26
    private Vector3 startPos;
27

    
28
    private Vector3 startScale;
29

    
30

    
31
    public SpriteRenderer underlay;
32

    
33
    private Dictionary<string, SpriteRenderer> overlay = new Dictionary<string, SpriteRenderer>();
34

    
35
    private Dictionary<string, Image> overlay2 = new Dictionary<string, Image>();
36
    
37
    private bool first = true;
38

    
39

    
40
    // Start is called before the first frame update
41
    void Start()
42
    {
43
        startPos = transform.position;
44
        startScale = transform.localScale;
45
        
46
        Load();
47
        interactable = true;
48
    }
49

    
50
    void Update()
51
    {
52
        if (first)
53
        {
54
            first = false;
55

    
56
            // Get source directory
57
            string sourceDirectory = sceneManager.mapSourceDirectory;
58

    
59
            // Get file with asset relative positions
60
            TextAsset output = Resources.Load<TextAsset>($"{sourceDirectory}/output");
61

    
62
            if (output == null)
63
            {
64
                Debug.Log($"Layout file missing at {sourceDirectory}/output.csv. Returning.");
65
                return;
66
            }
67

    
68
            string[] lines = output.ToString().Split('\n');
69
            List<string> filenamesTMP = new List<string>();
70

    
71
            for (int i = 0; i < lines.Length; i++)
72
            {
73
                lines[i] = lines[i].Trim();
74
                if (lines[i].Length != 0 && !lines[i].StartsWith("//"))
75
                    filenamesTMP.Add(lines[i]);
76
            }
77

    
78
            lines = filenamesTMP.ToArray();
79

    
80
            for (int i = 0; i < lines.Length; i++)
81
            {
82
                var split = lines[i].Split(';');
83

    
84
                // Parse name minus the extension
85
                // X - percent offset from left btm corner
86
                // Y - percent offset from left btm corner
87
                var name = split[0].Substring(0, split[0].Length - 4);
88
                var xoff = float.Parse(split[1]);
89
                var yoff = float.Parse(split[2]);
90

    
91
                var img = overlay[name];
92

    
93
                if (img != null)
94
                {
95
                    var bounds = underlay.bounds;
96
                    var imgbounds = img.bounds;
97

    
98
                    var xshift = -bounds.size.x / 2 + imgbounds.size.x / 2 + bounds.size.x * (xoff / 100);
99
                    var yshift = -bounds.size.y / 2 + imgbounds.size.y / 2 + bounds.size.y * (yoff / 100);
100

    
101
                    img.gameObject.transform.position = bounds.center + new Vector3(xshift, yshift, 0);
102
                }
103
                else
104
                {
105
                    Debug.Log($"Error: Missing sprite {name}!");
106
                }
107
            }
108
        }
109
    }
110

    
111
    /// <summary>
112
    /// Loads map resources from an annotated directory
113
    /// A "layout.txt" file with directory annotation is required
114
    /// Creates the underlay map and building overlays addressable by their name as per the layout file
115
    /// </summary>
116
    /// <param name="sourceDirectory">Path to the source directory</param>
117
    public void Load()
118
    {
119
        // Get source directory
120
        string sourceDirectory = sceneManager.mapSourceDirectory;
121

    
122
        // Load directory layout
123
        // Read filenames
124
        // First filename is the underlay
125
        // All the others are the overlays, names as their respective building codes
126
        TextAsset layout = Resources.Load<TextAsset>($"{sourceDirectory}/layout");
127

    
128
        if (layout == null)
129
        {
130
            Debug.Log($"Layout file missing at {sourceDirectory}/layout.txt. Returning.");
131
            return;
132
        }
133

    
134
        string[] filenames = layout.ToString().Split('\n');
135

    
136
        // A map must contain at least an underlay
137
        if (filenames.Length < 1)
138
        {
139
            Debug.Log("Attempted to load an empty map. Returning.");
140
            return;
141
        }
142

    
143
        // Trim filenames (line breaks), remove empty line breaks and comments
144
        List<string> filenamesTMP = new List<string>();
145
        
146
        for (int i = 0; i < filenames.Length; i++)
147
        {
148
            filenames[i] = filenames[i].Trim();
149
            if (filenames[i].Length != 0 && !filenames[i].StartsWith("//"))
150
                filenamesTMP.Add(filenames[i]);
151
        }
152

    
153
        filenames = filenamesTMP.ToArray();
154

    
155
        // Load underlay sprite
156
        Sprite underlaySprite = Resources.Load<Sprite>($"{sourceDirectory}/{filenames[0]}");
157

    
158
        if (underlaySprite == null)
159
        {
160
            Debug.LogError($"Underlay sprite does not exist at path \"{sourceDirectory}/{filenames[0]}.png\". Returning.");
161
            return;
162
        }
163

    
164
        // Load overlay sprites
165
        Sprite[] overlaySprites = new Sprite[filenames.Length - 1];
166

    
167
        for (int i = 1; i < filenames.Length; i++)
168
        {
169
            overlaySprites[i-1] = Resources.Load<Sprite>($"{sourceDirectory}/{filenames[i]}");
170
            
171
            if (overlaySprites[i - 1] == null)
172
            {
173
                Debug.LogError($"Overlay sprite does not exist at path \"{sourceDirectory}/{filenames[i]}.png\". Returning.");
174
                return;
175
            }
176
        }
177

    
178
        // Create game objects
179
        underlay = Instantiate(underlayTemplate, transform);
180
        underlay.name = "Underlay";
181
        underlay.sprite = underlaySprite;
182

    
183
        for (int i = 1; i < filenames.Length; i++)
184
        {
185
            overlay[filenames[i]] = Instantiate(overlayTemplate, transform);
186
            overlay[filenames[i]].name = filenames[i];
187
            overlay[filenames[i]].sprite = overlaySprites[i - 1];
188
            overlay[filenames[i]].sortingOrder = i;
189
        }
190

    
191
        // Get references to remaining building sprites
192
        BuildingTag[] images = (FindObjectsOfType(typeof(BuildingTag)) as BuildingTag[]);
193
        foreach (var building in images)
194
        {
195
            overlay2[building.builidngName] = building.GetComponent<Image>();
196
            //Debug.Log(building.builidngName);
197
        }
198
    }
199

    
200
    public void SetColors(double[] predictions)
201
    {
202
        var buildings = Buildings.buildings;
203

    
204
        if (predictions.Length != buildings.Length)
205
        {
206
            Debug.LogError("Mismatch in prediction and building count.");
207
            return;
208
        }
209

    
210
        for (int i = 0; i < buildings.Length; i++)
211
        {
212
            if (predictions[i] < 0)
213
            {
214
                // TODO set different material
215
            }
216
            else
217
            {
218
                if (overlay.ContainsKey(buildings[i]))
219
                {
220
                    float a = overlay[buildings[i]].color.a;
221
                    var c = Color.Lerp(minColor, maxColor, (float)predictions[i] / 100f);
222
                    c.a = a;
223
                    overlay[buildings[i]].color = c;
224
                }
225

    
226
                else if (overlay2.ContainsKey(buildings[i]))
227
                {
228
                    RectTransform rt = overlay2[buildings[i]].GetComponent(typeof(RectTransform)) as RectTransform;
229
                    rt.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, 25 + ( 200 * ((float)predictions[i] / 100f)));
230
                    rt.ForceUpdateRectTransforms();
231

    
232
                    float a = overlay2[buildings[i]].color.a;
233
                    var c = Color.Lerp(minColor, maxColor, (float)predictions[i] / 100f);
234
                    c.a = a;
235
                    overlay2[buildings[i]].color = c;
236
                }
237

    
238
            }
239
        }
240

    
241
    }
242

    
243
}
(1-1/14)