Beispiel #1
0
    void LoadLevelFromUrl(byte[] data)
    {
        if (data == null)
        {
            return;
        }
        Parser.Tr2Level leveldata = Parser.Parse(data);
        if (leveldata != null)
        {
            //leveldata.Camera = m_Camera;
            //leveldata.Text3DPrefav = m_Text3D;
            if (m_SharedMaterial != null)
            {
                m_SharedMaterial.mainTexture = TextureUV.GenerateTextureTile(leveldata);
                m_Level = BuildLevel(leveldata, m_SharedMaterial, m_LevelName);
            }
            else
            {
#if UNITY_EDITOR
                EditorUtility.DisplayDialog("Error", "m_SharedMaterial is not set in GameObject: " + this.name, "OK");
#else
                Debug.LogError("m_SharedMaterial is not set in GameObject" + this.name);
#endif
            }
        }
    }
Beispiel #2
0
    protected override void OnUpdate()
    {
        // there is a better way to do this!
        if (hasInitialized == 0 && mBlockData.Length > 0)
        {
            // create all the textures we'll use
            textures      = new TextureUV[BLOCK_COUNT];
            isTransparent = new bool[BLOCK_COUNT];

            TextureUV tex = getTextureUV("blocks\\dirt.png");
            textures[(int)BlockTypes.Dirt]      = tex;
            isTransparent[(int)BlockTypes.Dirt] = false;
            tex = getTextureUV("blocks\\bedrock.png");
            textures[(int)BlockTypes.Bedrock]      = tex;
            isTransparent[(int)BlockTypes.Bedrock] = false;
            tex = getTextureUV("blocks\\glass_cyan.png");
            textures[(int)BlockTypes.Water]      = tex;
            isTransparent[(int)BlockTypes.Water] = false;
            tex = getTextureUV("blocks\\grass_top.png");
            textures[(int)BlockTypes.Grass]      = tex;
            isTransparent[(int)BlockTypes.Grass] = false;
            textures[(int)BlockTypes.Air]        = tex;
            isTransparent[(int)BlockTypes.Air]   = true;
            Debug.Log("Blocks are initialized");

            // initialize the world now that all blocks are created
            VoxelWorld.instance.Start();
            hasInitialized = 1;
        }
        else if (mBlockData.Length <= 0)
        {
            Debug.Log("Blocks are not yet initialized");
        }
    }
Beispiel #3
0
    void LoadLevel()
    {
        Parser.Tr2Level leveldata = LoadLevelFromFile(Settings.LevelFileLocalPath);
        if (leveldata != null)
        {
            //leveldata.Camera = m_Camera;
            //leveldata.Text3DPrefav = m_Text3D;
            if (m_SharedMaterial != null)
            {
                m_SharedMaterial.mainTexture = TextureUV.GenerateTextureTile(leveldata);
                m_Level = BuildLevel(leveldata, m_SharedMaterial, m_LevelName);
            }
            else
            {
#if UNITY_EDITOR
                EditorUtility.DisplayDialog("Error", "m_SharedMaterial is not set in GameObject:" + this.name, "OK");
#else
                Debug.LogError("m_SharedMaterial is not set in GameObject" + this.name);
#endif
            }
        }
        else
        {
            //Selected file is not tr2 type!
            Application.LoadLevel("Browser");
        }
    }
Beispiel #4
0
        public void read(Reader reader)
        {
            if (!reader.readBytes(4).SequenceEqual(signature))
            {
                reader.Close();
                throw new Exception("Invalid Model v4 signature");
            }

            ushort vertCount = reader.ReadUInt16();

            textureUVs.Clear();
            for (int t = 0; t < vertCount; t++)
            {
                TextureUV uv = new TextureUV();
                uv.u = reader.ReadSingle();
                uv.v = reader.ReadSingle();
                textureUVs.Add(uv);
            }

            int indexCount = reader.ReadUInt16() * 3;

            indices.Clear();
            for (int i = 0; i < indexCount; ++i)
            {
                indices.Add(reader.ReadUInt16());
            }

            ushort frameCount = reader.ReadUInt16();

            frames.Clear();
            for (int f = 0; f < frameCount; ++f)
            {
                Frame frame = new Frame();
                for (int v = 0; v < vertCount; ++v)
                {
                    Vertex vert = new Vertex();
                    vert.x = reader.ReadSingle();
                    vert.y = reader.ReadSingle();
                    vert.z = reader.ReadSingle();

                    vert.nx = reader.ReadSingle();
                    vert.ny = reader.ReadSingle();
                    vert.nz = reader.ReadSingle();
                    frame.vertices.Add(vert);
                }
                frames.Add(frame);
            }

            reader.Close();
        }
Beispiel #5
0
    static void SetFaceUVs(Vector2[] nonSharedUVs, int vertOrUVIdx0, int vertOrUVIdx1, int vertOrUVIdx2, Parser.Tr2ObjectTexture texObj)
    {
        ushort texTileIdx = (ushort)(texObj.Tile & 0x7ff);  //bind this textile in material?

        Parser.Tr2ObjectTextureVertex[] Vertices = texObj.Vertices;

        nonSharedUVs[vertOrUVIdx0].x = (float)TextureUV.AdjustTextureCoordinateX((byte)Vertices[0].Xpixel, (sbyte)Vertices[0].Xcoordinate, texTileIdx);
        nonSharedUVs[vertOrUVIdx0].y = (float)TextureUV.AdjustTextureCoordinateY((byte)Vertices[0].Ypixel, (sbyte)Vertices[0].Ycoordinate, texTileIdx);

        nonSharedUVs[vertOrUVIdx1].x = (float)TextureUV.AdjustTextureCoordinateX((byte)Vertices[1].Xpixel, (sbyte)Vertices[1].Xcoordinate, texTileIdx);
        nonSharedUVs[vertOrUVIdx1].y = (float)TextureUV.AdjustTextureCoordinateY((byte)Vertices[1].Ypixel, (sbyte)Vertices[1].Ycoordinate, texTileIdx);

        nonSharedUVs[vertOrUVIdx2].x = (float)TextureUV.AdjustTextureCoordinateX((byte)Vertices[2].Xpixel, (sbyte)Vertices[2].Xcoordinate, texTileIdx);
        nonSharedUVs[vertOrUVIdx2].y = (float)TextureUV.AdjustTextureCoordinateY((byte)Vertices[2].Ypixel, (sbyte)Vertices[2].Ycoordinate, texTileIdx);
    }
Beispiel #6
0
 protected virtual void Awake()
 {
     if (VoxelManager.Instance == null)
     {
         VoxelManager.Instance = this;
         DontDestroyOnLoad(this.gameObject);
     }
     else
     {
         Destroy(this.gameObject);
         return;
     }
     this.waitWhileUpdatingChunk = new WaitWhile(() =>
     {
         return(this.updatingChunk != null && this.updatingChunk.IsUpdating);
     });
     for (int i = 0; i < this.worlds.Count; i++)
     {
         WorldDefinition world = this.worlds[i];
         for (int j = 0; j < world.Blocks.Count; j++)
         {
             BlockDefinition block = world.Blocks[j];
             if (!this.blocks.Contains(block))
             {
                 this.blocks.Add(block);
                 this.blocksDictionary.Add(block.Identifier, block);
             }
         }
     }
     for (int j = 0; j < this.currentWorld.TexturesUV.Count; j++)
     {
         TextureUV textureUV = this.currentWorld.TexturesUV[j];
         if (!this.texturesUVDictionary.ContainsKey(textureUV.Texture))
         {
             this.texturesUVDictionary.Add(textureUV.Texture, textureUV.UV);
         }
     }
 }
Beispiel #7
0
    public static Mesh Draw(int index)
    {
        TextureUV map = textures[index];
        Mesh      d   = new Mesh();

        // put together the uvmap format
        Vector2[] uvMap = new Vector2[]
        {
            // bottom
            new Vector2(map.pixelStartX, map.pixelStartY),
            new Vector2(map.pixelStartX, map.pixelEndY),
            new Vector2(map.pixelEndX, map.pixelStartY),
            new Vector2(map.pixelEndX, map.pixelEndY),
            // top
            new Vector2(map.pixelStartX, map.pixelStartY),
            new Vector2(map.pixelStartX, map.pixelEndY),
            new Vector2(map.pixelEndX, map.pixelStartY),
            new Vector2(map.pixelEndX, map.pixelEndY),
            // back
            new Vector2(map.pixelStartX, map.pixelStartY),
            new Vector2(map.pixelStartX, map.pixelEndY),
            new Vector2(map.pixelEndX, map.pixelStartY),
            new Vector2(map.pixelEndX, map.pixelEndY),
            // front
            new Vector2(map.pixelStartX, map.pixelStartY),
            new Vector2(map.pixelStartX, map.pixelEndY),
            new Vector2(map.pixelEndX, map.pixelStartY),
            new Vector2(map.pixelEndX, map.pixelEndY),
            // right
            new Vector2(map.pixelStartX, map.pixelStartY),
            new Vector2(map.pixelStartX, map.pixelEndY),
            new Vector2(map.pixelEndX, map.pixelStartY),
            new Vector2(map.pixelEndX, map.pixelEndY),
            // left
            new Vector2(map.pixelStartX, map.pixelStartY),
            new Vector2(map.pixelStartX, map.pixelEndY),
            new Vector2(map.pixelEndX, map.pixelStartY),
            new Vector2(map.pixelEndX, map.pixelEndY),
        };

        // create the cube vertices
        List <Vector3> vertices =
            new List <Vector3>()
        {        // bottom face
            new Vector3(0, 0, 0),
            new Vector3(0, 0, 1),
            new Vector3(1, 0, 0),
            new Vector3(1, 0, 1),
            // top face
            new Vector3(0, 1, 0),
            new Vector3(0, 1, 1),
            new Vector3(1, 1, 0),
            new Vector3(1, 1, 1),
            // back face
            new Vector3(1, 0, 0),
            new Vector3(1, 0, 1),
            new Vector3(1, 1, 0),
            new Vector3(1, 1, 1),
            // front face
            new Vector3(0, 0, 0),
            new Vector3(0, 0, 1),
            new Vector3(0, 1, 0),
            new Vector3(0, 1, 1),
            // left face
            new Vector3(0, 0, 0),
            new Vector3(1, 0, 0),
            new Vector3(0, 1, 0),
            new Vector3(1, 1, 0),
            // right face
            new Vector3(0, 0, 1),
            new Vector3(1, 0, 1),
            new Vector3(0, 1, 1),
            new Vector3(1, 1, 1),
        };

        // create the indices
        List <int> triangles =
            new List <int>()
        {
            // bottom face
            0, 2, 1, 3, 1, 2,
            // top face
            0 + 4, 1 + 4, 2 + 4, 3 + 4, 2 + 4, 1 + 4,
            // back face
            0 + 8, 2 + 8, 1 + 8, 3 + 8, 1 + 8, 2 + 8,
            // front face
            0 + 12, 1 + 12, 2 + 12, 3 + 12, 2 + 12, 1 + 12,
            // left face
            0 + 16, 2 + 16, 1 + 16, 3 + 16, 1 + 16, 2 + 16,
            // right face
            0 + 20, 1 + 20, 2 + 20, 3 + 20, 2 + 20, 1 + 20,
        };

        d.vertices  = vertices.ToArray();
        d.triangles = triangles.ToArray();
        d.uv        = uvMap;
        d.RecalculateNormals();
        d.RecalculateBounds();

        return(d);
    }
    protected override void OnUpdate()
    {
        EntityManager entityManager = World.EntityManager;

        entityManager.CompleteAllJobs();

        // now do special stuff that can't be done in parallel!

        //
        // ALL COMMAND BUFFER CHANGES
        //

        // Drone Task System:
        while (DroneTaskSystem.addRemoveTags.Count > 0)
        {
            TagInfo tagInfo = DroneTaskSystem.addRemoveTags.Dequeue();
            if (tagInfo.shouldRemove == 1)
            {
                switch (tagInfo.type)
                {
                case Tags.Moving:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(MovingTag));
                    break;

                case Tags.NeedsTask:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(NeedsTaskTag));
                    break;

                case Tags.PerformTask:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(PerformTaskTag));
                    break;

                case Tags.Disable:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(Disabled));
                    break;

                default:
                    break;
                }
            }
            else
            {
                switch (tagInfo.type)
                {
                case Tags.Moving:
                    entityManager.AddComponent(tagInfo.entity, typeof(MovingTag));
                    break;

                case Tags.NeedsTask:
                    entityManager.AddComponent(tagInfo.entity, typeof(NeedsTaskTag));
                    break;

                case Tags.PerformTask:
                    entityManager.AddComponent(tagInfo.entity, typeof(PerformTaskTag));
                    break;

                case Tags.Disable:
                    entityManager.AddComponent(tagInfo.entity, typeof(Disabled));
                    break;

                default:
                    break;
                }
            }
        }

        while (DroneTaskSystem.componentSetInfo.Count > 0)
        {
            ComponentSetInfo setInfo = DroneTaskSystem.componentSetInfo.Dequeue();
            entityManager.SetComponentData(setInfo.entity, setInfo.plantComponent);
        }

        // farmer Task System:
        while (FarmerTaskSystem.addRemoveTags.Count > 0)
        {
            TagInfo tagInfo = FarmerTaskSystem.addRemoveTags.Dequeue();
            if (tagInfo.shouldRemove == 1)
            {
                switch (tagInfo.type)
                {
                case Tags.Moving:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(MovingTag));
                    break;

                case Tags.NeedsTask:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(NeedsTaskTag));
                    break;

                case Tags.PerformTask:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(PerformTaskTag));
                    break;

                case Tags.Disable:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(Disabled));
                    break;

                default:
                    break;
                }
            }
            else
            {
                switch (tagInfo.type)
                {
                case Tags.Moving:
                    entityManager.AddComponent(tagInfo.entity, typeof(MovingTag));
                    break;

                case Tags.NeedsTask:
                    entityManager.AddComponent(tagInfo.entity, typeof(NeedsTaskTag));
                    break;

                case Tags.PerformTask:
                    entityManager.AddComponent(tagInfo.entity, typeof(PerformTaskTag));
                    break;

                case Tags.Disable:
                    entityManager.AddComponent(tagInfo.entity, typeof(Disabled));
                    break;

                default:
                    break;
                }
            }
        }

        while (
            FarmerTaskSystem.componentSetInfo.Count > 0)
        {
            ComponentSetInfo setInfo = FarmerTaskSystem.componentSetInfo.Dequeue();
            entityManager.SetComponentData(setInfo.entity, setInfo.plantComponent);
        }

        // movement system:
        while (MovementSystem.addRemoveTags.Count > 0)
        {
            TagInfo tagInfo = MovementSystem.addRemoveTags.Dequeue();
            if (tagInfo.shouldRemove == 1)
            {
                switch (tagInfo.type)
                {
                case Tags.Moving:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(MovingTag));
                    break;

                case Tags.NeedsTask:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(NeedsTaskTag));
                    break;

                case Tags.PerformTask:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(PerformTaskTag));
                    break;

                case Tags.Disable:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(Disabled));
                    break;

                default:
                    break;
                }
            }
            else
            {
                switch (tagInfo.type)
                {
                case Tags.Moving:
                    entityManager.AddComponent(tagInfo.entity, typeof(MovingTag));
                    break;

                case Tags.NeedsTask:
                    entityManager.AddComponent(tagInfo.entity, typeof(NeedsTaskTag));
                    break;

                case Tags.PerformTask:
                    entityManager.AddComponent(tagInfo.entity, typeof(PerformTaskTag));
                    break;

                case Tags.Disable:
                    entityManager.AddComponent(tagInfo.entity, typeof(Disabled));
                    break;

                default:
                    break;
                }
            }
        }

        // perform tasks system:
        while (
            PerformTaskSystem.addRemoveTags.Count > 0)
        {
            TagInfo tagInfo = PerformTaskSystem.addRemoveTags.Dequeue();
            if (tagInfo.shouldRemove == 1)
            {
                switch (tagInfo.type)
                {
                case Tags.Moving:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(MovingTag));
                    break;

                case Tags.NeedsTask:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(NeedsTaskTag));
                    break;

                case Tags.PerformTask:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(PerformTaskTag));
                    break;

                case Tags.Disable:
                    entityManager.RemoveComponent(tagInfo.entity, typeof(Disabled));
                    break;

                default:
                    break;
                }
            }
            else
            {
                switch (tagInfo.type)
                {
                case Tags.Moving:
                    entityManager.AddComponent(tagInfo.entity, typeof(MovingTag));
                    break;

                case Tags.NeedsTask:
                    entityManager.AddComponent(tagInfo.entity, typeof(NeedsTaskTag));
                    break;

                case Tags.PerformTask:
                    entityManager.AddComponent(tagInfo.entity, typeof(PerformTaskTag));
                    break;

                case Tags.Disable:
                    entityManager.AddComponent(tagInfo.entity, typeof(Disabled));
                    break;

                default:
                    break;
                }
            }
        }

        while (PerformTaskSystem.componentSetInfo.Count > 0)
        {
            ComponentSetInfo setInfo = PerformTaskSystem.componentSetInfo.Dequeue();
            entityManager.SetComponentData(setInfo.entity, setInfo.plantComponent);
        }

        // Plant system:
        while (PlantSystem.componentSetInfo.Count > 0)
        {
            PlantSystem.ComponentTransInfo setInfo = PlantSystem.componentSetInfo.Dequeue();
            Translation trans = new Translation {
                Value = setInfo.trans
            };
            entityManager.SetComponentData(setInfo.entity, trans);
        }

        while (PlantSystem.plantCreationDeletionInfo.Count > 0)
        {
            Entity info = (Entity)PlantSystem.plantCreationDeletionInfo.Dequeue();
            // set deleted plants invisible and add them to the free plant list
            entityManager.AddComponent(info, typeof(Disabled));
            PlantSystem.freePlants.Enqueue(info);
        }

        //
        // ALL NON-PARALLEL OPERATIONS WITH SYSTEMS THAT AREN'T COMMAND BUFFER RELATED
        //

        //
        // PERFORM TASK SYSTEM
        //

        // parallelization would be difficult since multiple farmers can potentially
        // turn the same tile into a tilled tile
        // Would have to make it so that only one farmer can set the tile
        // to parallelize this
        while (PerformTaskSystem.tillChanges.Count > 0)
        {
            float2 pos = PerformTaskSystem.tillChanges.Dequeue();
            if ((int)pos.x != -1 && (int)pos.y != -1)
            {
                // set the uv's on the mesh
                // NOTE: set pos to be a specific number if you want to test it
                Mesh tmp = GridDataInitialization.getMesh((int)pos.x, (int)pos.y,
                                                          GridDataInitialization.BoardWidth);
                int width = GridDataInitialization.getMeshWidth(tmp, (int)pos.x,
                                                                (int)pos.y, GridDataInitialization.BoardWidth);

                NativeArray <float2> uvs = GridDataInitialization.getUVs((int)pos.x, (int)pos.y,
                                                                         GridDataInitialization.BoardWidth);

                TextureUV tex          = GridDataInitialization.textures[(int)GridDataInitialization.BoardTypes.TilledDirt];
                int       uvStartIndex = (GridDataInitialization.getPosForMesh((int)pos.y) +
                                          width *
                                          GridDataInitialization.getPosForMesh((int)pos.x)) * 4;
                //Debug.Log("changing uv at! " + pos + " " + width + " " + uvStartIndex + " " + GridDataInitialization.getPosForMesh((int)pos.x) +
                //    " " + GridDataInitialization.getPosForMesh((int)pos.y) + "array length: " + uv.Length);

                uvs[uvStartIndex] = new float2(tex.pixelStartX,
                                               tex.pixelStartY);
                uvs[uvStartIndex + 1] = new float2(tex.pixelStartX,
                                                   tex.pixelEndY);
                uvs[uvStartIndex + 2] = new float2(tex.pixelEndX,
                                                   tex.pixelEndY);
                uvs[uvStartIndex + 3] = new float2(tex.pixelEndX,
                                                   tex.pixelStartY);
                tmp.SetUVs(0, uvs);
                tmp.MarkModified();
            }
        }

        // max this gets run is once a frame and
        // many times it doesn't get run at all
        // not worth running in parallel
        if (PerformTaskSystem.plantsSold[0] > 0)
        {
            PerformTaskSystem.storeInfo.moneyForFarmers += PerformTaskSystem.plantsSold[0];
            PerformTaskSystem.storeInfo.moneyForDrones  += PerformTaskSystem.plantsSold[0];
            if (PerformTaskSystem.storeInfo.moneyForFarmers >= 10 &&
                GridDataInitialization.farmerCount < GridDataInitialization.MaxFarmers)
            {
                // spawn a new farmer - never more than 1 a frame
                PerformTaskSystem.storeInfo.moneyForFarmers -= 10;
                var instance = entityManager.Instantiate(GridDataInitialization.farmerEntity);
                GridDataInitialization.farmerCount++;
                int startX = System.Math.Abs(rand.NextInt()) % GridData.GetInstance().width;
                int startZ = System.Math.Abs(rand.NextInt()) % GridData.GetInstance().width;

                // Place the instantiated entity in a random position on the grid
                var position = new float3(startX, 2, startZ);
                entityManager.SetComponentData(instance, new Translation()
                {
                    Value = position
                });
                var farmerData = new MovementComponent
                {
                    startPos  = new float2(startX, startZ),
                    speed     = 2,
                    targetPos = new float2(startX, startZ)
                };
                var entityData = new EntityInfo {
                    type = -1
                };
                entityManager.SetComponentData(instance, farmerData);
                entityManager.AddComponentData(instance, entityData);
                // give his first command
                entityManager.AddComponent <NeedsTaskTag>(instance);
            }

            if (PerformTaskSystem.storeInfo.moneyForDrones >= 50 &&
                GridDataInitialization.droneCount < GridDataInitialization.MaxDrones)
            {
                // spawn a new drone
                PerformTaskSystem.storeInfo.moneyForDrones -= 50;
                var instance = entityManager.Instantiate(GridDataInitialization.droneEntity);
                GridDataInitialization.droneCount++;
                int startX = System.Math.Abs(rand.NextInt()) % GridData.GetInstance().width;
                int startZ = System.Math.Abs(rand.NextInt()) % GridData.GetInstance().width;

                // Place the instantiated entity in a random position on the grid
                var position = new float3(startX, 2, startZ);
                entityManager.SetComponentData(instance, new Translation()
                {
                    Value = position
                });
                var droneData = new MovementComponent
                {
                    startPos  = new float2(startX, startZ),
                    speed     = 2,
                    targetPos = new float2(startX, startZ),
                };
                var entityData = new EntityInfo {
                    type = -1
                };
                entityManager.SetComponentData(instance, droneData);
                entityManager.SetComponentData(instance, entityData);
                // give his first command
                entityManager.AddComponent <NeedsTaskTag>(instance);
            }
            PerformTaskSystem.plantsSold[0] = 0;
        }

        //
        // DRONE TASK SYSTEM:
        //

        // This is here as hash table removals can't
        // be done in parallel (with good reason!)
        GridData data = GridData.GetInstance();

        // take care of drones
        while (DroneTaskSystem.hashRemovalsDrone.Count > 0)
        {
            DroneTaskSystem.RemovalInfo remInfo = (DroneTaskSystem.RemovalInfo)DroneTaskSystem.hashRemovalsDrone.Dequeue();
            int        key = remInfo.key;
            EntityInfo value;
            if (data.gridStatus.TryGetValue(key, out value))
            {
                if (value.type == (int)Tiles.Plant)
                {
                    // this is a harvest, so try to remove and if we can
                    // then set up the entity to harvest it
                    if (data.gridStatus.ContainsKey(key))
                    {
                        data.gridStatus.Remove(key);
                        // set reserve data in plant component for this entity
                        entityManager.SetComponentData(value.specificEntity, new PlantComponent
                        {
                            timeGrown    = PlantSystem.MAX_GROWTH,
                            state        = (int)PlantState.None,
                            reserveIndex = remInfo.requestingEntity.Index,
                        });
                    }
                }
                else
                {
                    data.gridStatus.Remove(key);
                }
            }
        }

        //
        // FARMER TASK SYSTEM:
        //

        // This is here because hash table removals can't
        // be done in parallel.
        while (FarmerTaskSystem.hashRemovalsFarmer.Count > 0)
        {
            FarmerTaskSystem.RemovalInfo remInfo = FarmerTaskSystem.hashRemovalsFarmer.Dequeue();
            int        key = remInfo.key;
            EntityInfo value;
            if (data.gridStatus.TryGetValue(key, out value))
            {
                if (value.type == (int)Tiles.Till)
                {
                    float plantingHeight = 1.0f;
                    // we're planting here and need to add a plant entity
                    data.gridStatus.Remove(key);
                    float2 trans = new float2(GridData.getRow(key), GridData.getCol(key));
                    Entity instance;
                    if (PlantSystem.freePlants.Count > 0)
                    {
                        // this will become the new plant to put it back into use
                        instance = (Entity)PlantSystem.freePlants.Dequeue();
                        entityManager.RemoveComponent(instance, typeof(Disabled));
                    }
                    else
                    {
                        // we really have to instantiate the plant
                        int nextRandom = UnityEngine.Mathf.Abs(rand.NextInt()) % GridDataInitialization.DIFF_PLANT_COUNT;
                        instance = entityManager.Instantiate(GridDataInitialization.plantEntity[nextRandom]);
                        Rotation rotation = entityManager.GetComponentData <Rotation>(instance);
                        var      newRot   = rotation.Value * Quaternion.Euler(0, 0, 90);
                        entityManager.SetComponentData(instance, new Rotation {
                            Value = newRot
                        });
                    }

                    EntityInfo plantInfo = new EntityInfo {
                        type = (int)Tiles.Plant, specificEntity = instance
                    };
                    if (data.gridStatus.TryAdd(key, plantInfo))
                    {
                        float3 pos = new float3((int)trans.x, plantingHeight, (int)trans.y);
                        entityManager.SetComponentData(instance, new Translation {
                            Value = pos
                        });
                        entityManager.SetComponentData(instance, new NonUniformScale {
                            Value = new float3(1.0f, 1.0f, 1.0f)
                        });
                        // for some reason the original plant mesh creation happens on the wrong axis,
                        // so we have to rotate it 90 degrees
                        entityManager.SetComponentData(instance, new PlantComponent
                        {
                            timeGrown = 0,
                            state     = (int)PlantState.Growing,
                        });
                        //Debug.Log("added grid plant " + instance.Index);
                    }
                }
                else
                if (value.type == (int)Tiles.Plant)
                {
                    // this is a harvest, so try to remove and if we can
                    // then set up the entity to harvest it
                    if (data.gridStatus.ContainsKey(key))
                    {
                        data.gridStatus.Remove(key);
                        // set reserve data in plant component for this entity
                        entityManager.SetComponentData(value.specificEntity, new PlantComponent
                        {
                            timeGrown    = PlantSystem.MAX_GROWTH,
                            state        = (int)PlantState.None,
                            reserveIndex = remInfo.requestingEntity.Index,
                        });
                    }
                }
                else
                {
                    data.gridStatus.Remove(key);
                }
            }
        }
    }
Beispiel #9
0
        public void read(Reader reader)
        {
            if (!reader.readBytes(4).SequenceEqual(signature))
            {
                reader.Close();
                throw new Exception("Invalid Model v5 signature");
            }

            flags           = reader.ReadByte();
            faceVertexCount = reader.ReadByte();
            if (faceVertexCount != 3 && faceVertexCount != 4)
            {
                throw new Exception("Detected Vertex Type wasn't Tris or Quads! RSDKv5 doesn't support other N-gons!");
            }

            ushort vertexCount = reader.ReadUInt16();
            ushort frameCount  = reader.ReadUInt16();

            textureUVs.Clear();
            if (hasTextures)
            {
                for (int t = 0; t < vertexCount; ++t)
                {
                    TextureUV uv = new TextureUV();
                    uv.u = reader.ReadSingle();
                    uv.v = reader.ReadSingle();
                    textureUVs.Add(uv);
                }
            }

            colours.Clear();
            if (hasColours)
            {
                for (int c = 0; c < vertexCount; ++c)
                {
                    Color colour = new Color();
                    colour.B = reader.ReadByte();
                    colour.G = reader.ReadByte();
                    colour.R = reader.ReadByte();
                    colour.A = reader.ReadByte();
                    colours.Add(colour);
                }
            }

            ushort indexCount = reader.ReadUInt16();

            indices.Clear();
            for (int i = 0; i < indexCount; ++i)
            {
                indices.Add(reader.ReadUInt16());
            }

            frames.Clear();
            for (int f = 0; f < frameCount; ++f)
            {
                Frame frame = new Frame();
                for (int v = 0; v < vertexCount; ++v)
                {
                    Vertex vert = new Vertex();
                    vert.x = reader.ReadSingle();
                    vert.y = reader.ReadSingle();
                    vert.z = reader.ReadSingle();

                    if (hasNormals)
                    {
                        vert.nx = reader.ReadSingle();
                        vert.ny = reader.ReadSingle();
                        vert.nz = reader.ReadSingle();
                    }
                    frame.vertices.Add(vert);
                }
                frames.Add(frame);
            }
        }
Beispiel #10
0
    public static void Create()
    {
        //procedure to store last browsed path
        string path = PlayerPrefs.GetString("last_browsed_path", "");

        if (path == "")
        {
            path = EditorUtility.OpenFilePanel("Open Tomb Raider II Level File (*.TR2)", Application.dataPath, "*.tr2; *.TR2");
        }
        else
        {
            path = EditorUtility.OpenFilePanel("Open Tomb Raider II Level File (*.TR2)", path, "*.tr2; *.TR2");
        }
        PlayerPrefs.SetString("last_browsed_path", Path.GetDirectoryName(path));

        if (path != null)
        {
            Settings.LevelFileLocalPath = path;
            Parser.Tr2Level leveldata = LoadLevelFromFile(Settings.LevelFileLocalPath);
            if (leveldata != null)
            {
                leveldata.Camera       = null;
                leveldata.Text3DPrefav = null;

                // generate shared texture
                Texture2D shared_texture = TextureUV.GenerateTextureTile(leveldata);
                if (!Directory.Exists(Application.dataPath + m_SharedTexturePath))
                {
                    Directory.CreateDirectory(Application.dataPath + m_SharedTexturePath);
                }
                //if(!File.Exists(Application.dataPath + "/Level Texture/" + Level.m_LevelName + ".png"))
                //File.WriteAllBytes(Application.dataPath + m_SharedTexturePath + Level.m_LevelName + ".png",shared_texture.EncodeToPNG());
                FileStream   fstream = File.Open(Application.dataPath + m_SharedTexturePath + m_LevelName + ".png", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                BinaryWriter bw      = new BinaryWriter(fstream);
                bw.Write(shared_texture.EncodeToPNG());
                bw.Close();

                //load shared texture
                //Refresh assete database for newly created texture
                AssetDatabase.Refresh();

                TextureImporter teximp = TextureImporter.GetAtPath("Assets" + m_SharedTexturePath + m_LevelName + ".png") as TextureImporter;
                if (teximp == null)
                {
                    EditorUtility.DisplayDialog("Error", "Assets" + m_SharedTexturePath + m_LevelName + ".png" + " is not found in Assets ", "OK");
                    return;
                }
                else
                {
                                        #if (UNITY_5_3_OR_NEWER || UNITY_5_3)
                    teximp.alphaSource = TextureImporterAlphaSource.FromInput;
                    teximp.filterMode  = FilterMode.Bilinear;
                    teximp.wrapMode    = TextureWrapMode.Clamp;
                    //teximp.sRGBTexture = true;
                    teximp.textureType        = TextureImporterType.Default;
                    teximp.maxTextureSize     = 4096;
                    teximp.mipmapEnabled      = false;
                    teximp.textureCompression = TextureImporterCompression.Uncompressed;
                                        #else
                    teximp.filterMode       = FilterMode.Bilinear;
                    teximp.grayscaleToAlpha = false;
                    teximp.textureFormat    = TextureImporterFormat.ARGB32;
                    teximp.wrapMode         = TextureWrapMode.Clamp;
                    teximp.maxTextureSize   = 4096;
                    teximp.mipmapEnabled    = false;
                                        #endif
                }

                //refresh assets to apply changes
                AssetDatabase.Refresh();
                //reimport is need after import setting modification
                AssetDatabase.ImportAsset("Assets" + m_SharedTexturePath + m_LevelName + ".png");

                //load shared material
                Material shared_material = (Material )AssetDatabase.LoadAssetAtPath("Assets" + m_SharedMaterialPath, typeof(Material));

                if (shared_material == null)
                {
                    EditorUtility.DisplayDialog("Error", "Assets" + m_SharedMaterialPath + " is not found in Assets ", "OK");
                    return;
                }

                shared_material.mainTexture = (Texture)AssetDatabase.LoadAssetAtPath("Assets" + m_SharedTexturePath + m_LevelName + ".png", typeof(Texture));
                m_Level = BuildLevel(leveldata, shared_material, m_LevelName);
            }
        }
    }