LoadEnv.cs 12.8 KB
Newer Older
BRUNEAU Julien's avatar
BRUNEAU Julien committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/* Crowd Simulator Engine
** Copyright (C) 2018 - Inria Rennes - Rainbow - Julien Pettre
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**
** Authors: Julien Bruneau
**
** Contact: crowd_group@inria.fr
*/

using UnityEngine;
using System.Collections;
using System.IO;
26
using System.Collections.Generic;
BRUNEAU Julien's avatar
BRUNEAU Julien committed
27
28
29
30
31

/// <summary>
/// Main manager: Load the scene, create all the agents and manage users input
/// </summary>
public class LoadEnv : MonoBehaviour
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
32
33
{

BRUNEAU Julien's avatar
BRUNEAU Julien committed
34
#region attributes
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
35
    List<GameObject> avatars;                               // List of agents
BRUNEAU Julien's avatar
BRUNEAU Julien committed
36
37
38
    public GameObject cam;                                  // Scene camera
    private CamRecorder cam_Rec;                            // Control scene recording
    private CamMvt cam_Movement;                            // Control camera movement behavior
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
39
    private MenuManager menuM;								// Control the starting menu
BRUNEAU Julien's avatar
BRUNEAU Julien committed
40
41
42
43
44
45
46
47
48
    //private float rotSpeed = 5;                             

    // --------------------------
    // CAMERA MOVEMENT PARAMETERS
    const float camTranslationSpeed = 25.0f;                // Camera translation speed
    const float camShiftPower = 250.0f;                     // Shift effect on camera speed
    const float camMaxShiftPower = 1000.0f;                 // Maximun shift effect on camera speed
    const float camRotationSpeed = 0.25f;                   // Rotation speed
    Vector3 lastMouse = new Vector3(255, 255, 255);         // Last mouse position to check its movement
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
49
    float camShiftHold = 1.0f;                              // Control the effect of shift with holding time      
BRUNEAU Julien's avatar
BRUNEAU Julien committed
50
#endregion
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
51
52


BRUNEAU Julien's avatar
BRUNEAU Julien committed
53
54
55
56
    /// <summary>
    /// Scene and agents initialization
    /// </summary>
    void Start()
57
58
59
60
61
62
63
64
65
    {
        avatars = new List<GameObject>();
        cam_Rec = cam.GetComponent<CamRecorder>();
        cam_Movement = cam.GetComponent<CamMvt>();

        cam_Rec.enabled = false;
        cam_Movement.enabled = false;

        menuM = gameObject.GetComponent<MenuManager>();
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
66
67
68
69
70
71
    }

    /// <summary>
    /// Load a scenario: create stage and spawn agents
    /// </summary>
    /// <param name="trajDir">The path to the scenario file</param>
72
    public void loadScenario(string trajDir)
BRUNEAU Julien's avatar
BRUNEAU Julien committed
73
74
75
76
77
78
79
80
81
82
    {
        // --------------------------------------------------
        // SET RANDOM SEED TO HAVE SAME RESULTS AT EVERY RUNS
        Random.InitState(75482);

        // ---------------------------------
        // INITIALIZE SCENE FROM CONFIG FILE

        // -------------
        // CAMERA CONFIG
83
84
        cam_Rec.enabled = true;
        cam_Movement.enabled = true;
BRUNEAU Julien's avatar
BRUNEAU Julien committed
85
86
87
88
89
90
        cam.transform.position = ConfigReader.camPosition;
        cam.transform.rotation = Quaternion.Euler(ConfigReader.camRotation);
        cam_Movement.lookAt_Id = ConfigReader.camLookAtTarget;
        cam_Movement.follow_Id = ConfigReader.camFollowTarget;
        cam_Movement.follow_LockX = !ConfigReader.camFollowOnX;
        cam_Movement.follow_LockZ = !ConfigReader.camFollowOnY;
91

BRUNEAU Julien's avatar
BRUNEAU Julien committed
92
93
94
95
96
97
98
        // -------------
        // RECORD CONFIG
        cam_Rec.record = ConfigReader.recording;
        cam_Rec.timeToStart = ConfigReader.recordingStart;
        cam_Rec.timeToStop = ConfigReader.recordingEnd;
        cam_Rec.framerate = ConfigReader.recordingFramerate;

99
100
101
102
        //FB don't know why there this check
        if (ConfigReader.recordingSaveDir[1] != ':')
            cam_Rec.saveDir = Directory.GetCurrentDirectory().Replace("\\", "/") + "/" + ConfigReader.recordingSaveDir;
        else
BRUNEAU Julien's avatar
BRUNEAU Julien committed
103
            cam_Rec.saveDir = ConfigReader.recordingSaveDir;
104
105
        Camera.main.GetComponent<CamRecorder>().Init();
        InitDeepRecorders();
BRUNEAU Julien's avatar
BRUNEAU Julien committed
106

107
108
109
110
111
112
        // ---------------------
        // CLEAR PREVIOUS AGENTS
        foreach (GameObject a in avatars)
        {
            Destroy(a);
        }
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
113
114
115
116
        avatars.Clear();

        // -------------
        // CREATE AGENTS
117
        DirectoryInfo dir = new DirectoryInfo(trajDir);
BRUNEAU Julien's avatar
BRUNEAU Julien committed
118
119
120
121
        FileInfo[] info = dir.GetFiles("*.csv");
        if (info.Length == 0)
            info = dir.GetFiles("*.txt");

122
        var crowdParentObject = new GameObject("Crowd");
BRUNEAU Julien's avatar
BRUNEAU Julien committed
123
124
125
126
127
        FollowTrajectory tmpFollower;
        int i = 0;
        object testRocketMan = Resources.Load("Prefabs/RocketBox/male/prefab_light/LS_m001_light");
        foreach (FileInfo f in info)
        {
128
129
130
131
132
133
134
135
136
137
138
            // ------------------------------------------------------------
            // IF NO ROCKETMAN (PROPRIETARY ASSETS), USE PLASTICMAN INSTEAD
            GameObject character = (testRocketMan!=null) ? CreateAgent_RocketBox(i) : CreateAgent_PlasticMan(i);
            character.transform.parent = crowdParentObject.transform;
            avatars.Add(character);

            // ---------------------
            // SET NAME, TAG, AND ID
            character.name += i.ToString("D4");
            character.tag = "Player";
            character.GetComponent<GetMemberPosition>().ID = i;
BRUNEAU Julien's avatar
BRUNEAU Julien committed
139
140
141
142

            // ----------------------------------
            // FOLLOWTRAJECTORY SCRIPT MANAGEMENT
            // Setup of the CSV filename and disable the start synchro
143
            tmpFollower = character.GetComponent<FollowTrajectory>();
BRUNEAU Julien's avatar
BRUNEAU Julien committed
144
            tmpFollower.SetCsvFilename(f.FullName);
145
            tmpFollower._SyncLaunchWithTrajectory = true; // start the character at the csv time
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
146

BRUNEAU Julien's avatar
BRUNEAU Julien committed
147
            i++;
BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
148
149
150
        }

        cam_Movement.updateTargetedObject();
151

BRUNEAU Julien's avatar
BRUNEAU Julien committed
152
153
    }

154
155
156
157
    /// <summary>
    /// Manage which deep recorder is used and initialize it
    /// </summary>
    private void InitDeepRecorders()
158
    {        
159
160
161
162
163
        GameObject DeepRecorders = GameObject.FindGameObjectWithTag("DeepRecorders");
        if (ConfigReader.recordingBodyBoundingBoxes)
            DeepRecorders.GetComponent<BodyBoundingBoxRecorder>().Init(ConfigReader.recordingSaveDir);
        else
            DeepRecorders.GetComponent<BodyBoundingBoxRecorder>().enabled = false;
164
165
166
167
168

        if (ConfigReader.recordingHeadBoundingBoxes)
            DeepRecorders.GetComponent<HeadBoundingBoxRecorder>().Init(ConfigReader.recordingSaveDir);
        else
            DeepRecorders.GetComponent<HeadBoundingBoxRecorder>().enabled = false;
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    }

    Color? GetColorForAgentId(int id)
    {
        if (ConfigReader.agentsColor != null && ConfigReader.agentsColor.Count > 0)
        {
            foreach (ConfigAgentColor c in ConfigReader.agentsColor)
            {
                if (id > c.firstAgent - 1 && id < c.lastAgent + 1 && (id - c.firstAgent) % c.step == 0)
                    return new Color(c.red, c.green, c.blue, 1);
            }
        }
        return null;
    }

    Material CreateMaterialWithColor(Color color)
    {
        var tmpMaterial = new Material(Shader.Find("Legacy Shaders/Diffuse"));
        tmpMaterial.color = color;
        return tmpMaterial;
    }

    string GetModelName_RocketBox(int id)
    {
        string path;
        int modelId;
        if (id % 2 == 0)
        {
            path = "Prefabs/m";
            modelId = id / 2;
        }
        else
        {
            path = "Prefabs/f";
            modelId = (id - 1) / 2;
        }
        modelId = (modelId % 20) + 1;
        return "RocketBox/" + path + modelId.ToString("D3");
    }

    GameObject CreateAgent_RocketBox(int id)
    {
        // -------------------
        // LOAD AGENT IN UNITY
        GameObject gameObject = Instantiate(Resources.Load<GameObject>(GetModelName_RocketBox(id)));
        gameObject.AddComponent<GetMemberPositionRocketBox>();

        // ---------------------------------------------
        // SET AGENT'S COLOR WHEN SPECIFY IN CONFIG FILE
        var tmpColor = GetColorForAgentId(id);
        if (tmpColor.HasValue)
        {
            var tmpMaterial = CreateMaterialWithColor(tmpColor.Value);
            Material[] mats = new Material[] { tmpMaterial, tmpMaterial, tmpMaterial };

            SkinnedMeshRenderer[] rendererList = gameObject.GetComponentsInChildren<SkinnedMeshRenderer>();
            foreach (SkinnedMeshRenderer renderer in rendererList)
                renderer.materials = mats;
        }

        return gameObject;
    }

    GameObject CreateAgent_PlasticMan(int id)
    {
        // -------------------
        // LOAD AGENT IN UNITY
        GameObject gameObject = Instantiate(Resources.Load<GameObject>("PlasticMan/plasticman"));
237
238
239

        // -------------------
        // SET BOUNDING BOXES ITEM
240
        gameObject.AddComponent<GetMemberPositionPlasticMan>();
241
242
243
        GameObject headBoundingBox = Instantiate(Resources.Load<GameObject>("HeadBoundingBoxes/Hbb_PlasticMan"));
        Transform Neck = gameObject.transform.Find("Plasticman:Reference/Plasticman:Hips/Plasticman:Spine/Plasticman:Spine1/Plasticman:Spine2/Plasticman:Spine3/Plasticman:Neck");
        headBoundingBox.transform.parent = Neck;
244
245
246
247
248
249
250
251
252
253
254
255
256

        // -----------------
        // SET AGENT'S COLOR
        var tmpColor = GetColorForAgentId(id);
        if (!tmpColor.HasValue)
            tmpColor = new Color(Random.value, Random.value, Random.value, 1);

        var tmpRenderer = gameObject.GetComponentInChildren<SkinnedMeshRenderer>();
        tmpRenderer.material = CreateMaterialWithColor(tmpColor.Value);

        return gameObject;
    }

BRUNEAU Julien's avatar
Master    
BRUNEAU Julien committed
257
258
259
    /// <summary>
    /// Update camera state
    /// </summary>
260
261
262
263
264
265
    private void Update()
    {
        ConfigReader.camPosition = cam.transform.position;
        ConfigReader.camRotation = cam.transform.rotation.eulerAngles;
    }

BRUNEAU Julien's avatar
BRUNEAU Julien committed
266
267
268
    /// <summary>
    /// Manage users Input
    /// </summary>
269
    void LateUpdate()
BRUNEAU Julien's avatar
BRUNEAU Julien committed
270
271
272
    {
        // -------------------
        // ESCAPE => EXIT APPS
273
        if (Input.GetKeyDown(KeyCode.Escape) == true)
BRUNEAU Julien's avatar
BRUNEAU Julien committed
274
        {
275
            menuM.toogleMenu();
BRUNEAU Julien's avatar
BRUNEAU Julien committed
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
        }

        // -------------------------------
        // MOUSE + RCLICK => ROTATE CAMERA
        if (Input.GetMouseButton(1))
        {
            lastMouse = Input.mousePosition - lastMouse;
            lastMouse = new Vector3(-lastMouse.y * camRotationSpeed, lastMouse.x * camRotationSpeed, 0);
            lastMouse = new Vector3(cam.transform.eulerAngles.x + lastMouse.x, cam.transform.eulerAngles.y + lastMouse.y, 0);

            // Block all the way up or down to prevent glitches
            if (lastMouse.x > 180 && lastMouse.x < 270)
                lastMouse.x = 270;
            else if (lastMouse.x > 90 && lastMouse.x < 180)
                lastMouse.x = 90;

            cam.transform.eulerAngles = lastMouse;
        }
        lastMouse = Input.mousePosition;

        // -----------------------------------------
        // ARROWS, SHIFT, CTRL => CAMERA TRANSLATION
        Vector3 p = new Vector3();
        if (Input.GetKey(KeyCode.UpArrow))
        {
            p += new Vector3(0, 0, 1);
        }
        if (Input.GetKey(KeyCode.DownArrow))
        {
            p += new Vector3(0, 0, -1);
        }
        if (Input.GetKey(KeyCode.LeftArrow))
        {
            p += new Vector3(-1, 0, 0);
        }
        if (Input.GetKey(KeyCode.RightArrow))
        {
            p += new Vector3(1, 0, 0);
        }
315
        if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
BRUNEAU Julien's avatar
BRUNEAU Julien committed
316
317
318
319
320
321
322
323
324
325
326
327
        {
            camShiftHold += Time.fixedUnscaledDeltaTime;
            p = p * Mathf.Max(camShiftHold * camShiftPower, camMaxShiftPower);
        }
        else
        {
            camShiftHold = Mathf.Clamp(camShiftHold * 0.5f, 1f, 1000f);
            p = p * camTranslationSpeed;
        }

        p = p * Time.fixedUnscaledDeltaTime;
        Vector3 newPosition = cam.transform.position;
328
        if (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl))
BRUNEAU Julien's avatar
BRUNEAU Julien committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
        { //If player wants to move on X and Z axis only
            cam.transform.Translate(p);
            newPosition.x = cam.transform.position.x;
            newPosition.z = cam.transform.position.z;
            cam.transform.position = newPosition;
        }
        else
        {
            cam.transform.Translate(p);
        }

        // --------------------------
        // F5 => SAVE CAMERA POSITION
        if (Input.GetKeyDown(KeyCode.F5))
        {
344
            menuM.saveConfig();
BRUNEAU Julien's avatar
BRUNEAU Julien committed
345
346
347
348
349
350
351
352
353
354
355
356
357
        }

        // ----------------------
        // SPACE => PAUSE UNPAUSE
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (Time.timeScale == 0)
                Time.timeScale = 1;
            else
                Time.timeScale = 0;
        }
    }
}