Exemplo n.º 1
0
        /// <summary>
        /// Load initial resources.
        /// </summary>
        public virtual void LoadResources()
        {
            // - Loads essential shaders
            ShaderManager.LoadShader <DefaultShader>();

            var Rectangle = VertexManager.Alloc(4);

            Rectangle[0] = new VertexData(new Vector3(-0.5F, -0.5F, 0F), Color4.Black);
            Rectangle[1] = new VertexData(new Vector3(0.5F, -0.5F, 0F), Color4.Black);
            Rectangle[2] = new VertexData(new Vector3(0.5F, 0.5F, 0F), Color4.Black);
            Rectangle[3] = new VertexData(new Vector3(-0.5F, 0.5F, 0F), Color4.Black);

            Rectangle.Invalidate();

            var Indexes = IndexManager.Alloc(6);

            Indexes[0] = 0;
            Indexes[1] = 1;
            Indexes[2] = 2;
            Indexes[3] = 2;
            Indexes[4] = 3;
            Indexes[5] = 0;

            Indexes.Invalidate();
        }
Exemplo n.º 2
0
    //Method used to add a new line renderer vertex and a new vertex sphere.
    public GameObject addVertex(Vector3 pos, int vertexID, GameObject selectedVertex)
    {
        pos = rotateVertex(pos, -getLocalRotation());

        //Get the vertex spheres that are children of this object
        List <GameObject> children = getChildrenVertices();

        //Add the selected vertex to that list (as it won't be a child of the object if it's selected), and sort the list.
        if (selectedVertex)
        {
            children.Add(selectedVertex);
        }

        children.Sort(sortByVertexID);


        //for loop to go through each vertex and update it's vertexID if it's PAST the selected vertex
        foreach (GameObject child in children)
        {
            VertexManager childsVM = child.GetComponent <VertexManager>();
            if (childsVM.getVertexID() >= vertexID)
            {
                childsVM.setVertexID(childsVM.getVertexID() + 1);
            }
        }

        //create a new vertex sphere
        GameObject    newVert    = drawVert(pos, vertexID, false);
        VertexManager newVertsVM = newVert.GetComponent <VertexManager>();

        //make the new vertex's size and "length" field equal to the one currently selected
        if (selectedVertex)
        {
            newVert.transform.localScale = selectedVertex.transform.lossyScale;
            newVertsVM.setVertexLength(selectedVertex.GetComponent <VertexManager>().getVertexLength());
        }
        //add this new vertex to the dictionary of vertexmanagers with its current timing
        timingDict[newVertsVM.getVertexTiming()].Add(newVertsVM);
        //add this new vertex to the list of children, and sort the list again.
        children.Add(newVert);
        children.Sort(sortByVertexID);
        //create a Vector3[] to hold the positions that the line renderer will be set to.
        Vector3[] finalPositions = new Vector3[children.Count];
        //translate the position of every child and add it to finalPositions.
        for (int i = 0; i < children.Count; i++)
        {
            Vector3 tempPos = children[i].transform.position;
            tempPos = rotateVertex(tempPos, -getLocalRotation());
            //tempPos = vertexRotationTwo(tempPos, localRotation+270, i);
            finalPositions[i] = tempPos;
        }

        //create a new vertex on the line renderer and set it's positions to finalPositions.
        attachedLR.positionCount += 1;
        attachedLR.SetPositions(finalPositions);

        boxColliderManager.addBoxCollider(vertexID);

        return(newVert);
    }
 //method called when user wants to remove the vertex currently being held from the game.
 public void removeVertex()
 {
     //if statement to check whether a vertex is currently being held:
     if (!currentRigidBody)
     {
         //if no held vertex, try to remove one that may be being hovered over.
         GameObject nearestVertex = hoverOverVertex();
         if (nearestVertex)
         {
             nearestVertex.transform.parent = gameObject.transform;
             VertexManager nearestVertexManager = nearestVertex.GetComponent <VertexManager>();
             nearestVertexManager.getParentsLineManager().removeVertex(nearestVertex.transform.position, nearestVertexManager.getVertexID(), nearestVertex);
             resetVariables();
         }
     }
     else if (isEditable(currentVertexManager.getVertexID(), currentVertexManager.getBaseLineParent().gameObject))
     {
         //if statement won't be entered if the id of the vertex being held is 1 (because that vertex is needed)
         currentVertexManager.getParentsLineManager().removeVertex(transform.position, currentVertexManager.getVertexID(), currentGameObject);
         resetVariables();
     }
     else
     {
         return;
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Initialize the graphic library.
        /// </summary>
        public override void Initialize()
        {
            base.Initialize();

            // - Create a Vulkan instance, this instance must be alive during all the game execution
            Library.Initialize(TargetSurface);

            // - Makes a new device manager
            PhysicalDevice.Initialize(TargetSurface);

            // - Initialize the physical device on this drawing area
            GraphicDevice.Initialize();

            // - Initialize index and vert manager
            VertexManager.Setup();
            IndexManager.Setup();

            // - Makes syncronization semaphores and fances CPU<->GPU
            for (int i = 0; i < MaxFrameInFlight; ++i)
            {
                CommandBuffers.Add(null);
                Commands.Add(GraphicDevice.Handle.CreateCommandPool(GraphicDevice.GraphicQueueIndex, CommandPoolCreateFlags.ResetCommandBuffer));
                ImageAvailableSemaphores.Add(GraphicDevice.Handle.CreateSemaphore());
                RenderFinishedSemaphores.Add(GraphicDevice.Handle.CreateSemaphore());
                InFlightFences.Add(GraphicDevice.Handle.CreateFence(FenceCreateFlags.Signaled));
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// This call configure the graphic library for the new device instance.
        /// </summary>
        public override void InvalidateDevice()
        {
            base.InvalidateDevice();

            // - Wait the GPU (we must operate only when GPU is idle)
            GraphicDevice.Handle.WaitIdle();

            // - Dispose render pass
            DefaultRenderPass.Dispose();

            // - Dispose the pipeline
            Pipeline.Dispose();

            // - Dipose current swapchain
            Swapchain.Dispose();

            // - Dispose current VK surface
            DrawingSurface.Dispose();

            // - Dispose vertex and index managers
            VertexManager.Dispose();
            IndexManager.Dispose();

            // - Release all VK shaders
            ShaderManager.Dispose();

            for (int i = 0; i < MaxFrameInFlight; ++i)
            {
                if (CommandBuffers[i] != null)
                {
                    foreach (var buffer in CommandBuffers[i])
                    {
                        buffer.Reset();
                    }
                    Commands[i].FreeCommandBuffers(CommandBuffers[i]);
                }
            }

            foreach (Fence fence in InFlightFences)
            {
                fence.Destroy();
            }
            foreach (Semaphore sem in ImageAvailableSemaphores)
            {
                sem.Destroy();
            }
            foreach (Semaphore sem in RenderFinishedSemaphores)
            {
                sem.Destroy();
            }

            // - Dispose device
            GraphicDevice.Dispose();

            // - Initialize device
            Initialize();

            // - Reconfigure the renderer
            ConfigureRendering();
        }
Exemplo n.º 6
0
    //the main method for this script, used to go through all vertices (spheres) in the environment and update their positions
    private void getVertexStats()
    {
        //get all vertices (spheres)
        allVertices = GameObject.FindGameObjectsWithTag("Vertex");
        foreach (GameObject vertex in allVertices)
        {
            //get each vertexManager attached to current vertex (sphere)
            vertexManager = vertex.GetComponent <VertexManager>();

            //Set the vector variables according to the vertice (sphere) position. To do maths on later.
            xVector.Set(vertex.transform.position.x, 0f, 0f);
            yVector.Set(0f, vertex.transform.position.y, 0f);
            zVector.Set(0f, 0f, vertex.transform.position.z);

            //calculate the distance between the vertices (sphere) x, y, and z cords from the center.
            xDist = Vector3.Distance(gameObject.transform.position, xVector);
            yDist = Vector3.Distance(gameObject.transform.position, yVector);
            zDist = Vector3.Distance(gameObject.transform.position, zVector);

            if (vertexManager != null && vertexManager.getVertexID() != 0 && vertexManager.getVertexID() != vertexManager.getParentsLineManager().getNumberOfVertices() - 1)
            {
                //setting vertex volume by passing x^2 + z^2 to convert volume
                vertexManager.setVertexVolume(convertVolume((xDist * xDist) + (zDist * zDist)));

                //setting vertex timing by passing y distance.
                vertexManager.setVertexTiming(convertTiming(vertex.transform.position.y));

                //calling calculateAngle with the vertices (sphere) x and z cordinates, and then setting the vertices note accordingly.
                float vertexAngle = calculateAngle(vertexManager.transform.position.x, vertexManager.transform.position.z);
                vertexManager.setVertexAngle(vertexAngle);
                vertexManager.setVertexNote(convertAngle(vertexAngle));
            }
        }
    }
Exemplo n.º 7
0
        /// <summary>
        /// Implement IDisposable.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            GraphicDevice.Handle.WaitForFences(InFlightFences.ToArray(), true, UInt64.MaxValue);

            // - Wait the GPU (we must operate only when GPU is idle)
            GraphicDevice.Handle.WaitIdle();

            // - Dispose render pass
            DefaultRenderPass.Dispose();

            // - Dispose the pipeline
            Pipeline.Dispose();

            // - Dipose current swapchain
            Swapchain.Dispose();

            // - Dispose vertex and index managers
            VertexManager.Dispose();
            IndexManager.Dispose();

            // - Release all VK shaders
            ShaderManager.Dispose();

            for (int i = 0; i < MaxFrameInFlight; ++i)
            {
                if (CommandBuffers[i] != null)
                {
                    foreach (var buffer in CommandBuffers[i])
                    {
                        buffer.Reset();
                    }
                }
            }

            foreach (CommandPool pool in Commands)
            {
                pool?.Destroy();
            }
            foreach (Fence fence in InFlightFences)
            {
                fence?.Destroy();
            }
            foreach (Semaphore sem in ImageAvailableSemaphores)
            {
                sem?.Destroy();
            }
            foreach (Semaphore sem in RenderFinishedSemaphores)
            {
                sem?.Destroy();
            }

            // - Dispose device
            GraphicDevice.Dispose();

            // - Dispose vulkan
            Library.Dispose();
        }
 //method used when letting go of an object (either voluntarily or forced)
 private void resetVariables()
 {
     fixedJoint.connectedBody = null;
     currentRigidBody         = null;
     currentVertexManager     = null;
     currentGameObject        = null;
     hoveringBoxColliders     = new List <GameObject>();
 }
Exemplo n.º 9
0
 /// <summary>
 /// 破棄します。
 /// </summary>
 protected override void DisposeResource()
 {
     if (vertexManager != null)
     {
         vertexManager.Dispose();
         vertexManager = null;
     }
 }
Exemplo n.º 10
0
    protected override void Awake()
    {
        base.Awake();

        _name          = "Planète Twippie";
        _planetManager = PlanetManager.Instance;
        _planetManager.Add(this);
        _vertexManager  = GetComponent <VertexManager>();
        _twippieManager = TwippieManager.Instance;
    }
    private void SetVertexColours()
    {
        // Pass colours to vertexManagers
        for (int i = 0; i < m_numMeshes; i++)
        {
            VertexManager vm            = m_VertexManagers[i];
            int           meshVertCount = vm.m_VertexIDs.Count * 4;
            vm.SetMeshCols(m_VertexColours.GetRange(MaxVertIndexPerMesh * i * 4, meshVertCount));

            //VertexManager vmOutline = m_OutlineVertexManagers[i];
            //vmOutline.SetMeshCols(m_OutlineColours.GetRange(MaxVertIndexPerMesh * i * 4, meshVertCount));
        }
    }
Exemplo n.º 12
0
    //Method used to remove a vertex from a line and return it back to the pool
    public void removeVertex(Vector3 pos, int vertexID, GameObject selectedVertex)
    {
        boxColliderManager.removeBoxCollider(vertexID);

        //if statement to detect whether the vertex being removed is the last in the line.
        if (vertexID == attachedLR.positionCount - 1)
        {
            //Lower the position count by 1 and return the object to the pool.
            attachedLR.positionCount -= 1;
            timingDict[selectedVertex.GetComponent <VertexManager>().getVertexTiming()].Remove(selectedVertex.GetComponent <VertexManager>());
            objectPooler.returnToPool("Vertex", selectedVertex);
        }
        else
        {
            //removing a vertex from the middle of a list
            //get the children of the lineBase and sort them
            List <GameObject> children = getChildrenVertices();
            children.Sort(sortByVertexID);

            //go through each vertex sphere that is a child of lineBase and lower it's vertexID by 1 if it is past the vertex being removed.
            foreach (GameObject child in children)
            {
                VertexManager childsVM = child.GetComponent <VertexManager>();
                if (childsVM.getVertexID() >= vertexID)
                {
                    childsVM.setVertexID(childsVM.getVertexID() - 1);
                }
            }

            //Translate the vector3 pos to take into account the position of the baseline object.
            pos = rotateVertex(pos, -getLocalRotation());

            //create a list of final positions that the line renderer vertices will be set too
            Vector3[] finalPositions = new Vector3[children.Count];
            for (int i = 0; i < children.Count; i++)
            {
                Vector3 tempPos = children[i].transform.position;
                tempPos           = rotateVertex(tempPos, -getLocalRotation());
                finalPositions[i] = tempPos;
            }

            //lower the number of vertices in the line renderer by 1, and set the remaining vertices to finalPositions
            attachedLR.positionCount -= 1;
            timingDict[selectedVertex.GetComponent <VertexManager>().getVertexTiming()].Remove(selectedVertex.GetComponent <VertexManager>());
            attachedLR.SetPositions(finalPositions);
            //return the removed vertex sphere back to the pool
            objectPooler.returnToPool("Vertex", selectedVertex);
        }
    }
Exemplo n.º 13
0
    protected override void Awake()
    {
        base.Awake();

        _objectManager = ObjetManager.Instance;
        _zoneManager   = ZoneManager.Instance;
        _vertexManager = VertexManager.Instance;
        _transform     = transform;

        VerticeIds   = new List <Guid>();
        NeighbourIds = new List <Guid>();
        PathCosts    = new Dictionary <Guid, PathCost>();
        Resources    = new List <Resource>();
        TwippieIds   = new List <Guid>();
        Col          = UnityEngine.Random.ColorHSV();
    }
    //remove this method???
    private Vector3 tetherToPoint(VertexManager vm, Vector3 currentPos)
    {
        float volume = vm.getVertexVolume();

        if (!vm.getParentsLineManager().checkIfTetheredForXZ(currentGameObject))
        {
            return(currentPos);
        }
        else
        {
            float m    = (currentPos.z / currentPos.x);
            float newX = (0.815f / (Mathf.Sqrt(Mathf.Pow(m, 2) + 1)));
            float newZ = newX * m;
            currentPos.Set(newX, currentPos.y, newZ);
            return(currentPos);
            //return currentPos.normalized*0.815f;
        }
    }
Exemplo n.º 15
0
    //Method used to call drawVert(...) multiple time with the given Vector3[] of vertices
    private void drawVerts(Vector3[] currentVerts)
    {
        int vertexID = 0;

        foreach (var vert in currentVerts)
        {
            VertexManager newVert = drawVert(vert, vertexID, true).GetComponent <VertexManager>();
            if (vertexID == 0)
            {
                newVert.setVertexTiming(-1);
            }
            else if (vertexID == getNumberOfVertices() - 1)
            {
                newVert.setVertexTiming(GridManager.getYSegments());
            }
            vertexID++;
        }
    }
 //method to see whether a vertex is currently close enough to the controller to be considered "hovering over"
 public GameObject hoverOverVertex()
 {
     if (GetNearestRigidBody())
     {
         GameObject nearestVertex       = GetNearestRigidBody().gameObject;
         Vector3    nearestVertexVector = nearestVertex.transform.position;
         if (Vector3.Distance(transform.position, nearestVertexVector) < 0.1f)
         {
             //is within range
             VertexManager nearestVertexManager = nearestVertex.GetComponent <VertexManager>();
             if (isEditable(nearestVertexManager.getVertexID(), nearestVertexManager.getBaseLineParent().gameObject))
             {
                 //is "editable"
                 return(nearestVertex);
             }
         }
     }
     return(null);
 }
    //method that is called when the controller should pick up the nearest rigid body
    public void pickUp()
    {
        currentRigidBody = GetNearestRigidBody();
        if (!currentRigidBody)
        {
            return;
        }
        else
        {
            //if statement checking the id of the vertex:
            if (currentRigidBody.GetComponent <VertexManager>().getBaseLineParent().GetComponent <LineManager>().getNumberOfVertices() - 1 == currentRigidBody.GetComponent <VertexManager>().getVertexID())
            {
                //if the id is the last in the line, cycle the voice of the line
                currentRigidBody.GetComponent <VertexManager>().getParentsLineManager().cycleVoices();
                resetVariables();
            }
            else
            {
                //set current-XYZ variables
                currentGameObject    = currentRigidBody.gameObject;
                currentVertexManager = currentRigidBody.GetComponent <VertexManager>();
                currentVertexManager.setIsSelected(true);


                Vector3 oldPos = currentGameObject.transform.position;

                //set the rigidBody parent and position to the controller holding it.
                currentRigidBody.transform.parent   = gameObject.transform;
                currentRigidBody.transform.position = transform.position;
                fixedJoint.connectedBody            = currentRigidBody;
                currentVertexManager.onPickUp();

                //if statement to check whether the id of the vertex is editable, if it isn't, act as if a new vertex should be made:
                if (!isEditable(currentVertexManager.getVertexID(), currentVertexManager.getBaseLineParent().gameObject))
                {
                    VertexManager newlyCreatedVertexManager = addNewVertex().GetComponent <VertexManager>();
                    newlyCreatedVertexManager.moveTo(oldPos);
                }
            }
        }
    }
    //method used to check if the current held vertex is going too low, too far from center, or too close to center.
    private void outOfBoundsCheck()
    {
        bool          outOfBounds       = false;
        int           r                 = 4;
        Vector3       pos               = transform.position;
        float         currentX          = pos.x;
        float         currentY          = pos.y;
        float         currentZ          = pos.z;
        VertexManager tempVertexManager = currentVertexManager;


        if (currentY <= 0.1)
        {
            //pos.Set(pos.x, 0.15f, pos.z);
            //letGo();
            //currentVertexManager.moveTo(pos);
            outOfBounds = true;
        }
        else if (Mathf.Sqrt(Mathf.Pow(currentX, 2) + Mathf.Pow(currentZ, 2)) > r)
        {
            float m    = (currentZ / currentX);
            float newX = ((r - 0.01f) / (Mathf.Sqrt(Mathf.Pow(m, 2) + 1)));
            float newZ = newX * m;
            pos.Set(newX, currentY, newZ);
            //letGo();
            tempVertexManager.moveTo(pos);
            outOfBounds = true;
            //return;
        }
        else if (checkSiblingHeights() != transform.position.y)
        {
            pos.y = checkSiblingHeights();
            tempVertexManager.moveTo(pos);
            outOfBounds = true;
        }
        if (!outOfBounds)
        {
            Vector3 tempPos = transform.position;
            tempVertexManager.moveTo(tempPos);
        }
    }
    //simple method for changing a hovered over vertices timing and y cordindate
    public void moveVertexDown()
    {
        GameObject nearestVertex = hoverOverVertex();

        if (nearestVertex)
        {
            VertexManager nearestVertexManager = nearestVertex.GetComponent <VertexManager>();
            float         nearestVertexTiming  = nearestVertexManager.getVertexTiming();

            float lowerSiblingY;
            float lowerSiblingTiming;
            nearestVertexManager.getLowerVertex(out lowerSiblingY, out lowerSiblingTiming);

            if (nearestVertexTiming <= GridManager.getYSegments() - 1 && nearestVertexTiming < lowerSiblingTiming)
            {
                Vector3 currentPos = nearestVertex.transform.position;
                Vector3 newPos     = new Vector3(currentPos.x, GridManager.getYFromTiming((int)nearestVertexTiming + 1), currentPos.z);
                nearestVertexManager.moveTo(newPos);
            }
        }
    }
    //simple method for changing a hovered over vertices timing and y cordindate
    public void moveVertexUp()
    {
        GameObject nearestVertex = hoverOverVertex();

        if (nearestVertex)
        {
            VertexManager nearestVertexManager = nearestVertex.GetComponent <VertexManager>();
            float         nearestVertexTiming  = nearestVertexManager.getVertexTiming();

            float higherSiblingY;
            float higherSiblingTiming;
            nearestVertexManager.getHigherVertex(out higherSiblingY, out higherSiblingTiming);

            if (nearestVertexTiming != 0 && nearestVertexTiming > higherSiblingTiming)
            {
                Vector3 currentPos = nearestVertex.transform.position;
                Vector3 newPos     = new Vector3(currentPos.x, GridManager.getYFromTiming((int)nearestVertexTiming - 1), currentPos.z);
                nearestVertexManager.moveTo(newPos);
            }
        }
    }
    //method used to return the nearest rigid body to the called of method
    private Rigidbody GetNearestRigidBody()
    {
        Rigidbody neartestRigidBody = null;
        float     minDistance       = float.MaxValue;
        float     distance          = 0.0f;

        foreach (Rigidbody contactBody in contactRigidBodies)
        {
            VertexManager vm = contactBody.gameObject.GetComponent <VertexManager>();
            //don't bother checking the position of contactBody if its ID is 0 as that vertex cannot be selected
            if (contactBody.gameObject.active && contactBody.gameObject.GetComponent <VertexManager>().getVertexID() >= 1)
            {
                distance = (contactBody.gameObject.transform.position - transform.position).sqrMagnitude;

                if (distance < minDistance)
                {
                    minDistance       = distance;
                    neartestRigidBody = contactBody;
                }
            }
        }
        return(neartestRigidBody);
    }
Exemplo n.º 22
0
 //update the timing dictionary by removing the vertex manager from the old key and inserting it into the new one.
 public void updateTimingDict(float oldTiming, float newTiming, VertexManager vm)
 {
     timingDict[oldTiming].Remove(vm);
     timingDict[newTiming].Add(vm);
 }
Exemplo n.º 23
0
 /// <summary>
 /// コンストラクタです。
 /// </summary>
 /// <param name="device"></param>
 public ShaderCommon(PPDDevice device)
 {
     vertexManager = new VertexManager(device);
 }
 //given a note, play it on Super Collider.
 private void playNote(GridManager.Notes note)
 {
     print(note);
     VertexManager.contactSC(note, 0.5f, 0.5f, "VoiceA");
 }
Exemplo n.º 25
0
    public void BuildLineMeshes()
    {
        // Clear any existing mesh objects
        for (int i = 0; i < m_LineModelObj.transform.childCount; i++)
        {
            Destroy(m_LineModelObj.transform.GetChild(i).gameObject);
        }

        numVerts = lines.Count;

        meshes    = new List <Mesh>();
        meshParts = new List <GameObject>();

        float lineWidth = 2.5f;

        int numMeshesRequired = (numVerts / ((MAX_VERTICES_PER_MESH / 4) - 1)) + 1;

        // Per mesh m
        for (int m = 0; m < numMeshesRequired; m++)
        {
            // Create mesh and vertecis, uv and triangles lists
            Mesh           mesh      = new Mesh();
            List <Vector3> vertices  = new List <Vector3>();
            List <Vector2> UVs       = new List <Vector2>();
            List <int>     triangles = new List <int>();

            // Create list of vert ids that will be in current mesh
            List <int> vs = new List <int>();

            int vertCounter = 0;

            // Calculate start and end vert indexes for current mesh
            int startInd = m * ((MAX_VERTICES_PER_MESH / 4) - 1);
            int endInd   = Mathf.Min(startInd + ((MAX_VERTICES_PER_MESH / 4) - 1), numVerts);

            // For each vert in this mesh (Square mode)
            for (int v = startInd; v < endInd - 1; v += 2)
            {
                // add vert indexes to current vs list
                vs.Add(v);
                vs.Add(v + 1);

                // Get start and end points of line
                Vector3 end   = lines[v];
                Vector3 start = lines[v + 1];

                // calculate normal and 'side' direction of line segment
                Vector3 normal = Vector3.Cross(start, end);
                Vector3 side   = Vector3.Cross(normal, end - start);
                side.Normalize();
                Vector3 side2 = Vector3.Normalize(Quaternion.AngleAxis(90, end - start) * side);


                // Create vectors for each corner of the Hexagonal mesh
                Vector3 a = start + side * (lineWidth / 2) - side2 * (lineWidth / 2);
                Vector3 b = start + side * (lineWidth / 2) + side2 * (lineWidth / 2);
                Vector3 c = start - side * (lineWidth / 2) + side2 * (lineWidth / 2);
                Vector3 d = start - side * (lineWidth / 2) - side2 * (lineWidth / 2);

                Vector3 e = end + side * (lineWidth / 2) - side2 * (lineWidth / 2);
                Vector3 f = end + side * (lineWidth / 2) + side2 * (lineWidth / 2);
                Vector3 g = end - side * (lineWidth / 2) + side2 * (lineWidth / 2);
                Vector3 h = end - side * (lineWidth / 2) - side2 * (lineWidth / 2);

                // add vectors to vertices list
                vertices.Add(a);
                vertices.Add(b);
                vertices.Add(c);
                vertices.Add(d);
                vertices.Add(e);
                vertices.Add(f);
                vertices.Add(g);
                vertices.Add(h);

                // Add uvs for these 8 vectors
                UVs.Add(new Vector2(vertices[vertCounter].x, vertices[vertCounter].z));
                UVs.Add(new Vector2(vertices[vertCounter + 1].x, vertices[vertCounter + 1].z));
                UVs.Add(new Vector2(vertices[vertCounter + 2].x, vertices[vertCounter + 2].z));
                UVs.Add(new Vector2(vertices[vertCounter + 3].x, vertices[vertCounter + 3].z));
                UVs.Add(new Vector2(vertices[vertCounter + 4].x, vertices[vertCounter + 4].z));
                UVs.Add(new Vector2(vertices[vertCounter + 5].x, vertices[vertCounter + 5].z));
                UVs.Add(new Vector2(vertices[vertCounter + 6].x, vertices[vertCounter + 6].z));
                UVs.Add(new Vector2(vertices[vertCounter + 7].x, vertices[vertCounter + 7].z));

                // Add triangles for these 12 vectors
                triangles.Add(vertCounter);
                triangles.Add(vertCounter + 1);
                triangles.Add(vertCounter + 4);

                triangles.Add(vertCounter + 1);
                triangles.Add(vertCounter + 5);
                triangles.Add(vertCounter + 4);


                triangles.Add(vertCounter + 1);
                triangles.Add(vertCounter + 2);
                triangles.Add(vertCounter + 5);


                triangles.Add(vertCounter + 2);
                triangles.Add(vertCounter + 6);
                triangles.Add(vertCounter + 5);


                triangles.Add(vertCounter + 2);
                triangles.Add(vertCounter + 3);
                triangles.Add(vertCounter + 6);


                triangles.Add(vertCounter + 3);
                triangles.Add(vertCounter + 7);
                triangles.Add(vertCounter + 6);


                triangles.Add(vertCounter + 3);
                triangles.Add(vertCounter);
                triangles.Add(vertCounter + 7);


                triangles.Add(vertCounter);
                triangles.Add(vertCounter + 4);
                triangles.Add(vertCounter + 7);



                // Increment vert counter
                vertCounter += 8;
            }



            /* Rectange mode
             * for (int i = startInd; i < endInd - 1; i += 2)
             * {
             *  // add vert indexes to current vs list
             *  vs.Add(i);
             *  vs.Add(i + 1);
             *
             *  // Get start and end points of line
             *  Vector3 end = lines[i];
             *  Vector3 start = lines[i + 1];
             *
             *  // calculate normal and 'side' direction of line segment
             *  Vector3 normal = Vector3.Cross(start, end);
             *  Vector3 side = Vector3.Cross(normal, end - start);
             *  side.Normalize();
             *
             *  // Create vectors for each corner of the line segment
             *  Vector3 a = start + side * (lineWidth / 2);
             *  Vector3 b = start + side * (lineWidth / -2);
             *  Vector3 c = end + side * (lineWidth / 2);
             *  Vector3 d = end + side * (lineWidth / -2);
             *
             *  // add vectors to vertices list
             *  vertices.Add(a);
             *  vertices.Add(b);
             *  vertices.Add(c);
             *  vertices.Add(d);
             *
             *  // Add uvs for these 4 vectors
             *
             *  UVs.Add(new Vector2(vertices[vertCounter].x, vertices[vertCounter].z));
             *  UVs.Add(new Vector2(vertices[vertCounter + 1].x, vertices[vertCounter + 1].z));
             *  UVs.Add(new Vector2(vertices[vertCounter + 2].x, vertices[vertCounter + 2].z));
             *  UVs.Add(new Vector2(vertices[vertCounter + 3].x, vertices[vertCounter + 3].z));
             *
             *  // Add triangles for these 4 vectors
             *  triangles.Add(vertCounter);
             *  triangles.Add(vertCounter + 2);
             *  triangles.Add(vertCounter + 1);
             *
             *  triangles.Add(vertCounter + 1);
             *  triangles.Add(vertCounter + 2);
             *  triangles.Add(vertCounter + 3);
             *
             *  // Increment vert counter
             *  vertCounter += 4;
             * }
             */

            // Add arrays to mesh object
            mesh.vertices  = vertices.ToArray();
            mesh.triangles = triangles.ToArray();
            mesh.uv        = UVs.ToArray();
            mesh.RecalculateNormals();


            //UnityEditor.AssetDatabase.CreateAsset(mesh, "Assets/FullCortexModel/LineSquare/MeshPartSquare__" + m + ".asset");

            // Create lineSeg object
            GameObject lineSeg = Instantiate(m_LineSegPrefab);
            lineSeg.transform.SetParent(m_LineModelObj.transform);
            // Reset lineSeg object's transform
            lineSeg.transform.localScale    = new Vector3(1, 1, 1);
            lineSeg.transform.localPosition = Vector3.zero;
            // Set mesh
            lineSeg.GetComponent <MeshFilter>().mesh = mesh;

            // Set data in VertexData script on lineSeg
            VertexManager vd = lineSeg.GetComponent <VertexManager>();
            if (vd)
            {
                vd.m_MeshID    = m;
                vd.m_VertexIDs = vs;
            }

            meshes.Add(mesh);
            meshParts.Add(lineSeg);
        }

        //PrefabUtility.ReplacePrefab(m_LineModelObj, m_lineModelPrefab, ReplacePrefabOptions.ConnectToPrefab);

        MeshInfo meshInf = new MeshInfo();

        meshInf.numVerts  = numVerts;
        meshInf.numMeshes = meshes.Count;

        m_meshInfo = meshInf;
        m_buildRun = true;

        MeshData.SaveMeshInfo(meshInf);
    }
Exemplo n.º 26
0
 private void Awake()
 {
     _vertexManager = GetComponent <VertexManager>();
     Planet         = GetComponent <Planet>();
     Colors         = new Color[_nbVertex];
 }
Exemplo n.º 27
0
    //method called by pulse manager to calculate a pulse should be on this line renderer. (and for creating new lead on pulses)
    public Vector3 interpole(float height, bool playVertex)
    {
        float lowerBoundTiming = float.MinValue;
        float upperBoundTiming = float.MaxValue;
        int   lowerBoundIndex  = 0;
        int   upperBoundIndex  = 0;
        int   flooredHeight    = Mathf.FloorToInt(height);

        //get all of the children, even ones attached to controllers.
        List <GameObject> childrenVertices = getAllChildrenVerticesForInterpole();

        childrenVertices.Sort(sortByVertexID);
        //first 1/3 of method used for deducing which 2 vertices the pulse should be between based on a given height.

        foreach (GameObject Vertex in childrenVertices)
        {
            VertexManager currentVertexManager = Vertex.GetComponent <VertexManager>();
            if (currentVertexManager.getVertexTiming() >= lowerBoundTiming && currentVertexManager.getVertexTiming() <= height)
            {
                lowerBoundTiming = currentVertexManager.getVertexTiming();
                lowerBoundIndex  = currentVertexManager.getVertexID();
            }
            if (currentVertexManager.getVertexTiming() < upperBoundTiming && currentVertexManager.getVertexTiming() > height && currentVertexManager.getVertexTiming() != upperBoundTiming)
            {
                upperBoundTiming = currentVertexManager.getVertexTiming();
                upperBoundIndex  = currentVertexManager.getVertexID();
            }
        }

        if (lastHeight > flooredHeight && flooredHeight == 0)
        {
            if (playVertex)
            {
                foreach (VertexManager vm in timingDict[0])
                {
                    vm.playVertex();
                }
            }
        }
        else if (lastHeight < flooredHeight)
        {
            float diffOfHeights = flooredHeight - lastHeight;
            if (playVertex && flooredHeight < GridManager.getYSegments() - 1)
            {
                foreach (VertexManager vm in timingDict[flooredHeight])
                {
                    vm.playVertex();
                }
            }
        }

        if (flooredHeight != -1)
        {
            lastHeight = flooredHeight;
        }

        float difference   = upperBoundTiming - lowerBoundTiming;
        float segment      = 1 / difference;
        float leftover     = height - lowerBoundTiming;
        int   numberOfDivs = Mathf.FloorToInt(leftover);
        float t            = (numberOfDivs * segment) + ((leftover % 1) / difference);

        if (flooredHeight == -1)
        {
            //lead on pulse:
            return(Vector3.Lerp(PulseTranslation(attachedLR.GetPosition(0)), PulseTranslation(attachedLR.GetPosition(1)), 1 - (height * -1)));
        }
        else
        {
            return(Vector3.Lerp(PulseTranslation(attachedLR.GetPosition(lowerBoundIndex)), PulseTranslation(attachedLR.GetPosition(upperBoundIndex)), t));
        }
    }
Exemplo n.º 28
0
 // Start is called before the first frame update
 void Start()
 {
     instance = this;
     graph    = FindObjectOfType <Graph>();
 }
Exemplo n.º 29
0
        /// <summary>
        /// Render a set of asssets on the screen.
        /// </summary>
        public override void Render(Asset[] assets)
        {
            base.Render(assets);


            CommandBuffers[CurrentFrame] = GraphicDevice.Handle.AllocateCommandBuffers(Commands[CurrentFrame], CommandBufferLevel.Primary, (uint)Swapchain.Images.Count());


            for (int index = 0; index < Swapchain.Images.Count(); index++)
            {
                var commandBuffer = CommandBuffers[CurrentFrame][index];

                commandBuffer.Begin(CommandBufferUsageFlags.SimultaneousUse);

                commandBuffer.BeginRenderPass(DefaultRenderPass.Handle, Swapchain.VideoBuffers[index].Handler, new Rect2D(Swapchain.SurfaceSize), (ClearValue)(0F, 1F, 0F, 1F), SubpassContents.Inline);

                if (assets != null)
                {
                    foreach (Asset asset in assets)
                    {
                        // - Gets the mesh from the mesh store
                        var mesh = GeometryDispatcher.Get(asset.Mesh);

                        VertexManager.Bind(commandBuffer);

                        IndexManager.Bind(commandBuffer, (int)mesh.Indexes.Offset);

                        commandBuffer.BindPipeline(PipelineBindPoint.Graphics, Pipeline.PipelineInstance);

                        commandBuffer.DrawIndexed((uint)mesh.Indexes.Count, (uint)mesh.Indexes.Count / 3, 0, 0, 0);
                    }
                }

                commandBuffer.EndRenderPass();

                commandBuffer.End();
            }


            uint nextImage = Swapchain.Handle.AcquireNextImage(uint.MaxValue, ImageAvailableSemaphores[CurrentFrame], null);

            if (ImagesInFlight[(int)nextImage] != null)
            {
                GraphicDevice.Handle.WaitForFences(ImagesInFlight[(int)nextImage], true, UInt64.MaxValue);
            }

            // - Mark the image as now being in use by this frame
            ImagesInFlight[(int)nextImage] = InFlightFences[CurrentFrame];

            try
            {
                GraphicDevice.Handle.ResetFences(InFlightFences[CurrentFrame]);

                GraphicDevice.GraphicQueue.Submit
                (
                    new SubmitInfo
                {
                    CommandBuffers           = new[] { CommandBuffers[CurrentFrame][nextImage] },
                    SignalSemaphores         = new[] { RenderFinishedSemaphores[CurrentFrame] },
                    WaitDestinationStageMask = new[] { PipelineStageFlags.ColorAttachmentOutput },
                    WaitSemaphores           = new[] { ImageAvailableSemaphores[CurrentFrame] }
                },
                    InFlightFences[CurrentFrame]
                );
            }
            catch (DeviceLostException)
            {
                InvalidateDevice();
            }

            try
            {
                var present = GraphicDevice.PresentQueue.Present(RenderFinishedSemaphores[CurrentFrame], Swapchain.Handle, nextImage, new Result[1]);

                switch (present)
                {
                case Result.Suboptimal:
                    InvalidateGraphics();
                    break;
                }

                if (present == Result.Success)
                {
                    GraphicDevice.Handle.WaitForFences(InFlightFences[CurrentFrame], true, UInt64.MaxValue);
                    Commands[(CurrentFrame + 1) % MaxFrameInFlight].FreeCommandBuffers(CommandBuffers[(CurrentFrame + 1) % MaxFrameInFlight]);
                    CommandBuffers[(CurrentFrame + 1) % MaxFrameInFlight] = null;
                }
            }
            catch
            {
                InvalidateGraphics();
            }
            finally
            {
            }

            CurrentFrame = (CurrentFrame + 1) % MaxFrameInFlight;
        }
Exemplo n.º 30
0
        /// <summary>
        ///
        /// </summary>
        public override void LoadAttachments(IEnumerable <Resource.IDescriptor> resources)
        {
            // - Skip buffer creation if no resources to load
            if (resources.Count() <= 0)
            {
                return;
            }

            // - Creates a command buffer for data transfer
            var commands = GraphicDevice.Handle.AllocateCommandBuffer(Commands[0], CommandBufferLevel.Primary);

            commands.Begin(CommandBufferUsageFlags.OneTimeSubmit);

            foreach (Resource.IDescriptor res in resources)
            {
                switch (res)
                {
                case Shape.Descriptor shape:

                    // - Loads the geometry
                    Geometry pointer = GeometryDispatcher.Load(shape);

                    // - Set resource loaded in the source thread
                    shape.SourceScheduler.Add(() =>
                    {
                        shape.SetResource(pointer);
                        shape.SetState(Resource.State.Loaded);
                    });

                    break;

                default:
                    throw new Exception($"Resource {res.GetType().Name} does not has a loader.");
                }
            }

            {
                // - Upload invalidated vertexs
                VertexManager.Upload(commands, 1000);

                // - Upload invalidated indexes
                IndexManager.Upload(commands, 1000);
            }
            commands.End();

            // - Perform all attachment operations
            GraphicDevice.GraphicQueue.Submit
            (
                new SubmitInfo
            {
                CommandBuffers = new[] { commands }
            },
                null
            );

            // - Free attachment command buffer
            Commands[0].FreeCommandBuffers(commands);

            // - Wait the GPU (we must operate only when GPU is idle)
            GraphicDevice.Handle.WaitIdle();
        }